diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..269f41649159832efcb833cb6dfb8a11afb8259c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/METADATA @@ -0,0 +1,141 @@ +Metadata-Version: 2.4 +Name: setuptools +Version: 82.0.0 +Summary: Easily download, build, install, upgrade, and uninstall Python packages +Author-email: Python Packaging Authority +License-Expression: MIT +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: 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.13.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.18.*; 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..94370a77e9255b6f13d4c7563032630c7a384eff --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/RECORD @@ -0,0 +1,760 @@ +_distutils_hack/__init__.py,sha256=34HmvLo07j45Uvd2VR-2aRQ7lJD91sTK6zJgn5fphbQ,6755 +_distutils_hack/__pycache__/__init__.cpython-311.pyc,, +_distutils_hack/__pycache__/override.cpython-311.pyc,, +_distutils_hack/override.py,sha256=Eu_s-NF6VIZ4Cqd0tbbA5wtWky2IZPNd8et6GLt1mzo,44 +distutils-precedence.pth,sha256=JjjOniUA5XKl4N5_rtZmHrVp0baW_LoHsN0iPaX10iQ,151 +setuptools-82.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +setuptools-82.0.0.dist-info/METADATA,sha256=rH6S0y76F6DYVMvMvpwyRPfKpeVjOzLxof3h2iaukV8,6573 +setuptools-82.0.0.dist-info/RECORD,, +setuptools-82.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools-82.0.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91 +setuptools-82.0.0.dist-info/entry_points.txt,sha256=zkgthpf_Fa9NVE9p6FKT3Xk9DR1faAcRU4coggsV7jA,2449 +setuptools-82.0.0.dist-info/licenses/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools-82.0.0.dist-info/top_level.txt,sha256=Wsln-wPBdc8NXLNXsnCRyTXUhGi0mUw_l0ZVThaim-I,27 +setuptools/__init__.py,sha256=-UtTG9pdeEZkYiIFT69RckMCqxUdVILjj24g3qeJ_rc,9521 +setuptools/__pycache__/__init__.cpython-311.pyc,, +setuptools/__pycache__/_core_metadata.cpython-311.pyc,, +setuptools/__pycache__/_discovery.cpython-311.pyc,, +setuptools/__pycache__/_entry_points.cpython-311.pyc,, +setuptools/__pycache__/_imp.cpython-311.pyc,, +setuptools/__pycache__/_importlib.cpython-311.pyc,, +setuptools/__pycache__/_itertools.cpython-311.pyc,, +setuptools/__pycache__/_normalization.cpython-311.pyc,, +setuptools/__pycache__/_path.cpython-311.pyc,, +setuptools/__pycache__/_reqs.cpython-311.pyc,, +setuptools/__pycache__/_scripts.cpython-311.pyc,, +setuptools/__pycache__/_shutil.cpython-311.pyc,, +setuptools/__pycache__/_static.cpython-311.pyc,, +setuptools/__pycache__/archive_util.cpython-311.pyc,, +setuptools/__pycache__/build_meta.cpython-311.pyc,, +setuptools/__pycache__/depends.cpython-311.pyc,, +setuptools/__pycache__/discovery.cpython-311.pyc,, +setuptools/__pycache__/dist.cpython-311.pyc,, +setuptools/__pycache__/errors.cpython-311.pyc,, +setuptools/__pycache__/extension.cpython-311.pyc,, +setuptools/__pycache__/glob.cpython-311.pyc,, +setuptools/__pycache__/installer.cpython-311.pyc,, +setuptools/__pycache__/launch.cpython-311.pyc,, +setuptools/__pycache__/logging.cpython-311.pyc,, +setuptools/__pycache__/modified.cpython-311.pyc,, +setuptools/__pycache__/monkey.cpython-311.pyc,, +setuptools/__pycache__/msvc.cpython-311.pyc,, +setuptools/__pycache__/namespaces.cpython-311.pyc,, +setuptools/__pycache__/unicode_utils.cpython-311.pyc,, +setuptools/__pycache__/version.cpython-311.pyc,, +setuptools/__pycache__/warnings.cpython-311.pyc,, +setuptools/__pycache__/wheel.cpython-311.pyc,, +setuptools/__pycache__/windows_support.cpython-311.pyc,, +setuptools/_core_metadata.py,sha256=T7Tjp-WSoN881adev3R1wzXCPnkDHqbC2MgylN1yjS8,11978 +setuptools/_discovery.py,sha256=HxEpgYQ8zUaLOOSp8JIA4y2Mdvn9ysVxspPT-ppfzM4,836 +setuptools/_distutils/__init__.py,sha256=xGYuhWwLG07J0Q49BVnEjPy6wyDcd6veJMDJX7ljlyM,359 +setuptools/_distutils/__pycache__/__init__.cpython-311.pyc,, +setuptools/_distutils/__pycache__/_log.cpython-311.pyc,, +setuptools/_distutils/__pycache__/_macos_compat.cpython-311.pyc,, +setuptools/_distutils/__pycache__/_modified.cpython-311.pyc,, +setuptools/_distutils/__pycache__/_msvccompiler.cpython-311.pyc,, +setuptools/_distutils/__pycache__/archive_util.cpython-311.pyc,, +setuptools/_distutils/__pycache__/ccompiler.cpython-311.pyc,, +setuptools/_distutils/__pycache__/cmd.cpython-311.pyc,, +setuptools/_distutils/__pycache__/core.cpython-311.pyc,, +setuptools/_distutils/__pycache__/cygwinccompiler.cpython-311.pyc,, +setuptools/_distutils/__pycache__/debug.cpython-311.pyc,, +setuptools/_distutils/__pycache__/dep_util.cpython-311.pyc,, +setuptools/_distutils/__pycache__/dir_util.cpython-311.pyc,, +setuptools/_distutils/__pycache__/dist.cpython-311.pyc,, +setuptools/_distutils/__pycache__/errors.cpython-311.pyc,, +setuptools/_distutils/__pycache__/extension.cpython-311.pyc,, +setuptools/_distutils/__pycache__/fancy_getopt.cpython-311.pyc,, +setuptools/_distutils/__pycache__/file_util.cpython-311.pyc,, +setuptools/_distutils/__pycache__/filelist.cpython-311.pyc,, +setuptools/_distutils/__pycache__/log.cpython-311.pyc,, +setuptools/_distutils/__pycache__/spawn.cpython-311.pyc,, +setuptools/_distutils/__pycache__/sysconfig.cpython-311.pyc,, +setuptools/_distutils/__pycache__/text_file.cpython-311.pyc,, +setuptools/_distutils/__pycache__/unixccompiler.cpython-311.pyc,, +setuptools/_distutils/__pycache__/util.cpython-311.pyc,, +setuptools/_distutils/__pycache__/version.cpython-311.pyc,, +setuptools/_distutils/__pycache__/versionpredicate.cpython-311.pyc,, +setuptools/_distutils/__pycache__/zosccompiler.cpython-311.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=dDZjw4BwhNIyt20hHlrIely4WSiN20HVTGdaPRKGI0o,8484 +setuptools/_distutils/ccompiler.py,sha256=FKVjqzGJ7c-FtouNjhLiaMPm5LKMZHHAruXf8LU216c,524 +setuptools/_distutils/cmd.py,sha256=lzqM-3rwYJNUhJiCYOv04aeUPenym2vyOndFPEOdZgo,21344 +setuptools/_distutils/command/__init__.py,sha256=GfFAzbBqk1qxSH4BdaKioKS4hRRnD44BAmwEN85C4u8,386 +setuptools/_distutils/command/__pycache__/__init__.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/_framework_compat.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/bdist.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/bdist_dumb.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/bdist_rpm.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/build.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/build_clib.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/build_ext.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/build_py.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/build_scripts.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/check.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/clean.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/config.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/install.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/install_data.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/install_egg_info.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/install_headers.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/install_lib.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/install_scripts.cpython-311.pyc,, +setuptools/_distutils/command/__pycache__/sdist.cpython-311.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=FF0FpuC3IgFpOjJ1ub3hGU5ERFMBnJOiUjrAI-u4auw,4609 +setuptools/_distutils/command/bdist_rpm.py,sha256=WRRB3k65qubgZO6zwiRMpaEEuG391mju_iJDRJTPvT8,21672 +setuptools/_distutils/command/build.py,sha256=SpHlagf0iNaKVyIhxDfhPFZ8X1-LAWOCQACy-yt2K0w,5923 +setuptools/_distutils/command/build_clib.py,sha256=6u-R8qjmWr6FPECuzDoAyVl1xRBtuEmXJZ2cz2Zk2zg,7733 +setuptools/_distutils/command/build_ext.py,sha256=vnInlUvOVbCS7eCpp3ThqTY4NkQ7WBHcmsROGn8upKw,32676 +setuptools/_distutils/command/build_py.py,sha256=BAJI_X9QlfiTyokU3ZgfDnsy3Xn6aWdxl2T_lToagbk,16606 +setuptools/_distutils/command/build_scripts.py,sha256=UKhGKyXLjGCAQoQVfP2t-DnlMaUVjcXWac6UCs6GWMI,4833 +setuptools/_distutils/command/check.py,sha256=yoNe2MPY4JcTM7rwoIQdfZ75q5Ri058I2coi-Gq9CjM,4946 +setuptools/_distutils/command/clean.py,sha256=UWkfAMmpOZGl0_PjiZJFdyLV2yzGnoimygF8fka907I,2551 +setuptools/_distutils/command/config.py,sha256=zE7F8mSQavwiZwNZj8WtrF6T92lt-K1dUNq9rYIQpgc,12206 +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=0tJ0AqFr8P1bf5wFH9eO7ssx1G3_SLhO9bCbWN-h0f4,2809 +setuptools/_distutils/command/install_headers.py,sha256=5ciKCj8c3XKsYNKdkdMvnypaUCKcoWCDeeZij3fD-Z4,1272 +setuptools/_distutils/command/install_lib.py,sha256=3VQc5P06dv-1QVl8G-raVpTD-bMlPTj1c3NE7adJiyk,8512 +setuptools/_distutils/command/install_scripts.py,sha256=CTzga_-kEjYWguL-Dg_GP83Jax6uw2VnFFwlR8XoAls,1877 +setuptools/_distutils/command/sdist.py,sha256=XGEO5UMznLzPT-F3ftbryqkMsMWLKd15tjObiZJsm8k,19107 +setuptools/_distutils/compat/__init__.py,sha256=J20aXGjJ86Rg41xFLIWlcWCgZ9edMdJ9vvdNEQ87vPQ,522 +setuptools/_distutils/compat/__pycache__/__init__.cpython-311.pyc,, +setuptools/_distutils/compat/__pycache__/numpy.cpython-311.pyc,, +setuptools/_distutils/compat/__pycache__/py39.cpython-311.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-311.pyc,, +setuptools/_distutils/compilers/C/__pycache__/cygwin.cpython-311.pyc,, +setuptools/_distutils/compilers/C/__pycache__/errors.cpython-311.pyc,, +setuptools/_distutils/compilers/C/__pycache__/msvc.cpython-311.pyc,, +setuptools/_distutils/compilers/C/__pycache__/unix.cpython-311.pyc,, +setuptools/_distutils/compilers/C/__pycache__/zos.cpython-311.pyc,, +setuptools/_distutils/compilers/C/base.py,sha256=0b6_nCJiQtmUkdxL6tFKxVx8vv8AkLZOfRkIS2zGXCc,54550 +setuptools/_distutils/compilers/C/cygwin.py,sha256=QFW4oBPylt6-uR4mdrXbFtGMQQ_mXJ4gB0qPUklbMWQ,11802 +setuptools/_distutils/compilers/C/errors.py,sha256=sKOVzJajMUmNdfywo9UM_QQGsKFcclDhtI5TlCiXMLc,573 +setuptools/_distutils/compilers/C/msvc.py,sha256=c-12nYp2XpD-fUvxfgd559rWZqmmRx9f9mWFwWTsoP4,21386 +setuptools/_distutils/compilers/C/tests/__pycache__/test_base.cpython-311.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_cygwin.cpython-311.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_mingw.cpython-311.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_msvc.cpython-311.pyc,, +setuptools/_distutils/compilers/C/tests/__pycache__/test_unix.cpython-311.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=AyadWw1fR-UeDl2TvIbYBzOJVHkpE_oRRQ3JTJWqaEA,14642 +setuptools/_distutils/compilers/C/unix.py,sha256=YH-y9g_pjBFjaJyHJQkDEBQ7q4D20I2-cWJNdgw-Yho,16531 +setuptools/_distutils/compilers/C/zos.py,sha256=WnGA_PR51_FP89wKbl85_2rcLA28BIKbeG5rPZ7JUig,6568 +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=1i-puqc3g8sTggEPX6NSuqNtGSNEdSy-Qw9qQfC3PSo,6864 +setuptools/_distutils/dist.py,sha256=kPQ81tTJdZikPayJ7OIunkFAh-m8-YqjbpQYQSuMTeI,55699 +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=O3hNtKxcs4jhCdOtGN23wIrLSvMwoRmMV2caEeXbvdU,7811 +setuptools/_distutils/filelist.py,sha256=MBeSRJmPcKmDv8ooZgSU4BiQPZ0Khwv8l_jhD50XycI,15337 +setuptools/_distutils/log.py,sha256=VyBs5j7z4-K6XTEEBThUc9HyMpoPLGtQpERqbz5ylww,1200 +setuptools/_distutils/spawn.py,sha256=sPnZ3Q3gsBzNBB2zsbfFxzkHJ-AveB6lyK9YqBHQiIw,3963 +setuptools/_distutils/sysconfig.py,sha256=KeI8OHbMuEzHJ8Q0cBez9KZny8iRy6Z6Y0AkMz1jlsU,19728 +setuptools/_distutils/tests/__init__.py,sha256=j-IoPZEtQv3EOPuqNTwalr6GLyRjzCC-OOaNvZzmHsI,1485 +setuptools/_distutils/tests/__pycache__/__init__.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/support.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_archive_util.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist_dumb.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_bdist_rpm.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_build.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_clib.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_ext.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_py.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_build_scripts.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_check.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_clean.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_cmd.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_config_cmd.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_core.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_dir_util.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_dist.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_extension.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_file_util.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_filelist.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_install.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_data.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_headers.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_lib.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_install_scripts.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_log.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_modified.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_sdist.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_spawn.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_sysconfig.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_text_file.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_util.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_version.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/test_versionpredicate.cpython-311.pyc,, +setuptools/_distutils/tests/__pycache__/unix_compat.cpython-311.pyc,, +setuptools/_distutils/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_distutils/tests/compat/__pycache__/__init__.cpython-311.pyc,, +setuptools/_distutils/tests/compat/__pycache__/py39.cpython-311.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=VaXLjV8kup-Z6rIVXCBW7u21pubcAH_R3hEtSmS81Xs,11441 +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=iGaXP9t2-SQo7vaDR7bKUoEbrGO5QN69xTEtS5eihvk,17534 +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=10TjbzfGdqWGH06lQuPPGDDci-OnXoIzrfpIWba5AZw,2468 +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=1H0YXdCuVkUcNX2zQqDyqa-4eWC8VI5vWjGGsbj7n8I,5798 +setuptools/_path.py,sha256=2Bv1q9_Hrd4oizKwcH3pv_05YVR6meovQE6ZtyD45yI,2976 +setuptools/_reqs.py,sha256=RRX-qYsz_fy6K66XchCHcIszK3bSAtU6aO1s3ZaLV14,1380 +setuptools/_scripts.py,sha256=5TrIWDVOuO3cRcfzcZAUBKPRH7K4svQRdQLZKKiD1bQ,11247 +setuptools/_shutil.py,sha256=IQQ1gcPX4X_wPilYGJGxChyMCqG43VOejoQZTIrCTY8,1578 +setuptools/_static.py,sha256=GTR79gESF1_JaK4trLkpDrEuCeEtPlwQW0MRv7VNQX4,4855 +setuptools/_vendor/.lock,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +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=K-5gcsvOxjkMVxB8jfywQikYqY7NtaLMNiGH8T1C6W8,1072 +setuptools/_vendor/autocommand-2.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +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-311.pyc,, +setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-311.pyc,, +setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-311.pyc,, +setuptools/_vendor/autocommand/__pycache__/automain.cpython-311.pyc,, +setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-311.pyc,, +setuptools/_vendor/autocommand/__pycache__/errors.cpython-311.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=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +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=D2nbcZtUIg1qSt_4v7BKyYr_6j3ItUBUoaeHoXVn9NE,1056 +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-311.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-311.pyc,, +setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-311.pyc,, +setuptools/_vendor/backports/tarfile/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-311.pyc,, +setuptools/_vendor/backports/tarfile/compat/py38.py,sha256=iYkyt_gvWjLzGUTJD9TuTfMMjOk-ersXZmRlvQYN2qE,568 +setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATA,sha256=o-OLnuQyYonUhkcE8w4pnudp4jCc6fSnXw3hpQrQo1Y,4670 +setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORD,sha256=Uqa47g3hXPf9mWJfQ7l80uOUKshvFgVOqQ3kjmbyk1U,1868 +setuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSE,sha256=RYUC4S2Xu_ZEOGBqIARKqF6wX7CoqAe7NdvsJT_R_AQ,10278 +setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19 +setuptools/_vendor/importlib_metadata/__init__.py,sha256=u7Ew4-UkpzNY-ka6k-WRkDhQZS1akkLMfWs2eEnUmGo,37734 +setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/_typing.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/_adapters.py,sha256=r5i8XLrKT6xmrpoREZhZrfczOYDmrVZeJBW5u0HzIGU,3797 +setuptools/_vendor/importlib_metadata/_collections.py,sha256=CxAhzlF3g1rwu_fMiB53JtRQiUFh0RgiMpoOvmK_ocg,760 +setuptools/_vendor/importlib_metadata/_compat.py,sha256=VC5ZDLlT-BcshauCShdFJvMNLntJJfZzNK1meGa-enw,1313 +setuptools/_vendor/importlib_metadata/_functools.py,sha256=0pA2OoiVK6wnsGq8HvVIzgdkvLiZ0nfnfw7IsndjoHk,3510 +setuptools/_vendor/importlib_metadata/_itertools.py,sha256=nMvp9SfHAQ_JYwK4L2i64lr3GRXGlYlikGTVzWbys_E,5351 +setuptools/_vendor/importlib_metadata/_meta.py,sha256=EtHyiJ5kGzWFDfKyQ2XQp6Vu113CeadKW1Vf6aGc1B4,1765 +setuptools/_vendor/importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166 +setuptools/_vendor/importlib_metadata/_typing.py,sha256=EQKhhsEgz_Sa-FnePI-faC72rNOOQwopjA1i5pG8FDU,367 +setuptools/_vendor/importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-311.pyc,, +setuptools/_vendor/importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608 +setuptools/_vendor/importlib_metadata/compat/py39.py,sha256=J3W7PUVRPNYMmcvT12RF8ndBU9e8_T0Ac4U87Bsrq70,1187 +setuptools/_vendor/importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379 +setuptools/_vendor/importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATA,sha256=XC_QkBLJVPE5sQYkl41TNaZUw0AUzQb29GbKaD28nFY,3731 +setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORD,sha256=Y7k2wwjQ_L4TkOgkVnzAB1NsMqhJrbAieOlfHUxzbDE,1157 +setuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEEL,sha256=Wyh-_nZ0DJYolHNn1_hMa4lM7uDedD_RGVwbmTjyItk,91 +setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco/context/__init__.py,sha256=br1ydYGo1Xr_Pu1anuEdd-QrjUiz_EY5L_5E4C03L4w,9809 +setuptools/_vendor/jaraco/context/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/jaraco/context/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco/functools/__init__.py,sha256=ZJx9cMs2Nvk2xGUl8OjVGkpjdOaNlSzJrN4dGglgX2g,18599 +setuptools/_vendor/jaraco/functools/__init__.pyi,sha256=K4DcbnYIHE5QlMxqf9-cVp-WhycrhuTao4J7O7TMq4Y,3907 +setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-311.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=lazNYXo8IhOR1bFigLAyGiiQao6jtO3KGWh8bZZPx3c,16762 +setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-311.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-311.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-311.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-311.pyc,, +setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-311.pyc,, +setuptools/_vendor/jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643 +setuptools/_vendor/jaraco/text/show-newlines.py,sha256=jT0vp4gLhG20hX2lTB-zKo_i3NgKzj79yRAdz4eMzIM,903 +setuptools/_vendor/jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412 +setuptools/_vendor/jaraco/text/to-dvorak.py,sha256=36nPPsiifwv6RfpAb--3zpgbIx8ohnnI1aR29IJTO9s,118 +setuptools/_vendor/jaraco/text/to-qwerty.py,sha256=IQoFY9v7vLTEybcput4KBYm_5GR35pmtgZ_xyrmdTgI,118 +setuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATA,sha256=BDXr_FIFXFqZdO0gwXG2RUOD6vnbsVCIFLp62XxZ1xI,4270 +setuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORD,sha256=RZnYds60K37vA6o54jXE6-q2rqJAnb5jRJaFI5PR-Dc,777 +setuptools/_vendor/jaraco_context-6.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +setuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSE,sha256=l1WhhRlmbl8PTK49qtPXASvK5IpgCzEjfXXp_hNOZoM,1076 +setuptools/_vendor/jaraco_context-6.1.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATA,sha256=LnnajcNGmSSr46yLIqP-tWkqeb-fR7vIa2U11hhkGEk,2960 +setuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORD,sha256=uq_S1tlMG95FPkyAWsBVEdxTmG4KY7AvZ07w94i-wUY,882 +setuptools/_vendor/jaraco_functools-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +setuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSE,sha256=WlfLTbheKi3YjCkGKJCK3VfjRRRJ4KmnH9-zh3b9dZ0,1076 +setuptools/_vendor/jaraco_functools-4.4.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 +setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA,sha256=arNRUUWr5YsGfwh8hnYxz0z11lP-2BuWQu4SCGw5BLg,39413 +setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD,sha256=ntGxNMCqg3IvNumfORiqlhDOOgpRTXk7u3SjaNRBoB0,1095 +setuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +setuptools/_vendor/more_itertools-10.8.0.dist-info/licenses/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053 +setuptools/_vendor/more_itertools/__init__.py,sha256=5F7E_zpoGcEBW_T_3WE0WYYt8j-gJodIuiBcOJxrOv8,149 +setuptools/_vendor/more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43 +setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/more_itertools/__pycache__/more.cpython-311.pyc,, +setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-311.pyc,, +setuptools/_vendor/more_itertools/more.py,sha256=mNPKKu5UI7lRL460vgm0QTCWFiGMVCMosSPxVSdibos,163690 +setuptools/_vendor/more_itertools/more.pyi,sha256=fpEgNX3O66wY5cnT-s5VYDKNUpAcaCyU3iP84It3OOM,27119 +setuptools/_vendor/more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/more_itertools/recipes.py,sha256=Ma-kuBNZDFhaQDbIJgRmnrG86WzaupbOyUV3v8je3xw,41811 +setuptools/_vendor/more_itertools/recipes.pyi,sha256=LNRwN-OL3nkMfQAqx-PPc1fBaetUObb_Z6mdePyzh1c,6226 +setuptools/_vendor/packaging-26.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/packaging-26.0.dist-info/METADATA,sha256=M2K7fWom2iliuo2qpHhc0LrKwhq6kIoRlcyPWVgKJlo,3309 +setuptools/_vendor/packaging-26.0.dist-info/RECORD,sha256=9QUDMzqulReAfS-02B_CfLYKpkRmb1AXaBJibWIkzl0,2113 +setuptools/_vendor/packaging-26.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/packaging-26.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +setuptools/_vendor/packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494 +setuptools/_vendor/packaging/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/_elffile.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/_parser.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/_structures.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/markers.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/metadata.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/pylock.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/requirements.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/specifiers.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/tags.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/utils.cpython-311.pyc,, +setuptools/_vendor/packaging/__pycache__/version.cpython-311.pyc,, +setuptools/_vendor/packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211 +setuptools/_vendor/packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559 +setuptools/_vendor/packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707 +setuptools/_vendor/packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518 +setuptools/_vendor/packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514 +setuptools/_vendor/packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421 +setuptools/_vendor/packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819 +setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-311.pyc,, +setuptools/_vendor/packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122 +setuptools/_vendor/packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771 +setuptools/_vendor/packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360 +setuptools/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537 +setuptools/_vendor/packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870 +setuptools/_vendor/packaging/specifiers.py,sha256=EPNPimY_zFivthv1vdjZYz5IqkKGsnKR2yKh-EVyvZw,40797 +setuptools/_vendor/packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856 +setuptools/_vendor/packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040 +setuptools/_vendor/packaging/version.py,sha256=7XWlL2IDYLwDYC0ht6cFEhapLwLWbmyo4rb7sEFj0x8,23272 +setuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/platformdirs-4.4.0.dist-info/METADATA,sha256=u8UhbV9Md7-8VyJyZNUuZrzN5xzPeedeGmBG0CnTAiM,12831 +setuptools/_vendor/platformdirs-4.4.0.dist-info/RECORD,sha256=PQ0vHMAYWTxNi6ojlbrwscHGRbvYwYzQZPSctOTJXqA,1218 +setuptools/_vendor/platformdirs-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/platformdirs-4.4.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +setuptools/_vendor/platformdirs-4.4.0.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089 +setuptools/_vendor/platformdirs/__init__.py,sha256=iORRy6_lZ9tXLvO0W6fJPn8QV7F532ivl-f2WGmabBc,22284 +setuptools/_vendor/platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493 +setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-311.pyc,, +setuptools/_vendor/platformdirs/__pycache__/android.cpython-311.pyc,, +setuptools/_vendor/platformdirs/__pycache__/api.cpython-311.pyc,, +setuptools/_vendor/platformdirs/__pycache__/macos.cpython-311.pyc,, +setuptools/_vendor/platformdirs/__pycache__/unix.cpython-311.pyc,, +setuptools/_vendor/platformdirs/__pycache__/version.cpython-311.pyc,, +setuptools/_vendor/platformdirs/__pycache__/windows.cpython-311.pyc,, +setuptools/_vendor/platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013 +setuptools/_vendor/platformdirs/api.py,sha256=wPHOlwOsfz2oqQZ6A2FcCu5kEAj-JondzoNOHYFQ0h8,9281 +setuptools/_vendor/platformdirs/macos.py,sha256=0XoOgin1NK7Qki7iskD-oS8xKxw6bXgoKEgdqpCRAFQ,6322 +setuptools/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458 +setuptools/_vendor/platformdirs/version.py,sha256=i31fi3nNO19D2FdSx8aldD7IFLSqm2YrAo6SmkV0FLM,704 +setuptools/_vendor/platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125 +setuptools/_vendor/tomli-2.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/tomli-2.4.0.dist-info/METADATA,sha256=9awKH4-6kItGRs1lUwnpGq2Wm2eHYWrFccpGKjgy_84,10567 +setuptools/_vendor/tomli-2.4.0.dist-info/RECORD,sha256=IlQwzpVkDo1Pzbk82uL8ONaFrsAW0OKT1fuZppWIb-0,822 +setuptools/_vendor/tomli-2.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/tomli-2.4.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +setuptools/_vendor/tomli-2.4.0.dist-info/licenses/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +setuptools/_vendor/tomli/__init__.py,sha256=ahtDjGJA2M_wWVvGpzx4YJtWxrWBx6qE-GH5-UYoECA,314 +setuptools/_vendor/tomli/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/tomli/__pycache__/_parser.cpython-311.pyc,, +setuptools/_vendor/tomli/__pycache__/_re.cpython-311.pyc,, +setuptools/_vendor/tomli/__pycache__/_types.cpython-311.pyc,, +setuptools/_vendor/tomli/_parser.py,sha256=txeATLE3zHyZ-ushXtYfrZ3LoIs7JzQF2W2KL1gwJPg,25958 +setuptools/_vendor/tomli/_re.py,sha256=oSNZ_ilFI6chEuQ01YRSoUydBQr_okF_mSdHTkFmv90,3396 +setuptools/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254 +setuptools/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 +setuptools/_vendor/wheel-0.46.3.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/wheel-0.46.3.dist-info/METADATA,sha256=IpEKqXyonLzCCgGeJ_4xNgt5KaS9ZsoNMQ-ZpE9szTU,2410 +setuptools/_vendor/wheel-0.46.3.dist-info/RECORD,sha256=sCl8OtoXuHJ-Fd3W0eOMipCpl_d5_Pl4mW9v7GLstwI,1734 +setuptools/_vendor/wheel-0.46.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/wheel-0.46.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +setuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txt,sha256=JJdtSAGTvMLbIkTVZUAMvGKO39FtWfCVF8mp_NH6e4g,110 +setuptools/_vendor/wheel-0.46.3.dist-info/licenses/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107 +setuptools/_vendor/wheel/__init__.py,sha256=UweKvhe4SyP7zFyDoYo8BOuwTA6q3-_WpMmY2NNO54c,59 +setuptools/_vendor/wheel/__main__.py,sha256=_83wl9tyGU2cHiqfudpubGHdRL5uonPXnzeznznkxzs,512 +setuptools/_vendor/wheel/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/wheel/__pycache__/__main__.cpython-311.pyc,, +setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-311.pyc,, +setuptools/_vendor/wheel/__pycache__/_metadata.cpython-311.pyc,, +setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-311.pyc,, +setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-311.pyc,, +setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-311.pyc,, +setuptools/_vendor/wheel/__pycache__/metadata.cpython-311.pyc,, +setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-311.pyc,, +setuptools/_vendor/wheel/_bdist_wheel.py,sha256=bpmNa7_s-CYFkVgXf9ENAYTiJ01XBhRW4pxH1T8XYsI,21729 +setuptools/_vendor/wheel/_commands/__init__.py,sha256=fCRAQZNDyj2JLrufdgPsBlaRS_t_j_aBUMpXj09KZ4E,4432 +setuptools/_vendor/wheel/_commands/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/wheel/_commands/__pycache__/convert.cpython-311.pyc,, +setuptools/_vendor/wheel/_commands/__pycache__/pack.cpython-311.pyc,, +setuptools/_vendor/wheel/_commands/__pycache__/tags.cpython-311.pyc,, +setuptools/_vendor/wheel/_commands/__pycache__/unpack.cpython-311.pyc,, +setuptools/_vendor/wheel/_commands/convert.py,sha256=0wSJMU0m-6LY16Om8Wmmloy-hJWFZeOmI8hT-2Z7Qms,12743 +setuptools/_vendor/wheel/_commands/pack.py,sha256=o3iwjfRHl7N9ul-M2kHbewLJZnqBLAWf0tzUCwoiTMw,3078 +setuptools/_vendor/wheel/_commands/tags.py,sha256=Rv2ySVb8-qX3osKp3uJgxcIMXkjt43XUD0-zvC6KvnY,4775 +setuptools/_vendor/wheel/_commands/unpack.py,sha256=AjDSS23XYyCSFfifnMutinrpPv-DK_2wbNHkKAUFwgM,1016 +setuptools/_vendor/wheel/_metadata.py,sha256=BP5jC9uC1hyicp7nL4FJ2LYixNFpEJIV_uMDY1KBZBg,6188 +setuptools/_vendor/wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781 +setuptools/_vendor/wheel/bdist_wheel.py,sha256=HrzYiSzMkh5ohAAhlQnYBS1p8qbr85X6F59xqxd9kBg,1102 +setuptools/_vendor/wheel/macosx_libfile.py,sha256=pL0wm88jRMl_4ASgGlNg_mz69Zmv5xm8JSkjLdwyvIQ,16712 +setuptools/_vendor/wheel/metadata.py,sha256=GknOO7JJiZMlcEe_fiD7nqnDTTLd0sX_-IgipM4L3-4,757 +setuptools/_vendor/wheel/wheelfile.py,sha256=m_g_7TNsEp-j-xnvSr5yDLEFb1nhyObueq9Q5_1_lBA,8720 +setuptools/_vendor/zipp-3.23.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +setuptools/_vendor/zipp-3.23.0.dist-info/METADATA,sha256=vdZ9TRbPC_O4k-fRjNPS13StuC837Zhbx3cMYHIms1s,3563 +setuptools/_vendor/zipp-3.23.0.dist-info/RECORD,sha256=O_q2YKJHBPhCKOS7HOHw4_qf-A5cgGNSpiay9GDq2DY,1078 +setuptools/_vendor/zipp-3.23.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/zipp-3.23.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +setuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSE,sha256=WlfLTbheKi3YjCkGKJCK3VfjRRRJ4KmnH9-zh3b9dZ0,1076 +setuptools/_vendor/zipp-3.23.0.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5 +setuptools/_vendor/zipp/__init__.py,sha256=ieXh9GIMdABjKRX_JUJtP9k5wdBLK4Mt5X4nszSkmYE,11976 +setuptools/_vendor/zipp/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/zipp/__pycache__/_functools.cpython-311.pyc,, +setuptools/_vendor/zipp/__pycache__/glob.cpython-311.pyc,, +setuptools/_vendor/zipp/_functools.py,sha256=f6Kt9LxZ4TE-cY1lJVdXSId3memSXmH9IdgMbU-_x2k,575 +setuptools/_vendor/zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-311.pyc,, +setuptools/_vendor/zipp/compat/__pycache__/overlay.cpython-311.pyc,, +setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-311.pyc,, +setuptools/_vendor/zipp/compat/__pycache__/py313.cpython-311.pyc,, +setuptools/_vendor/zipp/compat/overlay.py,sha256=oEIGAnbr8yGjuKTrVSO2ByewPui71uppbX18BLnYTKE,783 +setuptools/_vendor/zipp/compat/py310.py,sha256=S7i6N9mToEn3asNb2ILyjnzvITOXrATD_J4emjyBbDU,256 +setuptools/_vendor/zipp/compat/py313.py,sha256=RndvDNtuY7H2D9ecnnzcPBMZ8mZc42gmXD_IwQAXXAE,654 +setuptools/_vendor/zipp/glob.py,sha256=DLV9LBsDxA6YVW82e3-tkoNrus1h4R-j3BR6VqS0AzE,3382 +setuptools/archive_util.py,sha256=Tl_64hSTtc4y8x7xa98rFVUbG24oArpjzLAYGYP2_sI,7356 +setuptools/build_meta.py,sha256=x3a7i1m4K6gGYC03yj20LRnEtvZpZjetXCJbpgNo6Cg,20234 +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-311.pyc,, +setuptools/command/__pycache__/_requirestxt.cpython-311.pyc,, +setuptools/command/__pycache__/alias.cpython-311.pyc,, +setuptools/command/__pycache__/bdist_egg.cpython-311.pyc,, +setuptools/command/__pycache__/bdist_rpm.cpython-311.pyc,, +setuptools/command/__pycache__/bdist_wheel.cpython-311.pyc,, +setuptools/command/__pycache__/build.cpython-311.pyc,, +setuptools/command/__pycache__/build_clib.cpython-311.pyc,, +setuptools/command/__pycache__/build_ext.cpython-311.pyc,, +setuptools/command/__pycache__/build_py.cpython-311.pyc,, +setuptools/command/__pycache__/develop.cpython-311.pyc,, +setuptools/command/__pycache__/dist_info.cpython-311.pyc,, +setuptools/command/__pycache__/easy_install.cpython-311.pyc,, +setuptools/command/__pycache__/editable_wheel.cpython-311.pyc,, +setuptools/command/__pycache__/egg_info.cpython-311.pyc,, +setuptools/command/__pycache__/install.cpython-311.pyc,, +setuptools/command/__pycache__/install_egg_info.cpython-311.pyc,, +setuptools/command/__pycache__/install_lib.cpython-311.pyc,, +setuptools/command/__pycache__/install_scripts.cpython-311.pyc,, +setuptools/command/__pycache__/rotate.cpython-311.pyc,, +setuptools/command/__pycache__/saveopts.cpython-311.pyc,, +setuptools/command/__pycache__/sdist.cpython-311.pyc,, +setuptools/command/__pycache__/setopt.cpython-311.pyc,, +setuptools/command/__pycache__/test.cpython-311.pyc,, +setuptools/command/_requirestxt.py,sha256=ItYMTJGh_i5TlQstX_nFopqEhkC4PJFadBL2Zd3V670,4228 +setuptools/command/alias.py,sha256=vVxEYVEFMTZznxuXLg-62Y07VV2U-rfhVqmqhTc62Cg,2366 +setuptools/command/bdist_egg.py,sha256=1kWCzqsiDUGw-HiHu6aGcH16Cf7TjV8oe86ILNLLHTM,16832 +setuptools/command/bdist_rpm.py,sha256=LyqI49w48SKk0FmuHsE9MLzX1SuXjL7YMNbZMFZqFII,1435 +setuptools/command/bdist_wheel.py,sha256=2TMl21f7WWeH3m0NhJLVZPVOSWE0w-wZcG2pFseP8Qw,22210 +setuptools/command/build.py,sha256=eI7STMERGGZEpzk1tvJN8p9IOjAAXMcGLzljv2mwI3M,6052 +setuptools/command/build_clib.py,sha256=AbgpPIF_3qL8fZr3JIebI-WHTMTBiMfrFkVQz8K40G4,4528 +setuptools/command/build_ext.py,sha256=SaurTvvtJuOSOD8cm_6Wj1T0DFiyl5Nazv4GYINAgWA,18270 +setuptools/command/build_py.py,sha256=eHhfo9z7Qf79vSzrCnq-oEXayQC0R_nx3hWaTgWGv5M,15826 +setuptools/command/develop.py,sha256=TYKWIzfv3c3wjAYhH5UD8tW6S6ozZi_fpF6IJILm8Kg,1751 +setuptools/command/dist_info.py,sha256=HU752iLLmmYMHbsDBgz2ubRjkgJobugOp8H71LzzDys,3450 +setuptools/command/easy_install.py,sha256=XrN5cV51mfzbCDoapZ6iT8nCzaLpumdwJYRKeMHEjCQ,780 +setuptools/command/editable_wheel.py,sha256=xJOPl_0s5DbwpeLw-SNh75mvEnmwE7OFpnpChlOaNgg,34862 +setuptools/command/egg_info.py,sha256=_yZYJz5CrLh0aYeT2GXBp6bjF0a0QgYvoDR3uBdKJZc,25754 +setuptools/command/install.py,sha256=4x2hiNgBGQrFEXKuPBQMrb8ecSwIfYF4TYHZQLjPVAg,5066 +setuptools/command/install_egg_info.py,sha256=gYOkfDM-G0agy2aMCE8HzreIi4LzUy6acZ6Ka-rKahQ,2020 +setuptools/command/install_lib.py,sha256=9n1_U83eHcERL_a_rv_LhHCkhXlLdqyZ4SdBow-9qcE,4319 +setuptools/command/install_scripts.py,sha256=ZYfF_-viovV5HSLsRzBlNQv5pHv2H0t2ZnL5qzZ4xfM,2445 +setuptools/command/launcher manifest.xml,sha256=xlLbjWrB01tKC0-hlVkOKkiSPbzMml2eOPtJ_ucCnbE,628 +setuptools/command/rotate.py,sha256=PywuJoufmiO_5JykOg-oatrYsBnZfA0pG1HJy7Bsb9Q,2134 +setuptools/command/saveopts.py,sha256=k9hiQ_wOKweXWgBWV548PISmFKfYJkV2XHhi92ejz5o,678 +setuptools/command/sdist.py,sha256=nS2xogcTfQZwbZH1AQ5WYh13KCvNda9xwUT57sVxTec,7426 +setuptools/command/setopt.py,sha256=MCM9SM92LwGUC-E2nnvQxX8Yf2ukMj1YAa6KCRlqt_8,5047 +setuptools/command/test.py,sha256=x9z3DDCQi-_3-TRf8yNeQ9QH-G6yR1au7kX0ijedKqU,1400 +setuptools/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/compat/__pycache__/__init__.cpython-311.pyc,, +setuptools/compat/__pycache__/py310.cpython-311.pyc,, +setuptools/compat/__pycache__/py311.cpython-311.pyc,, +setuptools/compat/__pycache__/py312.cpython-311.pyc,, +setuptools/compat/__pycache__/py39.cpython-311.pyc,, +setuptools/compat/py310.py,sha256=JwjQZ3cNTizfpDLNl9GLsUGzBr-tVlMPxmMYVDTlhiI,344 +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-311.pyc,, +setuptools/config/__pycache__/_apply_pyprojecttoml.cpython-311.pyc,, +setuptools/config/__pycache__/expand.cpython-311.pyc,, +setuptools/config/__pycache__/pyprojecttoml.cpython-311.pyc,, +setuptools/config/__pycache__/setupcfg.cpython-311.pyc,, +setuptools/config/_apply_pyprojecttoml.py,sha256=tQXU9M4lcrd3iwO_2reihz22IbHaHg_Z-lAMBXZRzW8,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-311.pyc,, +setuptools/config/_validate_pyproject/__pycache__/error_reporting.cpython-311.pyc,, +setuptools/config/_validate_pyproject/__pycache__/extra_validations.cpython-311.pyc,, +setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_exceptions.cpython-311.pyc,, +setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-311.pyc,, +setuptools/config/_validate_pyproject/__pycache__/formats.cpython-311.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=STKJ6oNAo6avEBVUiR25WpfIthVPVZQG65Z-5-t78QI,16064 +setuptools/config/pyprojecttoml.py,sha256=YMu5PdbJJI5azp6kR_boM1mflf5nqOA-InF4s6LnLgw,18320 +setuptools/config/setupcfg.py,sha256=Wnfbrk6D0GQV-Z2AE0b0KnL-WGrw-KQUcsem3naImBw,26695 +setuptools/config/setuptools.schema.json,sha256=dZBRuSEnZkatoVlt1kVwG8ocTeRdO7BD0xvOWKH54PY,16071 +setuptools/depends.py,sha256=jKYfjmt_2ZQYVghb8L9bU7LJ6erHJ5ze-K_fKV1BMXk,5965 +setuptools/discovery.py,sha256=XYIeFN20WEsEtssmpzCFlnda-Qxilj8KlLYKaJphAto,21286 +setuptools/dist.py,sha256=aa181F7kGdfeL6To3X2ZvQ8zSiQCSacWRJdhL0v49xk,45184 +setuptools/errors.py,sha256=gY2x2PIaIgy01yRANRC-zcCwxDCqCScgJoCOZFe0yio,3024 +setuptools/extension.py,sha256=GbCxJ9rRk2rZcXS4qgmnzWNG36HlhLfUEvNwB-OKGk8,6818 +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=Wy_hG1g1r-45E6IWh7lvQ0Pk0QHNl6JJbu3hQmr1_Ek,5184 +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=nOD5vgLG7IpKAs7LrnpJxGPaCW54Rzj-onJmm91otoY,3733 +setuptools/msvc.py,sha256=IdCsRhdJLeyZG3gyDrGx2DqZymoay3ndBXC77taHHCA,42909 +setuptools/namespaces.py,sha256=eE1hI5X86TNWvY5u5BC1WiGiOrrJyGOv0pp9vycCmK0,3045 +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-311.pyc,, +setuptools/tests/__pycache__/contexts.cpython-311.pyc,, +setuptools/tests/__pycache__/environment.cpython-311.pyc,, +setuptools/tests/__pycache__/fixtures.cpython-311.pyc,, +setuptools/tests/__pycache__/mod_with_constant.cpython-311.pyc,, +setuptools/tests/__pycache__/namespaces.cpython-311.pyc,, +setuptools/tests/__pycache__/script-with-bom.cpython-311.pyc,, +setuptools/tests/__pycache__/test_archive_util.cpython-311.pyc,, +setuptools/tests/__pycache__/test_bdist_deprecations.cpython-311.pyc,, +setuptools/tests/__pycache__/test_bdist_egg.cpython-311.pyc,, +setuptools/tests/__pycache__/test_bdist_wheel.cpython-311.pyc,, +setuptools/tests/__pycache__/test_build.cpython-311.pyc,, +setuptools/tests/__pycache__/test_build_clib.cpython-311.pyc,, +setuptools/tests/__pycache__/test_build_ext.cpython-311.pyc,, +setuptools/tests/__pycache__/test_build_meta.cpython-311.pyc,, +setuptools/tests/__pycache__/test_build_py.cpython-311.pyc,, +setuptools/tests/__pycache__/test_config_discovery.cpython-311.pyc,, +setuptools/tests/__pycache__/test_core_metadata.cpython-311.pyc,, +setuptools/tests/__pycache__/test_depends.cpython-311.pyc,, +setuptools/tests/__pycache__/test_develop.cpython-311.pyc,, +setuptools/tests/__pycache__/test_dist.cpython-311.pyc,, +setuptools/tests/__pycache__/test_dist_info.cpython-311.pyc,, +setuptools/tests/__pycache__/test_distutils_adoption.cpython-311.pyc,, +setuptools/tests/__pycache__/test_editable_install.cpython-311.pyc,, +setuptools/tests/__pycache__/test_egg_info.cpython-311.pyc,, +setuptools/tests/__pycache__/test_extern.cpython-311.pyc,, +setuptools/tests/__pycache__/test_find_packages.cpython-311.pyc,, +setuptools/tests/__pycache__/test_find_py_modules.cpython-311.pyc,, +setuptools/tests/__pycache__/test_glob.cpython-311.pyc,, +setuptools/tests/__pycache__/test_install_scripts.cpython-311.pyc,, +setuptools/tests/__pycache__/test_logging.cpython-311.pyc,, +setuptools/tests/__pycache__/test_manifest.cpython-311.pyc,, +setuptools/tests/__pycache__/test_namespaces.cpython-311.pyc,, +setuptools/tests/__pycache__/test_scripts.cpython-311.pyc,, +setuptools/tests/__pycache__/test_sdist.cpython-311.pyc,, +setuptools/tests/__pycache__/test_setopt.cpython-311.pyc,, +setuptools/tests/__pycache__/test_setuptools.cpython-311.pyc,, +setuptools/tests/__pycache__/test_shutil_wrapper.cpython-311.pyc,, +setuptools/tests/__pycache__/test_unicode_utils.cpython-311.pyc,, +setuptools/tests/__pycache__/test_virtualenv.cpython-311.pyc,, +setuptools/tests/__pycache__/test_warnings.cpython-311.pyc,, +setuptools/tests/__pycache__/test_wheel.cpython-311.pyc,, +setuptools/tests/__pycache__/test_windows_wrappers.cpython-311.pyc,, +setuptools/tests/__pycache__/text.cpython-311.pyc,, +setuptools/tests/__pycache__/textwrap.cpython-311.pyc,, +setuptools/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +setuptools/tests/compat/__pycache__/__init__.cpython-311.pyc,, +setuptools/tests/compat/__pycache__/py39.cpython-311.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-311.pyc,, +setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-311.pyc,, +setuptools/tests/config/__pycache__/test_expand.cpython-311.pyc,, +setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-311.pyc,, +setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-311.pyc,, +setuptools/tests/config/__pycache__/test_setupcfg.cpython-311.pyc,, +setuptools/tests/config/downloads/__init__.py,sha256=9ixnDEdyL_arKbUzfuiJftAj9bGxKz8M9alOFZMjx9Y,1827 +setuptools/tests/config/downloads/__pycache__/__init__.cpython-311.pyc,, +setuptools/tests/config/downloads/__pycache__/preload.cpython-311.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=KVBqnElEW5p9HJpTYnztZqd3RXYaY6SrSY8ek9ysq7s,28822 +setuptools/tests/config/test_expand.py,sha256=S0oT6JvgA_oujR4YS4RUuf5gmOt1CTQV66RQDzV8xd4,8933 +setuptools/tests/config/test_pyprojecttoml.py,sha256=CzLH1qcKDQGxCyLHC_ZYMObms1D_Jtp6AuJROOFI_D8,12438 +setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py,sha256=1MRtzcxZag-ElRwVGt0kUk4KPRA-RSwKkibO8-Vy51w,3265 +setuptools/tests/config/test_setupcfg.py,sha256=iwViCQFLGVWZLgCDrBv8HKBBCj-Onr8aNdioD9_lBEo,33712 +setuptools/tests/contexts.py,sha256=Ozdfc2KydF9x9wODUsdun800myLuP27uxoeT06Gbk7M,3166 +setuptools/tests/environment.py,sha256=95_UtTaRiuvwYC9eXKEHbn02kDtZysvZq3UZJmPUj1I,3102 +setuptools/tests/fixtures.py,sha256=jE7pIFQt91dZIUc6Btsffi8OdBqmY_7DNeWI1Stv7i8,12224 +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-311.pyc,, +setuptools/tests/integration/__pycache__/helpers.cpython-311.pyc,, +setuptools/tests/integration/__pycache__/test_pbr.cpython-311.pyc,, +setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-311.pyc,, +setuptools/tests/integration/helpers.py,sha256=ieQtGuIohqNI_RHMH0yxE602Uz4E8wysUj7XaXYH30Y,2688 +setuptools/tests/integration/test_pbr.py,sha256=2eKuklFNmpnBgA_eEhYPBr6rLLG2Xm4MY6PlcmzZgGU,432 +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/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=xGHVaggiYobkOuGwkLK2bNejcSh8z2Fiuq-ge_S-yKo,23091 +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=ToI7-2LUnHuIPhKN8EkDkSEfLCvLqLI6VJhqwR5pVuU,33320 +setuptools/tests/test_build_py.py,sha256=SIcHFX3YNErcVkWjf0eDRuKmsO9kTymKjfK-PkOi9M0,14201 +setuptools/tests/test_config_discovery.py,sha256=FqV-lOtkqaI-ayzU2zocSdD5TaRAgCZnixNDilKA6FQ,22580 +setuptools/tests/test_core_metadata.py,sha256=p8mW920afKVdL8sC_Fce8zpmfWDCRylBa3dd39Y-qWo,18038 +setuptools/tests/test_depends.py,sha256=yQBXoQbNQlJit6mbRVoz6Bb553f3sNrq02lZimNz5XY,424 +setuptools/tests/test_develop.py,sha256=k-agNgB8DIGR8zlaYMBILu8KOPrL2plorNCexxzNm-s,3136 +setuptools/tests/test_dist.py,sha256=M4FikA-vL0_lZdA_5wry2Z9CBuSugr0Pj54dBZ3peBM,8951 +setuptools/tests/test_dist_info.py,sha256=EihdrU9UZkPV7d19G-K_OtOByp64GvGnf4or-f8Iq54,5005 +setuptools/tests/test_distutils_adoption.py,sha256=_eynrOfyEqXFEmjUJhzpe8GXPyTUPvNSObs4qAAmBy8,5987 +setuptools/tests/test_editable_install.py,sha256=o4DkoytkiL-_rzES8p1q8XYRa9-ha_m6uhrm-EWzdwI,42498 +setuptools/tests/test_egg_info.py,sha256=R7nT27YhVz9oSuDyimAGerWglkbRWiMSPBs5FzcSnBM,44941 +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=czGLLdGxUBZKXbea3A0HnSW9lf-3K_CUwaI0gDkVbOM,2096 +setuptools/tests/test_manifest.py,sha256=eMg65pIA52DizB6mpktSU-b8CjwaNCS5MSgL_V1LrFI,18562 +setuptools/tests/test_namespaces.py,sha256=e84seD5g6KIPVSDpawE9Ihc25Je7shooybV1flUsW20,2508 +setuptools/tests/test_scripts.py,sha256=_ra506yQF7n72ROUDcz2r3CTsGsawO1m-1oqA9EQCfw,379 +setuptools/tests/test_sdist.py,sha256=oKMgvBrkfTsPH5jqsrhFxRMbtUDoOy4vKfwll3kGCg0,32808 +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=iMfVTNixu4puf6xvRYjQDw4Zg_OHVCQjSy7SztvVYqE,18722 +setuptools/tests/test_windows_wrappers.py,sha256=wBjXN3iGldkzRGTgKTrx99xqUqwPJ0V-ldyiB1pWD-g,7868 +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=iI-LSDrgHMlJIzQMALVlJRq3Qesgbj7xa6hWZYJyZl4,9532 +setuptools/windows_support.py,sha256=wW4IYLM1Bv7Z1MaauP2xmPjyy-wkmQnXdyvXscAf9fw,726 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1ef5583317a5e59140e3f1c85c2db91aec0961e8 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/entry_points.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..0db0a6c8f1b8d9c0ad4a25db6892e29f8988fcf2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/top_level.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..11b11fe8dd21d5b4fcb4539230460a42747fa896 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools-82.0.0.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_distutils_hack +setuptools diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e455e3da55c78b12fbf54ccf94010e531997ab46 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_core_metadata.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_core_metadata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d38ab608fa32576a111e280a3c473e7250f42ad3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_core_metadata.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_discovery.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_discovery.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14432e48eda75463454195ab11a35d33936f277c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_discovery.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_entry_points.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_entry_points.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87cac6dae54e0e34200639c539a27bec641bcd65 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_entry_points.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_imp.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_imp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..829e3059ccee505424d0bd45d4c03cb64eff4c4d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_imp.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_importlib.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_importlib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5453b6c2230ecff90708aafb60fa49e615fa23ca Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_importlib.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_itertools.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_itertools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79c94837b670ad065c8ec73ff7bd2efc71a23905 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_itertools.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_normalization.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_normalization.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b6e2aada2cfc633688ad9c40518ae730b253f15 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_normalization.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_path.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_path.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8407c3323234cbc4c481f05f5f7f37995f1b9532 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_path.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_reqs.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_reqs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d747518c13be5b20713917a8a901ec8f0c24bd57 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_reqs.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_scripts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_scripts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edf848d8ec377fc03d01e8d5611631c5542e945c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_scripts.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_shutil.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_shutil.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5033e855f54c14f1d3a1609b682673e07a75312 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_shutil.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_static.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_static.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab17e419798a711b523dfeed7b6a5d251977c79a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/_static.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/archive_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/archive_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f31f6ea6970d26224aa0ac612f85791044f9032 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/archive_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/build_meta.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/build_meta.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6be0720c9cc7ab0feb2cf94cc5a9fcecfeca6b91 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/build_meta.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/depends.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/depends.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d95f451809c1cffe11c28159abd0a2e3b6199a2 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/depends.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/discovery.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/discovery.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3d45de7d3a7d35514dcf93d2ec2f09b93be4642 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/discovery.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/dist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/dist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13c7ed0a663e70d9a14dc7a04d15f7596de5c647 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/dist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/errors.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cbdd391bc52c70b50d23fb477dc3956b2ca4f4d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/errors.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/extension.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/extension.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..601d5d65eeaf48e499ef3600d5fffce84ca507fc Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/extension.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/glob.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/glob.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a44e51552b818ede30ee89d5f7c1389be9dd317 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/glob.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/installer.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/installer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9189e2c4de70e027683efe81fa4d82237705bd24 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/installer.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/launch.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/launch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f74644115bca585765667294d9935c5852b56568 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/launch.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/logging.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/logging.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5c38d1828c8d096856c143a61799616d2d8250a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/logging.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/modified.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/modified.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ab8d6797cd8eff52359793789999e0495da69a3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/modified.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/monkey.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/monkey.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..664159ffe6535c6f98e5c9f5d82f64e478e05096 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/monkey.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/msvc.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/msvc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32c9a5b94b856f8a779e379b7590d4ac4abaa132 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/msvc.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/namespaces.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/namespaces.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a648df14c5e8208868b80a4d4c4a3cda39fc59a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/namespaces.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/unicode_utils.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/unicode_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1d594caa226469945ebb97345118b597319bdde Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/unicode_utils.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/version.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2444650460467596f068cedfedc6dc0cc1893719 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/version.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/warnings.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/warnings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb8e72267abcdfb0cd10516b432b8581064d67ee Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/warnings.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/wheel.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/wheel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..670512d5033a63306e01b3d575f32aa958f72e94 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/wheel.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/windows_support.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/windows_support.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c14a17f9c024977b72941c29711ca358848e18f5 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/__pycache__/windows_support.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e374d5c5604d0eeed555e68b7523bfac72fd9101 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__init__.py @@ -0,0 +1,14 @@ +import importlib +import sys + +__version__, _, _ = sys.version.partition(' ') + + +try: + # Allow Debian and pkgsrc (only) to customize system + # behavior. Ref pypa/distutils#2 and pypa/distutils#16. + # This hook is deprecated and no other environments + # should use it. + importlib.import_module('_distutils_system_mod') +except ImportError: + pass diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbe5cf5fa2d5cebd58b6f81df371a876785b61e8 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_log.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_log.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac63da5ef7568b9cda65d3808c2defc2266b4e12 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_log.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_macos_compat.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_macos_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01c759ce81f5245a6df80a736bd8e3789e24b4f5 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_macos_compat.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_modified.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_modified.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b79ae6396b698588c3ac5871c9446b4c1ebafab Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_modified.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_msvccompiler.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_msvccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..420cccf24e07a1970d324cd331d76306566fe507 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/_msvccompiler.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/archive_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/archive_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f33fbdcc61243fee6db0ca5665865b1cad1495a0 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/archive_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/ccompiler.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/ccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58495701390e675bc3d695909225e660c8a61fde Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/ccompiler.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/cmd.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/cmd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a121433001557e3f82de76f55e52cca5cc898847 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/cmd.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/core.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc43bc1913248d4edf5ce1bf85a201676c3a8e9d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/core.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/cygwinccompiler.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/cygwinccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95830767faa2f5a5a1a677309aefb6b94532060f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/cygwinccompiler.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/debug.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/debug.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a755badc51b1457d0446746171554e9e54ac2ae0 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/debug.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dep_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dep_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ce4e84922cffc601dda134f0a03b0c052669cad Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dep_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dir_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dir_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1affcaaac273b294a8014f9958f6d57c74469b4 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dir_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d12960ce2d8b94fe2b9a1235cbc1a1f739478b4 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/dist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/errors.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a92607dfeaf3893bbd4b24c7a6638cb977c46c6c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/errors.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/extension.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/extension.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13c98eae30e2650c25028317a27562e413863622 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/extension.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/fancy_getopt.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/fancy_getopt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29be94e5595cc68933a967ccbcb5cc960831f755 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/fancy_getopt.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/file_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/file_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d45665493af6732b67c5ab68ab7929ea5faa53e Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/file_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/filelist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/filelist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58f9e8a69d48985981a9721e30381daf49ff5366 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/filelist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/log.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/log.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76f4656ac03c1cb4ee5c4b858a104df05c41d341 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/log.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/spawn.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/spawn.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9ce6f3a51410eb836aba2ccc3643af84ead1819 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/spawn.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/sysconfig.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/sysconfig.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..399a37e951f9b7b302dba4076b03c59d8530e295 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/sysconfig.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/text_file.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/text_file.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d1c69b7660ca962b4eeddaa2f7db00764d44dfb Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/text_file.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/unixccompiler.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/unixccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e654d17658ea26172d55daec86940b7be4034d44 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/unixccompiler.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6a92f0501a8b5070c6c939d3526775c0e5a2dbf Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/version.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fe1061be773c93a28423ad602b99ff8c32dde45 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/version.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/versionpredicate.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/versionpredicate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74e06336dbcf83fb3fe6db6d80578413a4b56e21 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/versionpredicate.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/zosccompiler.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/zosccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..556635ddeb7aafb5d0f932e51ada241f716e5c16 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/__pycache__/zosccompiler.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_log.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_log.py new file mode 100644 index 0000000000000000000000000000000000000000..0148f157ff3bf8bd728c82f49cd3d1cd9cb5a43e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_log.py @@ -0,0 +1,3 @@ +import logging + +log = logging.getLogger() diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_macos_compat.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_macos_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..76ecb96abe478313ce7d09342b2643bf4a765331 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_macos_compat.py @@ -0,0 +1,12 @@ +import importlib +import sys + + +def bypass_compiler_fixup(cmd, args): + return cmd + + +if sys.platform == 'darwin': + compiler_fixup = importlib.import_module('_osx_support').compiler_fixup +else: + compiler_fixup = bypass_compiler_fixup diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_modified.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_modified.py new file mode 100644 index 0000000000000000000000000000000000000000..f64cab7d61ae20dd0c425b8843b068f39faa6961 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_modified.py @@ -0,0 +1,95 @@ +"""Timestamp comparison of files and groups of files.""" + +from __future__ import annotations + +import functools +import os.path +from collections.abc import Callable, Iterable +from typing import Literal, TypeVar + +from jaraco.functools import splat + +from .compat.py39 import zip_strict +from .errors import DistutilsFileError + +_SourcesT = TypeVar( + "_SourcesT", bound="str | bytes | os.PathLike[str] | os.PathLike[bytes]" +) +_TargetsT = TypeVar( + "_TargetsT", bound="str | bytes | os.PathLike[str] | os.PathLike[bytes]" +) + + +def _newer(source, target): + return not os.path.exists(target) or ( + os.path.getmtime(source) > os.path.getmtime(target) + ) + + +def newer( + source: str | bytes | os.PathLike[str] | os.PathLike[bytes], + target: str | bytes | os.PathLike[str] | os.PathLike[bytes], +) -> bool: + """ + Is source modified more recently than target. + + Returns True if 'source' is modified more recently than + 'target' or if 'target' does not exist. + + Raises DistutilsFileError if 'source' does not exist. + """ + if not os.path.exists(source): + raise DistutilsFileError(f"file {os.path.abspath(source)!r} does not exist") + + return _newer(source, target) + + +def newer_pairwise( + sources: Iterable[_SourcesT], + targets: Iterable[_TargetsT], + newer: Callable[[_SourcesT, _TargetsT], bool] = newer, +) -> tuple[list[_SourcesT], list[_TargetsT]]: + """ + Filter filenames where sources are newer than targets. + + Walk two filename iterables in parallel, testing if each source is newer + than its corresponding target. Returns a pair of lists (sources, + targets) where source is newer than target, according to the semantics + of 'newer()'. + """ + newer_pairs = filter(splat(newer), zip_strict(sources, targets)) + return tuple(map(list, zip(*newer_pairs))) or ([], []) + + +def newer_group( + sources: Iterable[str | bytes | os.PathLike[str] | os.PathLike[bytes]], + target: str | bytes | os.PathLike[str] | os.PathLike[bytes], + missing: Literal["error", "ignore", "newer"] = "error", +) -> bool: + """ + Is target out-of-date with respect to any file in sources. + + Return True if 'target' is out-of-date with respect to any file + listed in 'sources'. In other words, if 'target' exists and is newer + than every file in 'sources', return False; otherwise return True. + ``missing`` controls how to handle a missing source file: + + - error (default): allow the ``stat()`` call to fail. + - ignore: silently disregard any missing source files. + - newer: treat missing source files as "target out of date". This + mode is handy in "dry-run" mode: it will pretend to carry out + commands that wouldn't work because inputs are missing, but + that doesn't matter because dry-run won't run the commands. + """ + + def missing_as_newer(source): + return missing == 'newer' and not os.path.exists(source) + + ignored = os.path.exists if missing == 'ignore' else None + return not os.path.exists(target) or any( + missing_as_newer(source) or _newer(source, target) + for source in filter(ignored, sources) + ) + + +newer_pairwise_group = functools.partial(newer_pairwise, newer=newer_group) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_msvccompiler.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_msvccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..d07c86ef8e41fc31357c989133d51e9618c3e43d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/_msvccompiler.py @@ -0,0 +1,16 @@ +import warnings + +from .compilers.C import msvc + +__all__ = ["MSVCCompiler"] + +MSVCCompiler = msvc.Compiler + + +def __getattr__(name): + if name == '_get_vc_env': + warnings.warn( + "_get_vc_env is private; find an alternative (pypa/distutils#340)" + ) + return msvc._get_vc_env + raise AttributeError(name) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/archive_util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/archive_util.py new file mode 100644 index 0000000000000000000000000000000000000000..4a7fb9c9e7a0c4a0ca2a3ab608ffab6acf10bb3e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/archive_util.py @@ -0,0 +1,284 @@ +"""distutils.archive_util + +Utility functions for creating archive files (tarballs, zip files, +that sort of thing).""" + +from __future__ import annotations + +import os +from typing import Literal, overload + +try: + import zipfile +except ImportError: + zipfile = None + + +from ._log import log +from .dir_util import mkpath +from .errors import DistutilsExecError +from .spawn import spawn + +try: + from pwd import getpwnam +except ImportError: + getpwnam = None + +try: + from grp import getgrnam +except ImportError: + getgrnam = None + + +def _get_gid(name): + """Returns a gid, given a group name.""" + if getgrnam is None or name is None: + return None + try: + result = getgrnam(name) + except KeyError: + result = None + if result is not None: + return result[2] + return None + + +def _get_uid(name): + """Returns an uid, given a user name.""" + if getpwnam is None or name is None: + return None + try: + result = getpwnam(name) + except KeyError: + result = None + if result is not None: + return result[2] + return None + + +def make_tarball( + base_name: str, + base_dir: str | os.PathLike[str], + compress: Literal["gzip", "bzip2", "xz"] | None = "gzip", + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: + """Create a (possibly compressed) tar file from all the files under + 'base_dir'. + + 'compress' must be "gzip" (the default), "bzip2", "xz", or None. + + 'owner' and 'group' can be used to define an owner and a group for the + archive that is being built. If not provided, the current owner and group + will be used. + + The output tar file will be named 'base_dir' + ".tar", possibly plus + the appropriate compression extension (".gz", ".bz2", ".xz" or ".Z"). + + Returns the output filename. + """ + tar_compression = { + 'gzip': 'gz', + 'bzip2': 'bz2', + 'xz': 'xz', + None: '', + } + compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz'} + + # flags for compression program, each element of list will be an argument + if compress is not None and compress not in compress_ext.keys(): + raise ValueError( + "bad value for 'compress': must be None, 'gzip', 'bzip2', 'xz'" + ) + + archive_name = base_name + '.tar' + archive_name += compress_ext.get(compress, '') + + mkpath(os.path.dirname(archive_name)) + + # creating the tarball + import tarfile # late import so Python build itself doesn't break + + log.info('Creating tar archive') + + uid = _get_uid(owner) + gid = _get_gid(group) + + def _set_uid_gid(tarinfo): + if gid is not None: + tarinfo.gid = gid + tarinfo.gname = group + if uid is not None: + tarinfo.uid = uid + tarinfo.uname = owner + return tarinfo + + tar = tarfile.open(archive_name, f'w|{tar_compression[compress]}') + try: + tar.add(base_dir, filter=_set_uid_gid) + finally: + tar.close() + + return archive_name + + +def make_zipfile( + base_name: str, + base_dir: str | os.PathLike[str], + verbose: bool = False, +) -> str: + """Create a zip file from all the files under 'base_dir'. + + The output zip file will be named 'base_name' + ".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. + """ + zip_filename = base_name + ".zip" + mkpath(os.path.dirname(zip_filename)) + + # If zipfile module is not available, try spawning an external + # 'zip' command. + if zipfile is None: + if verbose: + zipoptions = "-r" + else: + zipoptions = "-rq" + + try: + spawn(["zip", zipoptions, zip_filename, base_dir]) + except DistutilsExecError: + # XXX really should distinguish between "couldn't find + # external 'zip' command" and "zip failed". + raise DistutilsExecError( + f"unable to create zip file '{zip_filename}': " + "could neither import the 'zipfile' module nor " + "find a standalone zip utility" + ) + + else: + log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) + + try: + zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) + except RuntimeError: + zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_STORED) + + with zip: + if base_dir != os.curdir: + path = os.path.normpath(os.path.join(base_dir, '')) + zip.write(path, path) + log.info("adding '%s'", path) + for dirpath, dirnames, filenames in os.walk(base_dir): + for name in dirnames: + path = os.path.normpath(os.path.join(dirpath, name, '')) + zip.write(path, path) + log.info("adding '%s'", path) + for name in filenames: + path = os.path.normpath(os.path.join(dirpath, name)) + if os.path.isfile(path): + zip.write(path, path) + log.info("adding '%s'", path) + + return zip_filename + + +ARCHIVE_FORMATS = { + 'gztar': (make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"), + 'bztar': (make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"), + 'xztar': (make_tarball, [('compress', 'xz')], "xz'ed tar-file"), + 'ztar': (make_tarball, [('compress', 'compress')], "compressed tar file"), + 'tar': (make_tarball, [('compress', None)], "uncompressed tar file"), + 'zip': (make_zipfile, [], "ZIP file"), +} + + +def check_archive_formats(formats): + """Returns the first format from the 'format' list that is unknown. + + If all formats are known, returns None + """ + for format in formats: + if format not in ARCHIVE_FORMATS: + return format + return None + + +@overload +def make_archive( + base_name: str, + format: str, + root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None, + base_dir: str | None = None, + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: ... +@overload +def make_archive( + base_name: str | os.PathLike[str], + format: str, + root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes], + base_dir: str | None = None, + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: ... +def make_archive( + base_name: str | os.PathLike[str], + format: str, + root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None, + base_dir: str | None = None, + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: + """Create an archive file (eg. zip or tar). + + 'base_name' is the name of the file to create, minus any format-specific + extension; 'format' is the archive format: one of "zip", "tar", "gztar", + "bztar", "xztar", or "ztar". + + 'root_dir' is a directory that will be the root directory of the + archive; ie. we typically chdir into 'root_dir' before creating the + archive. 'base_dir' is the directory where we start archiving from; + ie. 'base_dir' will be the common prefix of all files and + directories in the archive. 'root_dir' and 'base_dir' both default + to the current directory. Returns the name of the archive file. + + 'owner' and 'group' are used when creating a tar archive. By default, + uses the current owner and group. + """ + save_cwd = os.getcwd() + if root_dir is not None: + log.debug("changing into '%s'", root_dir) + base_name = os.path.abspath(base_name) + os.chdir(root_dir) + + if base_dir is None: + base_dir = os.curdir + + kwargs: dict[str, bool | None] = {} + + try: + format_info = ARCHIVE_FORMATS[format] + except KeyError: + raise ValueError(f"unknown archive format '{format}'") + + func = format_info[0] + kwargs.update(format_info[1]) + + if format != 'zip': + kwargs['owner'] = owner + kwargs['group'] = group + + try: + filename = func(base_name, base_dir, **kwargs) + finally: + if root_dir is not None: + log.debug("changing back to '%s'", save_cwd) + os.chdir(save_cwd) + + return filename diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/ccompiler.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/ccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..58bc6a55e24fd2b0b170e4499c6095e934313827 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/ccompiler.py @@ -0,0 +1,26 @@ +from .compat.numpy import ( # noqa: F401 + _default_compilers, + compiler_class, +) +from .compilers.C import base +from .compilers.C.base import ( + gen_lib_options, + gen_preprocess_options, + get_default_compiler, + new_compiler, + show_compilers, +) +from .compilers.C.errors import CompileError, LinkError + +__all__ = [ + 'CompileError', + 'LinkError', + 'gen_lib_options', + 'gen_preprocess_options', + 'get_default_compiler', + 'new_compiler', + 'show_compilers', +] + + +CCompiler = base.Compiler diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/cmd.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..530cc108d4743ed26fdf0dd7a8eef204d309b5de --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/cmd.py @@ -0,0 +1,535 @@ +"""distutils.cmd + +Provides the Command class, the base class for the command classes +in the distutils.command package. +""" + +from __future__ import annotations + +import logging +import os +import re +import sys +from abc import abstractmethod +from collections.abc import Callable, MutableSequence +from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, overload + +from . import _modified, archive_util, dir_util, file_util, util +from ._log import log +from .errors import DistutilsOptionError + +if TYPE_CHECKING: + # type-only import because of mutual dependence between these classes + from distutils.dist import Distribution + + from typing_extensions import TypeVarTuple, Unpack + + _Ts = TypeVarTuple("_Ts") + +_StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]") +_BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]") +_CommandT = TypeVar("_CommandT", bound="Command") + + +class Command: + """Abstract base class for defining command classes, the "worker bees" + of the Distutils. A useful analogy for command classes is to think of + them as subroutines with local variables called "options". The options + are "declared" in 'initialize_options()' and "defined" (given their + final values, aka "finalized") in 'finalize_options()', both of which + must be defined by every command class. The distinction between the + two is necessary because option values might come from the outside + world (command line, config file, ...), and any options dependent on + other options must be computed *after* these outside influences have + been processed -- hence 'finalize_options()'. The "body" of the + subroutine, where it does all its work based on the values of its + options, is the 'run()' method, which must also be implemented by every + command class. + """ + + # 'sub_commands' formalizes the notion of a "family" of commands, + # eg. "install" as the parent with sub-commands "install_lib", + # "install_headers", etc. The parent of a family of commands + # defines 'sub_commands' as a class attribute; it's a list of + # (command_name : string, predicate : unbound_method | string | None) + # tuples, where 'predicate' is a method of the parent command that + # determines whether the corresponding command is applicable in the + # current situation. (Eg. we "install_headers" is only applicable if + # we have any C header files to install.) If 'predicate' is None, + # that command is always applicable. + # + # 'sub_commands' is usually defined at the *end* of a class, because + # predicates can be unbound methods, so they must already have been + # defined. The canonical example is the "install" command. + sub_commands: ClassVar[ # Any to work around variance issues + list[tuple[str, Callable[[Any], bool] | None]] + ] = [] + + user_options: ClassVar[ + # Specifying both because list is invariant. Avoids mypy override assignment issues + list[tuple[str, str, str]] | list[tuple[str, str | None, str]] + ] = [] + + # -- Creation/initialization methods ------------------------------- + + def __init__(self, dist: Distribution) -> None: + """Create and initialize a new Command object. Most importantly, + invokes the 'initialize_options()' method, which is the real + initializer and depends on the actual command being + instantiated. + """ + # late import because of mutual dependence between these classes + from distutils.dist import Distribution + + if not isinstance(dist, Distribution): + raise TypeError("dist must be a Distribution instance") + if self.__class__ is Command: + raise RuntimeError("Command is an abstract class") + + self.distribution = dist + self.initialize_options() + + # Per-command versions of the global flags, so that the user can + # customize Distutils' behaviour command-by-command and let some + # commands fall back on the Distribution's behaviour. None means + # "not defined, check self.distribution's copy". + + # verbose is largely ignored, but needs to be set for + # backwards compatibility (I think)? + self.verbose = dist.verbose + + # Some commands define a 'self.force' option to ignore file + # timestamps, but methods defined *here* assume that + # 'self.force' exists for all commands. So define it here + # just to be safe. + self.force = None + + # The 'help' flag is just used for command-line parsing, so + # none of that complicated bureaucracy is needed. + self.help = False + + # 'finalized' records whether or not 'finalize_options()' has been + # called. 'finalize_options()' itself should not pay attention to + # this flag: it is the business of 'ensure_finalized()', which + # always calls 'finalize_options()', to respect/update it. + self.finalized = False + + def ensure_finalized(self) -> None: + if not self.finalized: + self.finalize_options() + self.finalized = True + + # Subclasses must define: + # initialize_options() + # provide default values for all options; may be customized by + # setup script, by options from config file(s), or by command-line + # options + # finalize_options() + # decide on the final values for all options; this is called + # after all possible intervention from the outside world + # (command-line, option file, etc.) has been processed + # run() + # run the command: do whatever it is we're here to do, + # controlled by the command's various option values + + @abstractmethod + def initialize_options(self) -> None: + """Set default values for all the options that this command + supports. Note that these defaults may be overridden by other + commands, by the setup script, by config files, or by the + command-line. Thus, this is not the place to code dependencies + between options; generally, 'initialize_options()' implementations + are just a bunch of "self.foo = None" assignments. + + This method must be implemented by all command classes. + """ + raise RuntimeError( + f"abstract method -- subclass {self.__class__} must override" + ) + + @abstractmethod + def finalize_options(self) -> None: + """Set final values for all the options that this command supports. + This is always called as late as possible, ie. after any option + assignments from the command-line or from other commands have been + done. Thus, this is the place to code option dependencies: if + 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as + long as 'foo' still has the same value it was assigned in + 'initialize_options()'. + + This method must be implemented by all command classes. + """ + raise RuntimeError( + f"abstract method -- subclass {self.__class__} must override" + ) + + def dump_options(self, header=None, indent=""): + from distutils.fancy_getopt import longopt_xlate + + if header is None: + header = f"command options for '{self.get_command_name()}':" + self.announce(indent + header, level=logging.INFO) + indent = indent + " " + for option, _, _ in self.user_options: + option = option.translate(longopt_xlate) + if option[-1] == "=": + option = option[:-1] + value = getattr(self, option) + self.announce(indent + f"{option} = {value}", level=logging.INFO) + + @abstractmethod + def run(self) -> None: + """A command's raison d'etre: carry out the action it exists to + perform, controlled by the options initialized in + 'initialize_options()', customized by other commands, the setup + script, the command-line, and config files, and finalized in + 'finalize_options()'. All terminal output and filesystem + interaction should be done by 'run()'. + + This method must be implemented by all command classes. + """ + raise RuntimeError( + f"abstract method -- subclass {self.__class__} must override" + ) + + def announce(self, msg: object, level: int = logging.DEBUG) -> None: + log.log(level, msg) + + def debug_print(self, msg: object) -> None: + """Print 'msg' to stdout if the global DEBUG (taken from the + DISTUTILS_DEBUG environment variable) flag is true. + """ + from distutils.debug import DEBUG + + if DEBUG: + print(msg) + sys.stdout.flush() + + # -- Option validation methods ------------------------------------- + # (these are very handy in writing the 'finalize_options()' method) + # + # NB. the general philosophy here is to ensure that a particular option + # value meets certain type and value constraints. If not, we try to + # force it into conformance (eg. if we expect a list but have a string, + # split the string on comma and/or whitespace). If we can't force the + # option into conformance, raise DistutilsOptionError. Thus, command + # classes need do nothing more than (eg.) + # self.ensure_string_list('foo') + # and they can be guaranteed that thereafter, self.foo will be + # a list of strings. + + def _ensure_stringlike(self, option, what, default=None): + val = getattr(self, option) + if val is None: + setattr(self, option, default) + return default + elif not isinstance(val, str): + raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)") + return val + + def ensure_string(self, option: str, default: str | None = None) -> None: + """Ensure that 'option' is a string; if not defined, set it to + 'default'. + """ + self._ensure_stringlike(option, "string", default) + + def ensure_string_list(self, option: str) -> None: + r"""Ensure that 'option' is a list of strings. If 'option' is + currently a string, we split it either on /,\s*/ or /\s+/, so + "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become + ["foo", "bar", "baz"]. + """ + val = getattr(self, option) + if val is None: + return + elif isinstance(val, str): + setattr(self, option, re.split(r',\s*|\s+', val)) + else: + if isinstance(val, list): + ok = all(isinstance(v, str) for v in val) + else: + ok = False + if not ok: + raise DistutilsOptionError( + f"'{option}' must be a list of strings (got {val!r})" + ) + + def _ensure_tested_string(self, option, tester, what, error_fmt, default=None): + val = self._ensure_stringlike(option, what, default) + if val is not None and not tester(val): + raise DistutilsOptionError( + ("error in '%s' option: " + error_fmt) % (option, val) + ) + + def ensure_filename(self, option: str) -> None: + """Ensure that 'option' is the name of an existing file.""" + self._ensure_tested_string( + option, os.path.isfile, "filename", "'%s' does not exist or is not a file" + ) + + def ensure_dirname(self, option: str) -> None: + self._ensure_tested_string( + option, + os.path.isdir, + "directory name", + "'%s' does not exist or is not a directory", + ) + + # -- Convenience methods for commands ------------------------------ + + def get_command_name(self) -> str: + if hasattr(self, 'command_name'): + return self.command_name + else: + return self.__class__.__name__ + + def set_undefined_options( + self, src_cmd: str, *option_pairs: tuple[str, str] + ) -> None: + """Set the values of any "undefined" options from corresponding + option values in some other command object. "Undefined" here means + "is None", which is the convention used to indicate that an option + has not been changed between 'initialize_options()' and + 'finalize_options()'. Usually called from 'finalize_options()' for + options that depend on some other command rather than another + option of the same command. 'src_cmd' is the other command from + which option values will be taken (a command object will be created + for it if necessary); the remaining arguments are + '(src_option,dst_option)' tuples which mean "take the value of + 'src_option' in the 'src_cmd' command object, and copy it to + 'dst_option' in the current command object". + """ + # Option_pairs: list of (src_option, dst_option) tuples + src_cmd_obj = self.distribution.get_command_obj(src_cmd) + src_cmd_obj.ensure_finalized() + for src_option, dst_option in option_pairs: + if getattr(self, dst_option) is None: + setattr(self, dst_option, getattr(src_cmd_obj, src_option)) + + # NOTE: Because distutils is private to Setuptools and not all commands are exposed here, + # not every possible command is enumerated in the signature. + def get_finalized_command(self, command: str, create: bool = True) -> Command: + """Wrapper around Distribution's 'get_command_obj()' method: find + (create if necessary and 'create' is true) the command object for + 'command', call its 'ensure_finalized()' method, and return the + finalized command object. + """ + cmd_obj = self.distribution.get_command_obj(command, create) + cmd_obj.ensure_finalized() + return cmd_obj + + # XXX rename to 'get_reinitialized_command()'? (should do the + # same in dist.py, if so) + @overload + def reinitialize_command( + self, command: str, reinit_subcommands: bool = False + ) -> Command: ... + @overload + def reinitialize_command( + self, command: _CommandT, reinit_subcommands: bool = False + ) -> _CommandT: ... + def reinitialize_command( + self, command: str | Command, reinit_subcommands=False + ) -> Command: + return self.distribution.reinitialize_command(command, reinit_subcommands) + + def run_command(self, command: str) -> None: + """Run some other command: uses the 'run_command()' method of + Distribution, which creates and finalizes the command object if + necessary and then invokes its 'run()' method. + """ + self.distribution.run_command(command) + + def get_sub_commands(self) -> list[str]: + """Determine the sub-commands that are relevant in the current + distribution (ie., that need to be run). This is based on the + 'sub_commands' class attribute: each tuple in that list may include + a method that we call to determine if the subcommand needs to be + run for the current distribution. Return a list of command names. + """ + commands = [] + for cmd_name, method in self.sub_commands: + if method is None or method(self): + commands.append(cmd_name) + return commands + + # -- External world manipulation ----------------------------------- + + def warn(self, msg: object) -> None: + log.warning("warning: %s: %s\n", self.get_command_name(), msg) + + def execute( + self, + func: Callable[[Unpack[_Ts]], object], + args: tuple[Unpack[_Ts]], + msg: object = None, + level: int = 1, + ) -> None: + util.execute(func, args, msg) + + def mkpath(self, name: str, mode: int = 0o777) -> None: + dir_util.mkpath(name, mode) + + @overload + def copy_file( + self, + infile: str | os.PathLike[str], + outfile: _StrPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: int = 1, + ) -> tuple[_StrPathT | str, bool]: ... + @overload + def copy_file( + self, + infile: bytes | os.PathLike[bytes], + outfile: _BytesPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: int = 1, + ) -> tuple[_BytesPathT | bytes, bool]: ... + def copy_file( + self, + infile: str | os.PathLike[str] | bytes | os.PathLike[bytes], + outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes], + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: int = 1, + ) -> tuple[str | os.PathLike[str] | bytes | os.PathLike[bytes], bool]: + """Copy a file respecting verbose, dry-run and force flags. (The + former two default to whatever is in the Distribution object, and + the latter defaults to false for commands that don't define it.)""" + return file_util.copy_file( + infile, + outfile, + preserve_mode, + preserve_times, + not self.force, + link, + ) + + def copy_tree( + self, + infile: str | os.PathLike[str], + outfile: str, + preserve_mode: bool = True, + preserve_times: bool = True, + preserve_symlinks: bool = False, + level: int = 1, + ) -> list[str]: + """Copy an entire directory tree respecting verbose, dry-run, + and force flags. + """ + return dir_util.copy_tree( + infile, + outfile, + preserve_mode, + preserve_times, + preserve_symlinks, + not self.force, + ) + + @overload + def move_file( + self, src: str | os.PathLike[str], dst: _StrPathT, level: int = 1 + ) -> _StrPathT | str: ... + @overload + def move_file( + self, src: bytes | os.PathLike[bytes], dst: _BytesPathT, level: int = 1 + ) -> _BytesPathT | bytes: ... + def move_file( + self, + src: str | os.PathLike[str] | bytes | os.PathLike[bytes], + dst: str | os.PathLike[str] | bytes | os.PathLike[bytes], + level: int = 1, + ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]: + """Move a file respecting dry-run flag.""" + return file_util.move_file(src, dst) + + def spawn( + self, cmd: MutableSequence[str], search_path: bool = True, level: int = 1 + ) -> None: + """Spawn an external command respecting dry-run flag.""" + from distutils.spawn import spawn + + spawn(cmd, search_path) + + @overload + def make_archive( + self, + base_name: str, + format: str, + root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + @overload + def make_archive( + self, + base_name: str | os.PathLike[str], + format: str, + root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes], + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + def make_archive( + self, + base_name: str | os.PathLike[str], + format: str, + root_dir: str | os.PathLike[str] | bytes | os.PathLike[bytes] | None = None, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: + return archive_util.make_archive( + base_name, + format, + root_dir, + base_dir, + owner=owner, + group=group, + ) + + def make_file( + self, + infiles: str | list[str] | tuple[str, ...], + outfile: str | os.PathLike[str] | bytes | os.PathLike[bytes], + func: Callable[[Unpack[_Ts]], object], + args: tuple[Unpack[_Ts]], + exec_msg: object = None, + skip_msg: object = None, + level: int = 1, + ) -> None: + """Special case of 'execute()' for operations that process one or + more input files and generate one output file. Works just like + 'execute()', except the operation is skipped and a different + message printed if 'outfile' already exists and is newer than all + files listed in 'infiles'. If the command defined 'self.force', + and it is true, then the command is unconditionally run -- does no + timestamp checks. + """ + if skip_msg is None: + skip_msg = f"skipping {outfile} (inputs unchanged)" + + # Allow 'infiles' to be a single string + if isinstance(infiles, str): + infiles = (infiles,) + elif not isinstance(infiles, (list, tuple)): + raise TypeError("'infiles' must be a string, or a list or tuple of strings") + + if exec_msg is None: + exec_msg = "generating {} from {}".format(outfile, ', '.join(infiles)) + + # If 'outfile' must be regenerated (either because it doesn't + # exist, is out-of-date, or the 'force' flag is true) then + # perform the action that presumably regenerates it + if self.force or _modified.newer_group(infiles, outfile): + self.execute(func, args, exec_msg, level) + # Otherwise, print the "skip" message + else: + log.debug(skip_msg) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0f8a1692ba96f5e03167e7307c1c2ff5776b74d6 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__init__.py @@ -0,0 +1,23 @@ +"""distutils.command + +Package containing implementation of all the standard Distutils +commands.""" + +__all__ = [ + 'build', + 'build_py', + 'build_ext', + 'build_clib', + 'build_scripts', + 'clean', + 'install', + 'install_lib', + 'install_headers', + 'install_scripts', + 'install_data', + 'sdist', + 'bdist', + 'bdist_dumb', + 'bdist_rpm', + 'check', +] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df018bad6992026854cf8b6d0c3c65f323b7d2fd Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/_framework_compat.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/_framework_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e002f7334b7fa5188ddf653af3cc4a57921d6bb Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/_framework_compat.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..170039ca66f5cbb4c9b40c8a9195bbefc5df93c7 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist_dumb.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist_dumb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1158d300d695dd28003b96425841a7e78fe8c07 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist_dumb.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist_rpm.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist_rpm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c3eb15e75fabd4fff2e5e82306e809357d7c46b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/bdist_rpm.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14a270ce5950a94a8236cd7b2b035087f1d6e646 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_clib.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_clib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f56f8d7a7088b70d57526d3887656a2244adcf8b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_clib.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_ext.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_ext.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68b8ab10ac9dfa793f4c81bb79b8834f7b799475 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_ext.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_py.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..720bf5f63a225f3653848a0ca714e3b5233ff63c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_py.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_scripts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_scripts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c5e47bfbd18f171f57796e6e2aa2560602ea078 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/build_scripts.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/check.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/check.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b973396b9d1d7c5321faac6cdc8c82adccf53fcd Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/check.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/clean.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/clean.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4d24ef89fb18075c4f6d106592af847c6661c3a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/clean.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/config.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b04a7aae036386c6a609e9688f94b8dbe7fc7444 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/config.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7f6ac2c4ca93ab4f2eb592ba7a3ce8c43521864 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_data.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_data.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbb320a0814f176ebf45dbc299e59a51d98758e1 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_data.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_egg_info.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_egg_info.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd1577f71513b70476dbee017a955668ab2f6cc1 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_egg_info.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_headers.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_headers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8374c80898c623203c945423d49f6d945c8e1de6 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_headers.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_lib.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_lib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c89cabd4c397240fc44f1dcee609d95d0a175eaa Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_lib.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_scripts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_scripts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0495987959142797c0ad7f293b84c3a26133479 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/install_scripts.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/sdist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/sdist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..958ba035fcb1b71250298485591a4a5b501c0c1b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/__pycache__/sdist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/_framework_compat.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/_framework_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..00d34bc7d8c85126dbae716ebfa48e35b0833222 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/_framework_compat.py @@ -0,0 +1,54 @@ +""" +Backward compatibility for homebrew builds on macOS. +""" + +import functools +import os +import subprocess +import sys +import sysconfig + + +@functools.lru_cache +def enabled(): + """ + Only enabled for Python 3.9 framework homebrew builds + except ensurepip and venv. + """ + PY39 = (3, 9) < sys.version_info < (3, 10) + framework = sys.platform == 'darwin' and sys._framework + homebrew = "Cellar" in sysconfig.get_config_var('projectbase') + venv = sys.prefix != sys.base_prefix + ensurepip = os.environ.get("ENSUREPIP_OPTIONS") + return PY39 and framework and homebrew and not venv and not ensurepip + + +schemes = dict( + osx_framework_library=dict( + stdlib='{installed_base}/{platlibdir}/python{py_version_short}', + platstdlib='{platbase}/{platlibdir}/python{py_version_short}', + purelib='{homebrew_prefix}/lib/python{py_version_short}/site-packages', + platlib='{homebrew_prefix}/{platlibdir}/python{py_version_short}/site-packages', + include='{installed_base}/include/python{py_version_short}{abiflags}', + platinclude='{installed_platbase}/include/python{py_version_short}{abiflags}', + scripts='{homebrew_prefix}/bin', + data='{homebrew_prefix}', + ) +) + + +@functools.lru_cache +def vars(): + if not enabled(): + return {} + homebrew_prefix = subprocess.check_output(['brew', '--prefix'], text=True).strip() + return locals() + + +def scheme(name): + """ + Override the selected scheme for posix_prefix. + """ + if not enabled() or not name.endswith('_prefix'): + return name + return 'osx_framework_library' diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist.py new file mode 100644 index 0000000000000000000000000000000000000000..07811aab27ad7fcd2303883024243e2f52c2bbcb --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist.py @@ -0,0 +1,167 @@ +"""distutils.command.bdist + +Implements the Distutils 'bdist' command (create a built [binary] +distribution).""" + +from __future__ import annotations + +import os +import warnings +from collections.abc import Callable +from typing import TYPE_CHECKING, ClassVar + +from ..core import Command +from ..errors import DistutilsOptionError, DistutilsPlatformError +from ..util import get_platform + +if TYPE_CHECKING: + from typing_extensions import deprecated +else: + + def deprecated(message): + return lambda fn: fn + + +def show_formats(): + """Print list of available formats (arguments to "--format" option).""" + from ..fancy_getopt import FancyGetopt + + formats = [ + ("formats=" + format, None, bdist.format_commands[format][1]) + for format in bdist.format_commands + ] + pretty_printer = FancyGetopt(formats) + pretty_printer.print_help("List of available distribution formats:") + + +class ListCompat(dict[str, tuple[str, str]]): + # adapter to allow for Setuptools compatibility in format_commands + @deprecated("format_commands is now a dict. append is deprecated.") + def append(self, item: object) -> None: + warnings.warn( + "format_commands is now a dict. append is deprecated.", + DeprecationWarning, + stacklevel=2, + ) + + +class bdist(Command): + description = "create a built (binary) distribution" + + user_options = [ + ('bdist-base=', 'b', "temporary directory for creating built distributions"), + ( + 'plat-name=', + 'p', + "platform name to embed in generated filenames " + f"[default: {get_platform()}]", + ), + ('formats=', None, "formats for distribution (comma-separated list)"), + ( + 'dist-dir=', + 'd', + "directory to put final built distributions in [default: dist]", + ), + ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), + ( + '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]", + ), + ] + + boolean_options: ClassVar[list[str]] = ['skip-build'] + + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [ + ('help-formats', None, "lists available distribution formats", show_formats), + ] + + # The following commands do not take a format option from bdist + no_format_option: ClassVar[tuple[str, ...]] = ('bdist_rpm',) + + # This won't do in reality: will need to distinguish RPM-ish Linux, + # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS. + default_format: ClassVar[dict[str, str]] = {'posix': 'gztar', 'nt': 'zip'} + + # Define commands in preferred order for the --help-formats option + format_commands = ListCompat({ + 'rpm': ('bdist_rpm', "RPM distribution"), + 'gztar': ('bdist_dumb', "gzip'ed tar file"), + 'bztar': ('bdist_dumb', "bzip2'ed tar file"), + 'xztar': ('bdist_dumb', "xz'ed tar file"), + 'ztar': ('bdist_dumb', "compressed tar file"), + 'tar': ('bdist_dumb', "tar file"), + 'zip': ('bdist_dumb', "ZIP file"), + }) + + # for compatibility until consumers only reference format_commands + format_command = format_commands + + def initialize_options(self): + self.bdist_base = None + self.plat_name = None + self.formats = None + self.dist_dir = None + self.skip_build = False + self.group = None + self.owner = None + + def finalize_options(self) -> None: + # have to finalize 'plat_name' before 'bdist_base' + if self.plat_name is None: + if self.skip_build: + self.plat_name = get_platform() + else: + self.plat_name = self.get_finalized_command('build').plat_name + + # 'bdist_base' -- parent of per-built-distribution-format + # temporary directories (eg. we'll probably have + # "build/bdist./dumb", "build/bdist./rpm", etc.) + if self.bdist_base is None: + build_base = self.get_finalized_command('build').build_base + self.bdist_base = os.path.join(build_base, 'bdist.' + self.plat_name) + + self.ensure_string_list('formats') + if self.formats is None: + try: + self.formats = [self.default_format[os.name]] + except KeyError: + raise DistutilsPlatformError( + "don't know how to create built distributions " + f"on platform {os.name}" + ) + + if self.dist_dir is None: + self.dist_dir = "dist" + + def run(self) -> None: + # Figure out which sub-commands we need to run. + commands = [] + for format in self.formats: + try: + commands.append(self.format_commands[format][0]) + except KeyError: + raise DistutilsOptionError(f"invalid format '{format}'") + + # Reinitialize and run each command. + for i in range(len(self.formats)): + cmd_name = commands[i] + sub_cmd = self.reinitialize_command(cmd_name) + if cmd_name not in self.no_format_option: + sub_cmd.format = self.formats[i] + + # passing the owner and group names for tar archiving + if cmd_name == 'bdist_dumb': + sub_cmd.owner = self.owner + sub_cmd.group = self.group + + # If we're going to need to run this command again, tell it to + # keep its temporary files around so subsequent runs go faster. + if cmd_name in commands[i + 1 :]: + sub_cmd.keep_temp = True + self.run_command(cmd_name) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist_dumb.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist_dumb.py new file mode 100644 index 0000000000000000000000000000000000000000..c49ef253b47cd0791aae1fc65c005c668cb1e97b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist_dumb.py @@ -0,0 +1,141 @@ +"""distutils.command.bdist_dumb + +Implements the Distutils 'bdist_dumb' command (create a "dumb" built +distribution -- i.e., just an archive to be unpacked under $prefix or +$exec_prefix).""" + +import os +from distutils._log import log +from typing import ClassVar + +from ..core import Command +from ..dir_util import ensure_relative, remove_tree +from ..errors import DistutilsPlatformError +from ..sysconfig import get_python_version +from ..util import get_platform + + +class bdist_dumb(Command): + description = "create a \"dumb\" built distribution" + + user_options = [ + ('bdist-dir=', 'd', "temporary directory for creating the distribution"), + ( + 'plat-name=', + 'p', + "platform name to embed in generated filenames " + f"[default: {get_platform()}]", + ), + ( + 'format=', + 'f', + "archive format to create (tar, gztar, bztar, xztar, ztar, zip)", + ), + ( + '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]", + ), + ] + + boolean_options: ClassVar[list[str]] = ['keep-temp', 'skip-build', 'relative'] + + default_format = {'posix': 'gztar', 'nt': 'zip'} + + def initialize_options(self): + self.bdist_dir = None + self.plat_name = None + self.format = None + self.keep_temp = False + self.dist_dir = None + self.skip_build = None + self.relative = False + self.owner = None + self.group = None + + 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, 'dumb') + + if self.format is None: + try: + self.format = self.default_format[os.name] + except KeyError: + raise DistutilsPlatformError( + "don't know how to create dumb built distributions " + f"on platform {os.name}" + ) + + self.set_undefined_options( + 'bdist', + ('dist_dir', 'dist_dir'), + ('plat_name', 'plat_name'), + ('skip_build', 'skip_build'), + ) + + def run(self): + if not self.skip_build: + self.run_command('build') + + install = self.reinitialize_command('install', reinit_subcommands=True) + install.root = self.bdist_dir + install.skip_build = self.skip_build + install.warn_dir = False + + log.info("installing to %s", self.bdist_dir) + self.run_command('install') + + # And make an archive relative to the root of the + # pseudo-installation tree. + archive_basename = f"{self.distribution.get_fullname()}.{self.plat_name}" + + pseudoinstall_root = os.path.join(self.dist_dir, archive_basename) + if not self.relative: + archive_root = self.bdist_dir + else: + if self.distribution.has_ext_modules() and ( + install.install_base != install.install_platbase + ): + raise DistutilsPlatformError( + "can't make a dumb built distribution where " + f"base and platbase are different ({install.install_base!r}, {install.install_platbase!r})" + ) + else: + archive_root = os.path.join( + self.bdist_dir, ensure_relative(install.install_base) + ) + + # Make the archive + filename = self.make_archive( + pseudoinstall_root, + self.format, + root_dir=archive_root, + owner=self.owner, + group=self.group, + ) + if self.distribution.has_ext_modules(): + pyversion = get_python_version() + else: + pyversion = 'any' + self.distribution.dist_files.append(('bdist_dumb', pyversion, filename)) + + if not self.keep_temp: + remove_tree(self.bdist_dir) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist_rpm.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist_rpm.py new file mode 100644 index 0000000000000000000000000000000000000000..dfa5f99dda095af76d8ffac33e1dd8bfd6aad931 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/bdist_rpm.py @@ -0,0 +1,597 @@ +"""distutils.command.bdist_rpm + +Implements the Distutils 'bdist_rpm' command (create RPM source and binary +distributions).""" + +import os +import subprocess +import sys +from distutils._log import log +from typing import ClassVar + +from ..core import Command +from ..debug import DEBUG +from ..errors import ( + DistutilsExecError, + DistutilsFileError, + DistutilsOptionError, + DistutilsPlatformError, +) +from ..file_util import write_file +from ..sysconfig import get_python_version + + +class bdist_rpm(Command): + description = "create an RPM distribution" + + user_options = [ + ('bdist-base=', None, "base directory for creating built distributions"), + ( + 'rpm-base=', + None, + "base directory for creating RPMs (defaults to \"rpm\" under " + "--bdist-base; must be specified for RPM 2)", + ), + ( + 'dist-dir=', + 'd', + "directory to put final RPM files in (and .spec files if --spec-only)", + ), + ( + 'python=', + None, + "path to Python interpreter to hard-code in the .spec file " + "[default: \"python\"]", + ), + ( + 'fix-python', + None, + "hard-code the exact path to the current Python interpreter in " + "the .spec file", + ), + ('spec-only', None, "only regenerate spec file"), + ('source-only', None, "only generate source RPM"), + ('binary-only', None, "only generate binary RPM"), + ('use-bzip2', None, "use bzip2 instead of gzip to create source distribution"), + # More meta-data: too RPM-specific to put in the setup script, + # but needs to go in the .spec file -- so we make these options + # to "bdist_rpm". The idea is that packagers would put this + # info in setup.cfg, although they are of course free to + # supply it on the command line. + ( + 'distribution-name=', + None, + "name of the (Linux) distribution to which this " + "RPM applies (*not* the name of the module distribution!)", + ), + ('group=', None, "package classification [default: \"Development/Libraries\"]"), + ('release=', None, "RPM release number"), + ('serial=', None, "RPM serial number"), + ( + 'vendor=', + None, + "RPM \"vendor\" (eg. \"Joe Blow \") " + "[default: maintainer or author from setup script]", + ), + ( + 'packager=', + None, + "RPM packager (eg. \"Jane Doe \") [default: vendor]", + ), + ('doc-files=', None, "list of documentation files (space or comma-separated)"), + ('changelog=', None, "RPM changelog"), + ('icon=', None, "name of icon file"), + ('provides=', None, "capabilities provided by this package"), + ('requires=', None, "capabilities required by this package"), + ('conflicts=', None, "capabilities which conflict with this package"), + ('build-requires=', None, "capabilities required to build this package"), + ('obsoletes=', None, "capabilities made obsolete by this package"), + ('no-autoreq', None, "do not automatically calculate dependencies"), + # Actions to take when building RPM + ('keep-temp', 'k', "don't clean up RPM build directory"), + ('no-keep-temp', None, "clean up RPM build directory [default]"), + ( + 'use-rpm-opt-flags', + None, + "compile with RPM_OPT_FLAGS when building from source RPM", + ), + ('no-rpm-opt-flags', None, "do not pass any RPM CFLAGS to compiler"), + ('rpm3-mode', None, "RPM 3 compatibility mode (default)"), + ('rpm2-mode', None, "RPM 2 compatibility mode"), + # Add the hooks necessary for specifying custom scripts + ('prep-script=', None, "Specify a script for the PREP phase of RPM building"), + ('build-script=', None, "Specify a script for the BUILD phase of RPM building"), + ( + 'pre-install=', + None, + "Specify a script for the pre-INSTALL phase of RPM building", + ), + ( + 'install-script=', + None, + "Specify a script for the INSTALL phase of RPM building", + ), + ( + 'post-install=', + None, + "Specify a script for the post-INSTALL phase of RPM building", + ), + ( + 'pre-uninstall=', + None, + "Specify a script for the pre-UNINSTALL phase of RPM building", + ), + ( + 'post-uninstall=', + None, + "Specify a script for the post-UNINSTALL phase of RPM building", + ), + ('clean-script=', None, "Specify a script for the CLEAN phase of RPM building"), + ( + 'verify-script=', + None, + "Specify a script for the VERIFY phase of the RPM build", + ), + # Allow a packager to explicitly force an architecture + ('force-arch=', None, "Force an architecture onto the RPM build process"), + ('quiet', 'q', "Run the INSTALL phase of RPM building in quiet mode"), + ] + + boolean_options: ClassVar[list[str]] = [ + 'keep-temp', + 'use-rpm-opt-flags', + 'rpm3-mode', + 'no-autoreq', + 'quiet', + ] + + negative_opt: ClassVar[dict[str, str]] = { + 'no-keep-temp': 'keep-temp', + 'no-rpm-opt-flags': 'use-rpm-opt-flags', + 'rpm2-mode': 'rpm3-mode', + } + + def initialize_options(self): + self.bdist_base = None + self.rpm_base = None + self.dist_dir = None + self.python = None + self.fix_python = None + self.spec_only = None + self.binary_only = None + self.source_only = None + self.use_bzip2 = None + + self.distribution_name = None + self.group = None + self.release = None + self.serial = None + self.vendor = None + self.packager = None + self.doc_files = None + self.changelog = None + self.icon = None + + self.prep_script = None + self.build_script = None + self.install_script = None + self.clean_script = None + self.verify_script = None + self.pre_install = None + self.post_install = None + self.pre_uninstall = None + self.post_uninstall = None + self.prep = None + self.provides = None + self.requires = None + self.conflicts = None + self.build_requires = None + self.obsoletes = None + + self.keep_temp = False + self.use_rpm_opt_flags = True + self.rpm3_mode = True + self.no_autoreq = False + + self.force_arch = None + self.quiet = False + + def finalize_options(self) -> None: + self.set_undefined_options('bdist', ('bdist_base', 'bdist_base')) + if self.rpm_base is None: + if not self.rpm3_mode: + raise DistutilsOptionError("you must specify --rpm-base in RPM 2 mode") + self.rpm_base = os.path.join(self.bdist_base, "rpm") + + if self.python is None: + if self.fix_python: + self.python = sys.executable + else: + self.python = "python3" + elif self.fix_python: + raise DistutilsOptionError( + "--python and --fix-python are mutually exclusive options" + ) + + if os.name != 'posix': + raise DistutilsPlatformError( + f"don't know how to create RPM distributions on platform {os.name}" + ) + if self.binary_only and self.source_only: + raise DistutilsOptionError( + "cannot supply both '--source-only' and '--binary-only'" + ) + + # don't pass CFLAGS to pure python distributions + if not self.distribution.has_ext_modules(): + self.use_rpm_opt_flags = False + + self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) + self.finalize_package_data() + + def finalize_package_data(self) -> None: + self.ensure_string('group', "Development/Libraries") + self.ensure_string( + 'vendor', + f"{self.distribution.get_contact()} <{self.distribution.get_contact_email()}>", + ) + self.ensure_string('packager') + self.ensure_string_list('doc_files') + if isinstance(self.doc_files, list): + for readme in ('README', 'README.txt'): + if os.path.exists(readme) and readme not in self.doc_files: + self.doc_files.append(readme) + + self.ensure_string('release', "1") + self.ensure_string('serial') # should it be an int? + + self.ensure_string('distribution_name') + + self.ensure_string('changelog') + # Format changelog correctly + self.changelog = self._format_changelog(self.changelog) + + self.ensure_filename('icon') + + self.ensure_filename('prep_script') + self.ensure_filename('build_script') + self.ensure_filename('install_script') + self.ensure_filename('clean_script') + self.ensure_filename('verify_script') + self.ensure_filename('pre_install') + self.ensure_filename('post_install') + self.ensure_filename('pre_uninstall') + self.ensure_filename('post_uninstall') + + # XXX don't forget we punted on summaries and descriptions -- they + # should be handled here eventually! + + # Now *this* is some meta-data that belongs in the setup script... + self.ensure_string_list('provides') + self.ensure_string_list('requires') + self.ensure_string_list('conflicts') + self.ensure_string_list('build_requires') + self.ensure_string_list('obsoletes') + + self.ensure_string('force_arch') + + def run(self) -> None: # noqa: C901 + if DEBUG: + print("before _get_package_data():") + print("vendor =", self.vendor) + print("packager =", self.packager) + print("doc_files =", self.doc_files) + print("changelog =", self.changelog) + + # make directories + if self.spec_only: + spec_dir = self.dist_dir + self.mkpath(spec_dir) + else: + rpm_dir = {} + for d in ('SOURCES', 'SPECS', 'BUILD', 'RPMS', 'SRPMS'): + rpm_dir[d] = os.path.join(self.rpm_base, d) + self.mkpath(rpm_dir[d]) + spec_dir = rpm_dir['SPECS'] + + # Spec file goes into 'dist_dir' if '--spec-only specified', + # build/rpm. otherwise. + spec_path = os.path.join(spec_dir, f"{self.distribution.get_name()}.spec") + self.execute( + write_file, (spec_path, self._make_spec_file()), f"writing '{spec_path}'" + ) + + if self.spec_only: # stop if requested + return + + # Make a source distribution and copy to SOURCES directory with + # optional icon. + saved_dist_files = self.distribution.dist_files[:] + sdist = self.reinitialize_command('sdist') + if self.use_bzip2: + sdist.formats = ['bztar'] + else: + sdist.formats = ['gztar'] + self.run_command('sdist') + self.distribution.dist_files = saved_dist_files + + source = sdist.get_archive_files()[0] + source_dir = rpm_dir['SOURCES'] + self.copy_file(source, source_dir) + + if self.icon: + if os.path.exists(self.icon): + self.copy_file(self.icon, source_dir) + else: + raise DistutilsFileError(f"icon file '{self.icon}' does not exist") + + # build package + log.info("building RPMs") + rpm_cmd = ['rpmbuild'] + + if self.source_only: # what kind of RPMs? + rpm_cmd.append('-bs') + elif self.binary_only: + rpm_cmd.append('-bb') + else: + rpm_cmd.append('-ba') + rpm_cmd.extend(['--define', f'__python {self.python}']) + if self.rpm3_mode: + rpm_cmd.extend(['--define', f'_topdir {os.path.abspath(self.rpm_base)}']) + if not self.keep_temp: + rpm_cmd.append('--clean') + + if self.quiet: + rpm_cmd.append('--quiet') + + rpm_cmd.append(spec_path) + # Determine the binary rpm names that should be built out of this spec + # file + # Note that some of these may not be really built (if the file + # list is empty) + nvr_string = "%{name}-%{version}-%{release}" + src_rpm = nvr_string + ".src.rpm" + non_src_rpm = "%{arch}/" + nvr_string + ".%{arch}.rpm" + q_cmd = rf"rpm -q --qf '{src_rpm} {non_src_rpm}\n' --specfile '{spec_path}'" + + out = os.popen(q_cmd) + try: + binary_rpms = [] + source_rpm = None + while True: + line = out.readline() + if not line: + break + ell = line.strip().split() + assert len(ell) == 2 + binary_rpms.append(ell[1]) + # The source rpm is named after the first entry in the spec file + if source_rpm is None: + source_rpm = ell[0] + + status = out.close() + if status: + raise DistutilsExecError(f"Failed to execute: {q_cmd!r}") + + finally: + out.close() + + self.spawn(rpm_cmd) + + if self.distribution.has_ext_modules(): + pyversion = get_python_version() + else: + pyversion = 'any' + + if not self.binary_only: + srpm = os.path.join(rpm_dir['SRPMS'], source_rpm) + assert os.path.exists(srpm) + self.move_file(srpm, self.dist_dir) + filename = os.path.join(self.dist_dir, source_rpm) + self.distribution.dist_files.append(('bdist_rpm', pyversion, filename)) + + if not self.source_only: + for rpm in binary_rpms: + rpm = os.path.join(rpm_dir['RPMS'], rpm) + if os.path.exists(rpm): + self.move_file(rpm, self.dist_dir) + filename = os.path.join(self.dist_dir, os.path.basename(rpm)) + self.distribution.dist_files.append(( + 'bdist_rpm', + pyversion, + filename, + )) + + def _dist_path(self, path): + return os.path.join(self.dist_dir, os.path.basename(path)) + + def _make_spec_file(self): # noqa: C901 + """Generate the text of an RPM spec file and return it as a + list of strings (one per line). + """ + # definitions and headers + spec_file = [ + '%define name ' + self.distribution.get_name(), + '%define version ' + self.distribution.get_version().replace('-', '_'), + '%define unmangled_version ' + self.distribution.get_version(), + '%define release ' + self.release.replace('-', '_'), + '', + 'Summary: ' + (self.distribution.get_description() or "UNKNOWN"), + ] + + # Workaround for #14443 which affects some RPM based systems such as + # RHEL6 (and probably derivatives) + vendor_hook = subprocess.getoutput('rpm --eval %{__os_install_post}') + # Generate a potential replacement value for __os_install_post (whilst + # normalizing the whitespace to simplify the test for whether the + # invocation of brp-python-bytecompile passes in __python): + vendor_hook = '\n'.join([ + f' {line.strip()} \\' for line in vendor_hook.splitlines() + ]) + problem = "brp-python-bytecompile \\\n" + fixed = "brp-python-bytecompile %{__python} \\\n" + fixed_hook = vendor_hook.replace(problem, fixed) + if fixed_hook != vendor_hook: + spec_file.append('# Workaround for https://bugs.python.org/issue14443') + spec_file.append('%define __os_install_post ' + fixed_hook + '\n') + + # put locale summaries into spec file + # XXX not supported for now (hard to put a dictionary + # in a config file -- arg!) + # for locale in self.summaries.keys(): + # spec_file.append('Summary(%s): %s' % (locale, + # self.summaries[locale])) + + spec_file.extend([ + 'Name: %{name}', + 'Version: %{version}', + 'Release: %{release}', + ]) + + # XXX yuck! this filename is available from the "sdist" command, + # but only after it has run: and we create the spec file before + # running "sdist", in case of --spec-only. + if self.use_bzip2: + spec_file.append('Source0: %{name}-%{unmangled_version}.tar.bz2') + else: + spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz') + + spec_file.extend([ + 'License: ' + (self.distribution.get_license() or "UNKNOWN"), + 'Group: ' + self.group, + 'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot', + 'Prefix: %{_prefix}', + ]) + + if not self.force_arch: + # noarch if no extension modules + if not self.distribution.has_ext_modules(): + spec_file.append('BuildArch: noarch') + else: + spec_file.append(f'BuildArch: {self.force_arch}') + + for field in ( + 'Vendor', + 'Packager', + 'Provides', + 'Requires', + 'Conflicts', + 'Obsoletes', + ): + val = getattr(self, field.lower()) + if isinstance(val, list): + spec_file.append('{}: {}'.format(field, ' '.join(val))) + elif val is not None: + spec_file.append(f'{field}: {val}') + + if self.distribution.get_url(): + spec_file.append('Url: ' + self.distribution.get_url()) + + if self.distribution_name: + spec_file.append('Distribution: ' + self.distribution_name) + + if self.build_requires: + spec_file.append('BuildRequires: ' + ' '.join(self.build_requires)) + + if self.icon: + spec_file.append('Icon: ' + os.path.basename(self.icon)) + + if self.no_autoreq: + spec_file.append('AutoReq: 0') + + spec_file.extend([ + '', + '%description', + self.distribution.get_long_description() or "", + ]) + + # put locale descriptions into spec file + # XXX again, suppressed because config file syntax doesn't + # easily support this ;-( + # for locale in self.descriptions.keys(): + # spec_file.extend([ + # '', + # '%description -l ' + locale, + # self.descriptions[locale], + # ]) + + # rpm scripts + # figure out default build script + def_setup_call = f"{self.python} {os.path.basename(sys.argv[0])}" + def_build = f"{def_setup_call} build" + if self.use_rpm_opt_flags: + def_build = 'env CFLAGS="$RPM_OPT_FLAGS" ' + def_build + + # insert contents of files + + # XXX this is kind of misleading: user-supplied options are files + # that we open and interpolate into the spec file, but the defaults + # are just text that we drop in as-is. Hmmm. + + install_cmd = f'{def_setup_call} install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES' + + script_options = [ + ('prep', 'prep_script', "%setup -n %{name}-%{unmangled_version}"), + ('build', 'build_script', def_build), + ('install', 'install_script', install_cmd), + ('clean', 'clean_script', "rm -rf $RPM_BUILD_ROOT"), + ('verifyscript', 'verify_script', None), + ('pre', 'pre_install', None), + ('post', 'post_install', None), + ('preun', 'pre_uninstall', None), + ('postun', 'post_uninstall', None), + ] + + for rpm_opt, attr, default in script_options: + # Insert contents of file referred to, if no file is referred to + # use 'default' as contents of script + val = getattr(self, attr) + if val or default: + spec_file.extend([ + '', + '%' + rpm_opt, + ]) + if val: + with open(val) as f: + spec_file.extend(f.read().split('\n')) + else: + spec_file.append(default) + + # files section + spec_file.extend([ + '', + '%files -f INSTALLED_FILES', + '%defattr(-,root,root)', + ]) + + if self.doc_files: + spec_file.append('%doc ' + ' '.join(self.doc_files)) + + if self.changelog: + spec_file.extend([ + '', + '%changelog', + ]) + spec_file.extend(self.changelog) + + return spec_file + + def _format_changelog(self, changelog): + """Format the changelog correctly and convert it to a list of strings""" + if not changelog: + return changelog + new_changelog = [] + for line in changelog.strip().split('\n'): + line = line.strip() + if line[0] == '*': + new_changelog.extend(['', line]) + elif line[0] == '-': + new_changelog.append(line) + else: + new_changelog.append(' ' + line) + + # strip trailing newline inserted by first changelog entry + if not new_changelog[0]: + del new_changelog[0] + + return new_changelog diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build.py new file mode 100644 index 0000000000000000000000000000000000000000..6a8303a954ea705c547e2014dc6b51d9d987a532 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build.py @@ -0,0 +1,156 @@ +"""distutils.command.build + +Implements the Distutils 'build' command.""" + +from __future__ import annotations + +import os +import sys +import sysconfig +from collections.abc import Callable +from typing import ClassVar + +from ..ccompiler import show_compilers +from ..core import Command +from ..errors import DistutilsOptionError +from ..util import get_platform + + +class build(Command): + description = "build everything needed to install" + + user_options = [ + ('build-base=', 'b', "base directory for build library"), + ('build-purelib=', None, "build directory for platform-neutral distributions"), + ('build-platlib=', None, "build directory for platform-specific distributions"), + ( + 'build-lib=', + None, + "build directory for all distribution (defaults to either build-purelib or build-platlib", + ), + ('build-scripts=', None, "build directory for scripts"), + ('build-temp=', 't', "temporary build directory"), + ( + 'plat-name=', + 'p', + f"platform name to build for, if supported [default: {get_platform()}]", + ), + ('compiler=', 'c', "specify the compiler type"), + ('parallel=', 'j', "number of parallel build jobs"), + ('debug', 'g', "compile extensions and libraries with debugging information"), + ('force', 'f', "forcibly build everything (ignore file timestamps)"), + ('executable=', 'e', "specify final destination interpreter path (build.py)"), + ] + + boolean_options: ClassVar[list[str]] = ['debug', 'force'] + + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [ + ('help-compiler', None, "list available compilers", show_compilers), + ] + + def initialize_options(self): + self.build_base = 'build' + # these are decided only after 'build_base' has its final value + # (unless overridden by the user or client) + self.build_purelib = None + self.build_platlib = None + self.build_lib = None + self.build_temp = None + self.build_scripts = None + self.compiler = None + self.plat_name = None + self.debug = None + self.force = False + self.executable = None + self.parallel = None + + def finalize_options(self) -> None: # noqa: C901 + if self.plat_name is None: + self.plat_name = get_platform() + else: + # plat-name only supported for windows (other platforms are + # supported via ./configure flags, if at all). Avoid misleading + # other platforms. + if os.name != 'nt': + raise DistutilsOptionError( + "--plat-name only supported on Windows (try " + "using './configure --help' on your platform)" + ) + + plat_specifier = f".{self.plat_name}-{sys.implementation.cache_tag}" + + # Python 3.13+ with --disable-gil shouldn't share build directories + if sysconfig.get_config_var('Py_GIL_DISABLED'): + plat_specifier += 't' + + # Make it so Python 2.x and Python 2.x with --with-pydebug don't + # share the same build directories. Doing so confuses the build + # process for C modules + if hasattr(sys, 'gettotalrefcount'): + plat_specifier += '-pydebug' + + # 'build_purelib' and 'build_platlib' just default to 'lib' and + # 'lib.' under the base build directory. We only use one of + # them for a given distribution, though -- + if self.build_purelib is None: + self.build_purelib = os.path.join(self.build_base, 'lib') + if self.build_platlib is None: + self.build_platlib = os.path.join(self.build_base, 'lib' + plat_specifier) + + # 'build_lib' is the actual directory that we will use for this + # particular module distribution -- if user didn't supply it, pick + # one of 'build_purelib' or 'build_platlib'. + if self.build_lib is None: + if self.distribution.has_ext_modules(): + self.build_lib = self.build_platlib + else: + self.build_lib = self.build_purelib + + # 'build_temp' -- temporary directory for compiler turds, + # "build/temp." + if self.build_temp is None: + self.build_temp = os.path.join(self.build_base, 'temp' + plat_specifier) + if self.build_scripts is None: + self.build_scripts = os.path.join( + self.build_base, + f'scripts-{sys.version_info.major}.{sys.version_info.minor}', + ) + + if self.executable is None and sys.executable: + self.executable = os.path.normpath(sys.executable) + + if isinstance(self.parallel, str): + try: + self.parallel = int(self.parallel) + except ValueError: + raise DistutilsOptionError("parallel should be an integer") + + def run(self) -> None: + # Run all relevant sub-commands. This will be some subset of: + # - build_py - pure Python modules + # - build_clib - standalone C libraries + # - build_ext - Python extensions + # - build_scripts - (Python) scripts + for cmd_name in self.get_sub_commands(): + self.run_command(cmd_name) + + # -- Predicates for the sub-command list --------------------------- + + def has_pure_modules(self): + return self.distribution.has_pure_modules() + + def has_c_libraries(self): + return self.distribution.has_c_libraries() + + def has_ext_modules(self): + return self.distribution.has_ext_modules() + + def has_scripts(self): + return self.distribution.has_scripts() + + sub_commands = [ + ('build_py', has_pure_modules), + ('build_clib', has_c_libraries), + ('build_ext', has_ext_modules), + ('build_scripts', has_scripts), + ] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_clib.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_clib.py new file mode 100644 index 0000000000000000000000000000000000000000..8de5df239c793ac74265d5aac6b113c99b1934fd --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_clib.py @@ -0,0 +1,199 @@ +"""distutils.command.build_clib + +Implements the Distutils 'build_clib' command, to build a C/C++ library +that is included in the module distribution and needed by an extension +module.""" + +# XXX this module has *lots* of code ripped-off quite transparently from +# build_ext.py -- not surprisingly really, as the work required to build +# a static library from a collection of C source files is not really all +# that different from what's required to build a shared object file from +# a collection of C source files. Nevertheless, I haven't done the +# necessary refactoring to account for the overlap in code between the +# two modules, mainly because a number of subtle details changed in the +# cut 'n paste. Sigh. +from __future__ import annotations + +import os +from collections.abc import Callable +from distutils._log import log +from typing import ClassVar + +from ..ccompiler import new_compiler, show_compilers +from ..core import Command +from ..errors import DistutilsSetupError +from ..sysconfig import customize_compiler + + +class build_clib(Command): + description = "build C/C++ libraries used by Python extensions" + + user_options: ClassVar[list[tuple[str, str, str]]] = [ + ('build-clib=', 'b', "directory to build C/C++ libraries to"), + ('build-temp=', 't', "directory to put temporary build by-products"), + ('debug', 'g', "compile with debugging information"), + ('force', 'f', "forcibly build everything (ignore file timestamps)"), + ('compiler=', 'c', "specify the compiler type"), + ] + + boolean_options: ClassVar[list[str]] = ['debug', 'force'] + + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [ + ('help-compiler', None, "list available compilers", show_compilers), + ] + + def initialize_options(self): + self.build_clib = None + self.build_temp = None + + # List of libraries to build + self.libraries = None + + # Compilation options for all libraries + self.include_dirs = None + self.define = None + self.undef = None + self.debug = None + self.force = False + self.compiler = None + + def finalize_options(self) -> None: + # This might be confusing: both build-clib and build-temp default + # to build-temp as defined by the "build" command. This is because + # I think that C libraries are really just temporary build + # by-products, at least from the point of view of building Python + # extensions -- but I want to keep my options open. + self.set_undefined_options( + 'build', + ('build_temp', 'build_clib'), + ('build_temp', 'build_temp'), + ('compiler', 'compiler'), + ('debug', 'debug'), + ('force', 'force'), + ) + + self.libraries = self.distribution.libraries + if self.libraries: + self.check_library_list(self.libraries) + + if self.include_dirs is None: + self.include_dirs = self.distribution.include_dirs or [] + if isinstance(self.include_dirs, str): + self.include_dirs = self.include_dirs.split(os.pathsep) + + # XXX same as for build_ext -- what about 'self.define' and + # 'self.undef' ? + + def run(self) -> None: + if not self.libraries: + return + + self.compiler = new_compiler(compiler=self.compiler, force=self.force) + customize_compiler(self.compiler) + + if self.include_dirs is not None: + self.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: + self.compiler.define_macro(name, value) + if self.undef is not None: + for macro in self.undef: + self.compiler.undefine_macro(macro) + + self.build_libraries(self.libraries) + + def check_library_list(self, libraries) -> None: + """Ensure that the list of libraries is valid. + + `library` is presumably provided as a command option 'libraries'. + This method checks that it is a list of 2-tuples, where the tuples + are (library_name, build_info_dict). + + Raise DistutilsSetupError if the structure is invalid anywhere; + just returns otherwise. + """ + if not isinstance(libraries, list): + raise DistutilsSetupError("'libraries' option must be a list of tuples") + + for lib in libraries: + if not isinstance(lib, tuple) and len(lib) != 2: + raise DistutilsSetupError("each element of 'libraries' must a 2-tuple") + + name, build_info = lib + + if not isinstance(name, str): + raise DistutilsSetupError( + "first element of each tuple in 'libraries' " + "must be a string (the library name)" + ) + + if '/' in name or (os.sep != '/' and os.sep in name): + raise DistutilsSetupError( + f"bad library name '{lib[0]}': may not contain directory separators" + ) + + if not isinstance(build_info, dict): + raise DistutilsSetupError( + "second element of each tuple in 'libraries' " + "must be a dictionary (build info)" + ) + + def get_library_names(self): + # Assume the library list is valid -- 'check_library_list()' is + # called from 'finalize_options()', so it should be! + if not self.libraries: + return None + + lib_names = [] + for lib_name, _build_info in self.libraries: + lib_names.append(lib_name) + return lib_names + + def get_source_files(self): + self.check_library_list(self.libraries) + filenames = [] + for lib_name, build_info in self.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" + ) + + filenames.extend(sources) + return filenames + + 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 = list(sources) + + log.info("building '%s' library", lib_name) + + # 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') + objects = self.compiler.compile( + sources, + output_dir=self.build_temp, + macros=macros, + include_dirs=include_dirs, + 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( + objects, lib_name, output_dir=self.build_clib, debug=self.debug + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_ext.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..df623d7e0ef2f667bfce329283256513621eacf7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_ext.py @@ -0,0 +1,811 @@ +"""distutils.command.build_ext + +Implements the Distutils 'build_ext' command, for building extension +modules (currently limited to C extensions, should accommodate C++ +extensions ASAP).""" + +from __future__ import annotations + +import contextlib +import os +import re +import sys +from collections.abc import Callable +from distutils._log import log +from site import USER_BASE +from typing import ClassVar + +from .._modified import newer_group +from ..ccompiler import new_compiler, show_compilers +from ..core import Command +from ..errors import ( + CCompilerError, + CompileError, + DistutilsError, + DistutilsOptionError, + DistutilsPlatformError, + DistutilsSetupError, +) +from ..extension import Extension +from ..sysconfig import customize_compiler, get_config_h_filename, get_python_version +from ..util import get_platform, is_freethreaded, is_mingw + +# An extension name is just a dot-separated list of Python NAMEs (ie. +# the same as a fully-qualified module name). +extension_name_re = re.compile(r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$') + + +class build_ext(Command): + description = "build C/C++ extensions (compile/link to build directory)" + + # XXX thoughts on how to deal with complex command-line options like + # these, i.e. how to make it so fancy_getopt can suck them off the + # command line and make it look like setup.py defined the appropriate + # lists of tuples of what-have-you. + # - each command needs a callback to process its command-line options + # - Command.__init__() needs access to its share of the whole + # command line (must ultimately come from + # Distribution.parse_command_line()) + # - it then calls the current command class' option-parsing + # callback to deal with weird options like -D, which have to + # parse the option text and churn out some custom data + # structure + # - that data structure (in this case, a list of 2-tuples) + # will then be present in the command object by the time + # we get to finalize_options() (i.e. the constructor + # takes care of both command-line and client options + # in between initialize_options() and finalize_options()) + + sep_by = f" (separated by '{os.pathsep}')" + user_options = [ + ('build-lib=', 'b', "directory for compiled extension modules"), + ('build-temp=', 't', "directory for temporary files (build by-products)"), + ( + 'plat-name=', + 'p', + "platform name to cross-compile for, if supported " + f"[default: {get_platform()}]", + ), + ( + 'inplace', + 'i', + "ignore build-lib and put compiled extensions into the source " + "directory alongside your pure Python modules", + ), + ( + 'include-dirs=', + 'I', + "list of directories to search for header files" + sep_by, + ), + ('define=', 'D', "C preprocessor macros to define"), + ('undef=', 'U', "C preprocessor macros to undefine"), + ('libraries=', 'l', "external C libraries to link with"), + ( + 'library-dirs=', + 'L', + "directories to search for external C libraries" + sep_by, + ), + ('rpath=', 'R', "directories to search for shared C libraries at runtime"), + ('link-objects=', 'O', "extra explicit link objects to include in the link"), + ('debug', 'g', "compile/link with debugging information"), + ('force', 'f', "forcibly build everything (ignore file timestamps)"), + ('compiler=', 'c', "specify the compiler type"), + ('parallel=', 'j', "number of parallel build jobs"), + ('swig-cpp', None, "make SWIG create C++ files (default is C)"), + ('swig-opts=', None, "list of SWIG command line options"), + ('swig=', None, "path to the SWIG executable"), + ('user', None, "add user include, library and rpath"), + ] + + boolean_options: ClassVar[list[str]] = [ + 'inplace', + 'debug', + 'force', + 'swig-cpp', + 'user', + ] + + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [ + ('help-compiler', None, "list available compilers", show_compilers), + ] + + def initialize_options(self): + self.extensions = None + self.build_lib = None + self.plat_name = None + self.build_temp = None + self.inplace = False + self.package = None + + self.include_dirs = None + self.define = None + self.undef = None + self.libraries = None + self.library_dirs = None + self.rpath = None + self.link_objects = None + self.debug = None + self.force = None + self.compiler = None + self.swig = None + self.swig_cpp = None + self.swig_opts = None + self.user = None + self.parallel = None + + @staticmethod + def _python_lib_dir(sysconfig): + """ + Resolve Python's library directory for building extensions + that rely on a shared Python library. + + See python/cpython#44264 and python/cpython#48686 + """ + if not sysconfig.get_config_var('Py_ENABLE_SHARED'): + return + + if sysconfig.python_build: + yield '.' + return + + if sys.platform == 'zos': + # On z/OS, a user is not required to install Python to + # a predetermined path, but can use Python portably + installed_dir = sysconfig.get_config_var('base') + lib_dir = sysconfig.get_config_var('platlibdir') + yield os.path.join(installed_dir, lib_dir) + else: + # building third party extensions + yield sysconfig.get_config_var('LIBDIR') + + def finalize_options(self) -> None: # noqa: C901 + from distutils import sysconfig + + self.set_undefined_options( + 'build', + ('build_lib', 'build_lib'), + ('build_temp', 'build_temp'), + ('compiler', 'compiler'), + ('debug', 'debug'), + ('force', 'force'), + ('parallel', 'parallel'), + ('plat_name', 'plat_name'), + ) + + if self.package is None: + self.package = self.distribution.ext_package + + self.extensions = self.distribution.ext_modules + + # Make sure Python's include directories (for Python.h, pyconfig.h, + # etc.) are in the include search path. + py_include = sysconfig.get_python_inc() + plat_py_include = sysconfig.get_python_inc(plat_specific=True) + if self.include_dirs is None: + self.include_dirs = self.distribution.include_dirs or [] + if isinstance(self.include_dirs, str): + self.include_dirs = self.include_dirs.split(os.pathsep) + + # If in a virtualenv, add its include directory + # Issue 16116 + if sys.exec_prefix != sys.base_exec_prefix: + self.include_dirs.append(os.path.join(sys.exec_prefix, 'include')) + + # Put the Python "system" include dir at the end, so that + # any local include dirs take precedence. + self.include_dirs.extend(py_include.split(os.path.pathsep)) + if plat_py_include != py_include: + self.include_dirs.extend(plat_py_include.split(os.path.pathsep)) + + self.ensure_string_list('libraries') + self.ensure_string_list('link_objects') + + # Life is easier if we're not forever checking for None, so + # simplify these options to empty lists if unset + if self.libraries is None: + self.libraries = [] + if self.library_dirs is None: + self.library_dirs = [] + elif isinstance(self.library_dirs, str): + self.library_dirs = self.library_dirs.split(os.pathsep) + + if self.rpath is None: + self.rpath = [] + elif isinstance(self.rpath, str): + self.rpath = self.rpath.split(os.pathsep) + + # for extensions under windows use different directories + # for Release and Debug builds. + # also Python's library directory must be appended to library_dirs + if os.name == 'nt' and not is_mingw(): + # the 'libs' directory is for binary installs - we assume that + # must be the *native* platform. But we don't really support + # cross-compiling via a binary install anyway, so we let it go. + self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs')) + if sys.base_exec_prefix != sys.prefix: # Issue 16116 + self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs')) + if self.debug: + self.build_temp = os.path.join(self.build_temp, "Debug") + else: + self.build_temp = os.path.join(self.build_temp, "Release") + + # Append the source distribution include and library directories, + # this allows distutils on windows to work in the source tree + self.include_dirs.append(os.path.dirname(get_config_h_filename())) + self.library_dirs.append(sys.base_exec_prefix) + + # Use the .lib files for the correct architecture + if self.plat_name == 'win32': + suffix = 'win32' + else: + # win-amd64 + suffix = self.plat_name[4:] + new_lib = os.path.join(sys.exec_prefix, 'PCbuild') + if suffix: + new_lib = os.path.join(new_lib, suffix) + self.library_dirs.append(new_lib) + + # For extensions under Cygwin, Python's library directory must be + # appended to library_dirs + if sys.platform[:6] == 'cygwin': + if not sysconfig.python_build: + # building third party extensions + self.library_dirs.append( + os.path.join( + sys.prefix, "lib", "python" + get_python_version(), "config" + ) + ) + else: + # building python standard extensions + self.library_dirs.append('.') + + self.library_dirs.extend(self._python_lib_dir(sysconfig)) + + # The argument parsing will result in self.define being a string, but + # it has to be a list of 2-tuples. All the preprocessor symbols + # specified by the 'define' option will be set to '1'. Multiple + # symbols can be separated with commas. + + if self.define: + defines = self.define.split(',') + self.define = [(symbol, '1') for symbol in defines] + + # The option for macros to undefine is also a string from the + # option parsing, but has to be a list. Multiple symbols can also + # be separated with commas here. + if self.undef: + self.undef = self.undef.split(',') + + if self.swig_opts is None: + self.swig_opts = [] + else: + self.swig_opts = self.swig_opts.split(' ') + + # Finally add the user include and library directories if requested + if self.user: + user_include = os.path.join(USER_BASE, "include") + user_lib = os.path.join(USER_BASE, "lib") + if os.path.isdir(user_include): + self.include_dirs.append(user_include) + if os.path.isdir(user_lib): + self.library_dirs.append(user_lib) + self.rpath.append(user_lib) + + if isinstance(self.parallel, str): + try: + self.parallel = int(self.parallel) + except ValueError: + raise DistutilsOptionError("parallel should be an integer") + + def run(self) -> None: # noqa: C901 + # 'self.extensions', as supplied by setup.py, is a list of + # Extension instances. See the documentation for Extension (in + # distutils.extension) for details. + # + # For backwards compatibility with Distutils 0.8.2 and earlier, we + # also allow the 'extensions' list to be a list of tuples: + # (ext_name, build_info) + # where build_info is a dictionary containing everything that + # Extension instances do except the name, with a few things being + # differently named. We convert these 2-tuples to Extension + # instances as needed. + + if not self.extensions: + return + + # If we were asked to build any C/C++ libraries, make sure that the + # directory where we put them is in the library search path for + # linking extensions. + if self.distribution.has_c_libraries(): + build_clib = self.get_finalized_command('build_clib') + self.libraries.extend(build_clib.get_library_names() or []) + self.library_dirs.append(build_clib.build_clib) + + # Setup the CCompiler object that we'll use to do all the + # compiling and linking + self.compiler = new_compiler( + compiler=self.compiler, + verbose=self.verbose, + force=self.force, + ) + customize_compiler(self.compiler) + # If we are cross-compiling, init the compiler now (if we are not + # cross-compiling, init would not hurt, but people may rely on + # late initialization of compiler even if they shouldn't...) + if os.name == 'nt' and self.plat_name != get_platform(): + self.compiler.initialize(self.plat_name) + + # The official Windows free threaded Python installer doesn't set + # Py_GIL_DISABLED because its pyconfig.h is shared with the + # default build, so define it here (pypa/setuptools#4662). + if os.name == 'nt' and is_freethreaded(): + self.compiler.define_macro('Py_GIL_DISABLED', '1') + + # And make sure that any compile/link-related options (which might + # come from the command-line or from the setup script) are set in + # that CCompiler object -- that way, they automatically apply to + # all compiling and linking done here. + if self.include_dirs is not None: + self.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: + self.compiler.define_macro(name, value) + if self.undef is not None: + for macro in self.undef: + self.compiler.undefine_macro(macro) + if self.libraries is not None: + self.compiler.set_libraries(self.libraries) + if self.library_dirs is not None: + self.compiler.set_library_dirs(self.library_dirs) + if self.rpath is not None: + self.compiler.set_runtime_library_dirs(self.rpath) + if self.link_objects is not None: + self.compiler.set_link_objects(self.link_objects) + + # Now actually compile and link everything. + self.build_extensions() + + def check_extensions_list(self, extensions) -> None: # noqa: C901 + """Ensure that the list of extensions (presumably provided as a + command option 'extensions') is valid, i.e. it is a list of + Extension objects. We also support the old-style list of 2-tuples, + where the tuples are (ext_name, build_info), which are converted to + Extension instances here. + + Raise DistutilsSetupError if the structure is invalid anywhere; + just returns otherwise. + """ + if not isinstance(extensions, list): + raise DistutilsSetupError( + "'ext_modules' option must be a list of Extension instances" + ) + + for i, ext in enumerate(extensions): + if isinstance(ext, Extension): + continue # OK! (assume type-checking done + # by Extension constructor) + + if not isinstance(ext, tuple) or len(ext) != 2: + raise DistutilsSetupError( + "each element of 'ext_modules' option must be an " + "Extension instance or 2-tuple" + ) + + ext_name, build_info = ext + + log.warning( + "old-style (ext_name, build_info) tuple found in " + "ext_modules for extension '%s' " + "-- please convert to Extension instance", + ext_name, + ) + + if not (isinstance(ext_name, str) and extension_name_re.match(ext_name)): + raise DistutilsSetupError( + "first element of each tuple in 'ext_modules' " + "must be the extension name (a string)" + ) + + if not isinstance(build_info, dict): + raise DistutilsSetupError( + "second element of each tuple in 'ext_modules' " + "must be a dictionary (build info)" + ) + + # OK, the (ext_name, build_info) dict is type-safe: convert it + # to an Extension instance. + ext = Extension(ext_name, build_info['sources']) + + # Easy stuff: one-to-one mapping from dict elements to + # instance attributes. + for key in ( + 'include_dirs', + 'library_dirs', + 'libraries', + 'extra_objects', + 'extra_compile_args', + 'extra_link_args', + ): + val = build_info.get(key) + if val is not None: + setattr(ext, key, val) + + # Medium-easy stuff: same syntax/semantics, different names. + ext.runtime_library_dirs = build_info.get('rpath') + if 'def_file' in build_info: + log.warning("'def_file' element of build info dict no longer supported") + + # Non-trivial stuff: 'macros' split into 'define_macros' + # and 'undef_macros'. + macros = build_info.get('macros') + if macros: + ext.define_macros = [] + ext.undef_macros = [] + for macro in macros: + if not (isinstance(macro, tuple) and len(macro) in (1, 2)): + raise DistutilsSetupError( + "'macros' element of build info dict must be 1- or 2-tuple" + ) + if len(macro) == 1: + ext.undef_macros.append(macro[0]) + elif len(macro) == 2: + ext.define_macros.append(macro) + + extensions[i] = ext + + def get_source_files(self): + self.check_extensions_list(self.extensions) + filenames = [] + + # Wouldn't it be neat if we knew the names of header files too... + for ext in self.extensions: + filenames.extend(ext.sources) + return filenames + + def get_outputs(self): + # Sanity check the 'extensions' list -- can't assume this is being + # done in the same run as a 'build_extensions()' call (in fact, we + # can probably assume that it *isn't*!). + self.check_extensions_list(self.extensions) + + # And build the list of output (built) filenames. Note that this + # ignores the 'inplace' flag, and assumes everything goes in the + # "build" tree. + return [self.get_ext_fullpath(ext.name) for ext in self.extensions] + + def build_extensions(self) -> None: + # First, sanity-check the 'extensions' list + self.check_extensions_list(self.extensions) + if self.parallel: + self._build_extensions_parallel() + else: + self._build_extensions_serial() + + def _build_extensions_parallel(self): + workers = self.parallel + if self.parallel is True: + workers = os.cpu_count() # may return None + try: + from concurrent.futures import ThreadPoolExecutor + except ImportError: + workers = None + + if workers is None: + self._build_extensions_serial() + return + + with ThreadPoolExecutor(max_workers=workers) as executor: + futures = [ + executor.submit(self.build_extension, ext) for ext in self.extensions + ] + for ext, fut in zip(self.extensions, futures): + with self._filter_build_errors(ext): + fut.result() + + def _build_extensions_serial(self): + for ext in self.extensions: + with self._filter_build_errors(ext): + self.build_extension(ext) + + @contextlib.contextmanager + def _filter_build_errors(self, ext): + try: + yield + except (CCompilerError, DistutilsError, CompileError) as e: + if not ext.optional: + raise + self.warn(f'building extension "{ext.name}" failed: {e}') + + def build_extension(self, ext) -> None: + sources = ext.sources + if sources is None or not isinstance(sources, (list, tuple)): + raise DistutilsSetupError( + f"in 'ext_modules' option (extension '{ext.name}'), " + "'sources' must be present and must be " + "a list of source filenames" + ) + # sort to make the resulting .so file build reproducible + sources = sorted(sources) + + ext_path = self.get_ext_fullpath(ext.name) + depends = sources + ext.depends + if not (self.force or newer_group(depends, ext_path, 'newer')): + log.debug("skipping '%s' extension (up-to-date)", ext.name) + return + else: + log.info("building '%s' extension", ext.name) + + # First, scan the sources for SWIG definition files (.i), run + # SWIG on 'em to create .c files, and modify the sources list + # accordingly. + sources = self.swig_sources(sources, ext) + + # Next, compile the source code to object files. + + # XXX not honouring 'define_macros' or 'undef_macros' -- the + # CCompiler API needs to change to accommodate this, and I + # want to do one thing at a time! + + # Two possible sources for extra compiler arguments: + # - 'extra_compile_args' in Extension object + # - CFLAGS environment variable (not particularly + # elegant, but people seem to expect it and I + # guess it's useful) + # The environment variable should take precedence, and + # any sensible compiler will give precedence to later + # command line args. Hence we combine them in order: + extra_args = ext.extra_compile_args or [] + + macros = ext.define_macros[:] + for undef in ext.undef_macros: + macros.append((undef,)) + + objects = self.compiler.compile( + sources, + output_dir=self.build_temp, + macros=macros, + include_dirs=ext.include_dirs, + debug=self.debug, + extra_postargs=extra_args, + depends=ext.depends, + ) + + # XXX outdated variable, kept here in case third-part code + # needs it. + self._built_objects = objects[:] + + # Now link the object files together into a "shared object" -- + # of course, first we have to figure out all the other things + # that go into the mix. + if ext.extra_objects: + objects.extend(ext.extra_objects) + extra_args = ext.extra_link_args or [] + + # Detect target language, if not provided + language = ext.language or self.compiler.detect_language(sources) + + self.compiler.link_shared_object( + objects, + ext_path, + libraries=self.get_libraries(ext), + library_dirs=ext.library_dirs, + runtime_library_dirs=ext.runtime_library_dirs, + extra_postargs=extra_args, + export_symbols=self.get_export_symbols(ext), + debug=self.debug, + build_temp=self.build_temp, + target_lang=language, + ) + + def swig_sources(self, sources, extension): + """Walk the list of source files in 'sources', looking for SWIG + interface (.i) files. Run SWIG on all that are found, and + return a modified 'sources' list with SWIG source files replaced + by the generated C (or C++) files. + """ + new_sources = [] + swig_sources = [] + swig_targets = {} + + # XXX this drops generated C/C++ files into the source tree, which + # is fine for developers who want to distribute the generated + # source -- but there should be an option to put SWIG output in + # the temp dir. + + if self.swig_cpp: + log.warning("--swig-cpp is deprecated - use --swig-opts=-c++") + + if ( + self.swig_cpp + or ('-c++' in self.swig_opts) + or ('-c++' in extension.swig_opts) + ): + target_ext = '.cpp' + else: + target_ext = '.c' + + for source in sources: + (base, ext) = os.path.splitext(source) + if ext == ".i": # SWIG interface file + new_sources.append(base + '_wrap' + target_ext) + swig_sources.append(source) + swig_targets[source] = new_sources[-1] + else: + new_sources.append(source) + + if not swig_sources: + return new_sources + + swig = self.swig or self.find_swig() + swig_cmd = [swig, "-python"] + swig_cmd.extend(self.swig_opts) + if self.swig_cpp: + swig_cmd.append("-c++") + + # Do not override commandline arguments + if not self.swig_opts: + swig_cmd.extend(extension.swig_opts) + + for source in swig_sources: + target = swig_targets[source] + log.info("swigging %s to %s", source, target) + self.spawn(swig_cmd + ["-o", target, source]) + + return new_sources + + def find_swig(self): + """Return the name of the SWIG executable. On Unix, this is + just "swig" -- it should be in the PATH. Tries a bit harder on + Windows. + """ + if os.name == "posix": + return "swig" + elif os.name == "nt": + # Look for SWIG in its standard installation directory on + # Windows (or so I presume!). If we find it there, great; + # if not, act like Unix and assume it's in the PATH. + for vers in ("1.3", "1.2", "1.1"): + fn = os.path.join(f"c:\\swig{vers}", "swig.exe") + if os.path.isfile(fn): + return fn + else: + return "swig.exe" + else: + raise DistutilsPlatformError( + f"I don't know how to find (much less run) SWIG on platform '{os.name}'" + ) + + # -- Name generators ----------------------------------------------- + # (extension names, filenames, whatever) + def get_ext_fullpath(self, ext_name: str) -> str: + """Returns the path of the filename for a given extension. + + The file is located in `build_lib` or directly in the package + (inplace option). + """ + fullname = self.get_ext_fullname(ext_name) + modpath = fullname.split('.') + filename = self.get_ext_filename(modpath[-1]) + + if not self.inplace: + # no further work needed + # returning : + # build_dir/package/path/filename + filename = os.path.join(*modpath[:-1] + [filename]) + return os.path.join(self.build_lib, filename) + + # the inplace option requires to find the package directory + # using the build_py command for that + package = '.'.join(modpath[0:-1]) + build_py = self.get_finalized_command('build_py') + package_dir = os.path.abspath(build_py.get_package_dir(package)) + + # returning + # package_dir/filename + return os.path.join(package_dir, filename) + + def get_ext_fullname(self, ext_name: str) -> str: + """Returns the fullname of a given extension name. + + Adds the `package.` prefix""" + if self.package is None: + return ext_name + else: + return self.package + '.' + ext_name + + def get_ext_filename(self, ext_name: str) -> str: + r"""Convert the name of an extension (eg. "foo.bar") into the name + of the file from which it will be loaded (eg. "foo/bar.so", or + "foo\bar.pyd"). + """ + from ..sysconfig import get_config_var + + ext_path = ext_name.split('.') + ext_suffix = get_config_var('EXT_SUFFIX') + return os.path.join(*ext_path) + ext_suffix + + def get_export_symbols(self, ext: Extension) -> list[str]: + """Return the list of symbols that a shared extension has to + export. This either uses 'ext.export_symbols' or, if it's not + provided, "PyInit_" + module_name. Only relevant on Windows, where + the .pyd file (DLL) must export the module "PyInit_" function. + """ + name = self._get_module_name_for_symbol(ext) + try: + # Unicode module name support as defined in PEP-489 + # https://peps.python.org/pep-0489/#export-hook-name + name.encode('ascii') + except UnicodeEncodeError: + suffix = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii') + else: + suffix = "_" + name + + initfunc_name = "PyInit" + suffix + if initfunc_name not in ext.export_symbols: + ext.export_symbols.append(initfunc_name) + return ext.export_symbols + + def _get_module_name_for_symbol(self, ext): + # Package name should be used for `__init__` modules + # https://github.com/python/cpython/issues/80074 + # https://github.com/pypa/setuptools/issues/4826 + parts = ext.name.split(".") + if parts[-1] == "__init__" and len(parts) >= 2: + return parts[-2] + return parts[-1] + + def get_libraries(self, ext: Extension) -> list[str]: # noqa: C901 + """Return the list of libraries to link against when building a + shared extension. On most platforms, this is just 'ext.libraries'; + on Windows, we add the Python library (eg. python20.dll). + """ + # The python library is always needed on Windows. For MSVC, this + # is redundant, since the library is mentioned in a pragma in + # pyconfig.h that MSVC groks. The other Windows compilers all seem + # to need it mentioned explicitly, though, so that's what we do. + # Append '_d' to the python import library on debug builds. + if sys.platform == "win32" and not is_mingw(): + from .._msvccompiler import MSVCCompiler + + if not isinstance(self.compiler, MSVCCompiler): + template = "python%d%d" + if self.debug: + template = template + '_d' + pythonlib = template % ( + sys.hexversion >> 24, + (sys.hexversion >> 16) & 0xFF, + ) + # don't extend ext.libraries, it may be shared with other + # extensions, it is a reference to the original list + return ext.libraries + [pythonlib] + else: + # On Android only the main executable and LD_PRELOADs are considered + # to be RTLD_GLOBAL, all the dependencies of the main executable + # remain RTLD_LOCAL and so the shared libraries must be linked with + # libpython when python is built with a shared python library (issue + # bpo-21536). + # On Cygwin (and if required, other POSIX-like platforms based on + # Windows like MinGW) it is simply necessary that all symbols in + # shared libraries are resolved at link time. + from ..sysconfig import get_config_var + + link_libpython = False + if get_config_var('Py_ENABLE_SHARED'): + # A native build on an Android device or on Cygwin + if hasattr(sys, 'getandroidapilevel'): + link_libpython = True + elif sys.platform == 'cygwin' or is_mingw(): + link_libpython = True + elif '_PYTHON_HOST_PLATFORM' in os.environ: + # We are cross-compiling for one of the relevant platforms + if get_config_var('ANDROID_API_LEVEL') != 0: + link_libpython = True + elif get_config_var('MACHDEP') == 'cygwin': + link_libpython = True + + if link_libpython: + ldversion = get_config_var('LDVERSION') + return ext.libraries + ['python' + ldversion] + + return ext.libraries diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_py.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_py.py new file mode 100644 index 0000000000000000000000000000000000000000..d6ec7d10d2a807e02f1856fcacf488057ec69081 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_py.py @@ -0,0 +1,404 @@ +"""distutils.command.build_py + +Implements the Distutils 'build_py' command.""" + +import glob +import importlib.util +import os +import sys +from distutils._log import log +from typing import ClassVar + +from ..core import Command +from ..errors import DistutilsFileError, DistutilsOptionError +from ..util import convert_path + + +class build_py(Command): + description = "\"build\" pure Python modules (copy to build directory)" + + user_options = [ + ('build-lib=', 'd', "directory to \"build\" (copy) to"), + ('compile', 'c', "compile .py to .pyc"), + ('no-compile', None, "don't compile .py files [default]"), + ( + 'optimize=', + 'O', + "also compile with optimization: -O1 for \"python -O\", " + "-O2 for \"python -OO\", and -O0 to disable [default: -O0]", + ), + ('force', 'f', "forcibly build everything (ignore file timestamps)"), + ] + + boolean_options: ClassVar[list[str]] = ['compile', 'force'] + negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'} + + def initialize_options(self): + self.build_lib = None + self.py_modules = None + self.package = None + self.package_data = None + self.package_dir = None + self.compile = False + self.optimize = 0 + self.force = None + + def finalize_options(self) -> None: + self.set_undefined_options( + 'build', ('build_lib', 'build_lib'), ('force', 'force') + ) + + # Get the distribution options that are aliases for build_py + # options -- list of packages and list of modules. + self.packages = self.distribution.packages + self.py_modules = self.distribution.py_modules + self.package_data = self.distribution.package_data + self.package_dir = {} + if self.distribution.package_dir: + for name, path in self.distribution.package_dir.items(): + self.package_dir[name] = convert_path(path) + self.data_files = self.get_data_files() + + # Ick, copied straight from install_lib.py (fancy_getopt needs a + # type system! Hell, *everything* needs a type system!!!) + if not isinstance(self.optimize, int): + try: + self.optimize = int(self.optimize) + assert 0 <= self.optimize <= 2 + except (ValueError, AssertionError): + raise DistutilsOptionError("optimize must be 0, 1, or 2") + + def run(self) -> None: + # XXX copy_file by default preserves atime and mtime. IMHO this is + # the right thing to do, but perhaps it should be an option -- in + # particular, a site administrator might want installed files to + # reflect the time of installation rather than the last + # modification time before the installed release. + + # XXX copy_file by default preserves mode, which appears to be the + # wrong thing to do: if a file is read-only in the working + # directory, we want it to be installed read/write so that the next + # installation of the same module distribution can overwrite it + # without problems. (This might be a Unix-specific issue.) Thus + # we turn off 'preserve_mode' when copying to the build directory, + # since the build directory is supposed to be exactly what the + # installation will look like (ie. we preserve mode when + # installing). + + # Two options control which modules will be installed: 'packages' + # and 'py_modules'. The former lets us work with whole packages, not + # specifying individual modules at all; the latter is for + # specifying modules one-at-a-time. + + if self.py_modules: + self.build_modules() + if self.packages: + self.build_packages() + self.build_package_data() + + self.byte_compile(self.get_outputs(include_bytecode=False)) + + def get_data_files(self): + """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" + data = [] + if not self.packages: + return data + for package in self.packages: + # 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('.'))) + + # Length of path to strip from found files + plen = 0 + if src_dir: + plen = len(src_dir) + 1 + + # Strip directory from globbed filenames + filenames = [file[plen:] for file in self.find_data_files(package, src_dir)] + data.append((package, src_dir, build_dir, filenames)) + return data + + def find_data_files(self, package, src_dir): + """Return filenames for package's data files in 'src_dir'""" + globs = self.package_data.get('', []) + self.package_data.get(package, []) + files = [] + for pattern in globs: + # Each pattern has to be converted to a platform-specific path + filelist = glob.glob( + os.path.join(glob.escape(src_dir), convert_path(pattern)) + ) + # Files that match more than one pattern are only added once + files.extend([ + fn for fn in filelist if fn not in files and os.path.isfile(fn) + ]) + return files + + def build_package_data(self) -> None: + """Copy data files into build directory""" + for _package, src_dir, build_dir, filenames in self.data_files: + for filename in filenames: + target = os.path.join(build_dir, filename) + self.mkpath(os.path.dirname(target)) + self.copy_file( + os.path.join(src_dir, filename), target, preserve_mode=False + ) + + def get_package_dir(self, package): + """Return the directory, relative to the top of the source + distribution, where package 'package' should be found + (at least according to the 'package_dir' option, if any).""" + path = package.split('.') + + if not self.package_dir: + if path: + return os.path.join(*path) + else: + return '' + else: + tail = [] + while path: + try: + pdir = self.package_dir['.'.join(path)] + except KeyError: + tail.insert(0, path[-1]) + del path[-1] + else: + tail.insert(0, pdir) + return os.path.join(*tail) + else: + # Oops, got all the way through 'path' without finding a + # match in package_dir. If package_dir defines a directory + # for the root (nameless) package, then fallback on it; + # otherwise, we might as well have not consulted + # package_dir at all, as we just use the directory implied + # by 'tail' (which should be the same as the original value + # of 'path' at this point). + pdir = self.package_dir.get('') + if pdir is not None: + tail.insert(0, pdir) + + if tail: + return os.path.join(*tail) + else: + return '' + + def check_package(self, package, package_dir): + # Empty dir name means current directory, which we can probably + # assume exists. Also, os.path.exists and isdir don't know about + # my "empty string means current dir" convention, so we have to + # circumvent them. + if package_dir != "": + if not os.path.exists(package_dir): + raise DistutilsFileError( + f"package directory '{package_dir}' does not exist" + ) + if not os.path.isdir(package_dir): + raise DistutilsFileError( + f"supposed package directory '{package_dir}' exists, " + "but is not a directory" + ) + + # Directories without __init__.py are namespace packages (PEP 420). + if package: + init_py = os.path.join(package_dir, "__init__.py") + if os.path.isfile(init_py): + return init_py + + # Either not in a package at all (__init__.py not expected), or + # __init__.py doesn't exist -- so don't return the filename. + return None + + def check_module(self, module, module_file): + if not os.path.isfile(module_file): + log.warning("file %s (for module %s) not found", module_file, module) + return False + else: + return True + + def find_package_modules(self, package, package_dir): + self.check_package(package, package_dir) + module_files = glob.glob(os.path.join(glob.escape(package_dir), "*.py")) + modules = [] + setup_script = os.path.abspath(self.distribution.script_name) + + for f in module_files: + abs_f = os.path.abspath(f) + if abs_f != setup_script: + module = os.path.splitext(os.path.basename(f))[0] + modules.append((package, module, f)) + else: + self.debug_print(f"excluding {setup_script}") + return modules + + def find_modules(self): + """Finds individually-specified Python modules, ie. those listed by + module name in 'self.py_modules'. Returns a list of tuples (package, + module_base, filename): 'package' is a tuple of the path through + package-space to the module; 'module_base' is the bare (no + packages, no dots) module name, and 'filename' is the path to the + ".py" file (relative to the distribution root) that implements the + module. + """ + # Map package names to tuples of useful info about the package: + # (package_dir, checked) + # package_dir - the directory where we'll find source files for + # this package + # checked - true if we have checked that the package directory + # is valid (exists, contains __init__.py, ... ?) + packages = {} + + # List of (package, module, filename) tuples to return + modules = [] + + # We treat modules-in-packages almost the same as toplevel modules, + # just the "package" for a toplevel is empty (either an empty + # string or empty list, depending on context). Differences: + # - don't check for __init__.py in directory for empty package + for module in self.py_modules: + path = module.split('.') + package = '.'.join(path[0:-1]) + module_base = path[-1] + + try: + (package_dir, checked) = packages[package] + except KeyError: + package_dir = self.get_package_dir(package) + checked = False + + if not checked: + init_py = self.check_package(package, package_dir) + packages[package] = (package_dir, 1) + if init_py: + modules.append((package, "__init__", init_py)) + + # XXX perhaps we should also check for just .pyc files + # (so greedy closed-source bastards can distribute Python + # modules too) + module_file = os.path.join(package_dir, module_base + ".py") + if not self.check_module(module, module_file): + continue + + modules.append((package, module_base, module_file)) + + return modules + + def find_all_modules(self): + """Compute the list of all modules that will be built, whether + they are specified one-module-at-a-time ('self.py_modules') or + by whole packages ('self.packages'). Return a list of tuples + (package, module, module_file), just like 'find_modules()' and + 'find_package_modules()' do.""" + modules = [] + if self.py_modules: + modules.extend(self.find_modules()) + if self.packages: + for package in self.packages: + package_dir = self.get_package_dir(package) + m = self.find_package_modules(package, package_dir) + modules.extend(m) + return modules + + def get_source_files(self): + return [module[-1] for module in self.find_all_modules()] + + def get_module_outfile(self, build_dir, package, module): + outfile_path = [build_dir] + list(package) + [module + ".py"] + return os.path.join(*outfile_path) + + def get_outputs(self, include_bytecode: bool = True) -> list[str]: + modules = self.find_all_modules() + outputs = [] + for package, module, _module_file in modules: + package = package.split('.') + filename = self.get_module_outfile(self.build_lib, package, module) + outputs.append(filename) + if include_bytecode: + if self.compile: + outputs.append( + importlib.util.cache_from_source(filename, optimization='') + ) + if self.optimize > 0: + outputs.append( + importlib.util.cache_from_source( + filename, optimization=self.optimize + ) + ) + + outputs += [ + os.path.join(build_dir, filename) + for package, src_dir, build_dir, filenames in self.data_files + for filename in filenames + ] + + return outputs + + def build_module(self, module, module_file, package): + if isinstance(package, str): + package = package.split('.') + elif not isinstance(package, (list, tuple)): + raise TypeError( + "'package' must be a string (dot-separated), list, or tuple" + ) + + # Now put the module source file into the "build" area -- this is + # easy, we just copy it somewhere under self.build_lib (the build + # directory for Python source). + outfile = self.get_module_outfile(self.build_lib, package, module) + dir = os.path.dirname(outfile) + self.mkpath(dir) + return self.copy_file(module_file, outfile, preserve_mode=False) + + def build_modules(self) -> None: + modules = self.find_modules() + for package, module, module_file in modules: + # Now "build" the module -- ie. copy the source file to + # self.build_lib (the build directory for Python source). + # (Actually, it gets copied to the directory for this package + # under self.build_lib.) + self.build_module(module, module_file, package) + + def build_packages(self) -> None: + for package in self.packages: + # Get list of (package, module, module_file) tuples based on + # scanning the package directory. 'package' is only included + # in the tuple so that 'find_modules()' and + # 'find_package_tuples()' have a consistent interface; it's + # ignored here (apart from a sanity check). Also, 'module' is + # the *unqualified* module name (ie. no dots, no package -- we + # already know its package!), and 'module_file' is the path to + # the .py file, relative to the current directory + # (ie. including 'package_dir'). + package_dir = self.get_package_dir(package) + modules = self.find_package_modules(package, package_dir) + + # Now loop over the modules we found, "building" each one (just + # copy it to self.build_lib). + for package_, module, module_file in modules: + assert package == package_ + self.build_module(module, module_file, package) + + def byte_compile(self, files) -> None: + if sys.dont_write_bytecode: + self.warn('byte-compiling is disabled, skipping.') + return + + from ..util import byte_compile + + prefix = self.build_lib + if prefix[-1] != os.sep: + prefix = prefix + os.sep + + # XXX this code is essentially the same as the 'byte_compile() + # method of the "install_lib" command, except for the determination + # of the 'prefix' string. Hmmm. + if self.compile: + byte_compile(files, optimize=0, force=self.force, prefix=prefix) + if self.optimize > 0: + byte_compile( + files, + optimize=self.optimize, + force=self.force, + prefix=prefix, + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_scripts.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..0b551d11be0200b4e9c620d1af387ff7c2752096 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/build_scripts.py @@ -0,0 +1,150 @@ +"""distutils.command.build_scripts + +Implements the Distutils 'build_scripts' command.""" + +import os +import re +import tokenize +from distutils._log import log +from stat import ST_MODE +from typing import ClassVar + +from .._modified import newer +from ..core import Command +from ..util import convert_path + +shebang_pattern = re.compile('^#!.*python[0-9.]*([ \t].*)?$') +""" +Pattern matching a Python interpreter indicated in first line of a script. +""" + +# for Setuptools compatibility +first_line_re = shebang_pattern + + +class build_scripts(Command): + description = "\"build\" scripts (copy and fixup #! line)" + + user_options: ClassVar[list[tuple[str, str, str]]] = [ + ('build-dir=', 'd', "directory to \"build\" (copy) to"), + ('force', 'f', "forcibly build everything (ignore file timestamps"), + ('executable=', 'e', "specify final destination interpreter path"), + ] + + boolean_options: ClassVar[list[str]] = ['force'] + + def initialize_options(self): + self.build_dir = None + self.scripts = None + self.force = None + self.executable = None + + def finalize_options(self): + self.set_undefined_options( + 'build', + ('build_scripts', 'build_dir'), + ('force', 'force'), + ('executable', 'executable'), + ) + self.scripts = self.distribution.scripts + + def get_source_files(self): + return self.scripts + + def run(self): + if not self.scripts: + return + self.copy_scripts() + + def copy_scripts(self): + """ + Copy each script listed in ``self.scripts``. + + If a script is marked as a Python script (first line matches + 'shebang_pattern', i.e. starts with ``#!`` and contains + "python"), then adjust in the copy the first line to refer to + the current Python interpreter. + """ + self.mkpath(self.build_dir) + outfiles = [] + updated_files = [] + for script in self.scripts: + self._copy_script(script, outfiles, updated_files) + + self._change_modes(outfiles) + + return outfiles, updated_files + + def _copy_script(self, script, outfiles, updated_files): + shebang_match = None + script = convert_path(script) + outfile = os.path.join(self.build_dir, os.path.basename(script)) + outfiles.append(outfile) + + if not self.force and not newer(script, outfile): + log.debug("not copying %s (up-to-date)", script) + return + + # Always open the file, but ignore failures in dry-run mode + # in order to attempt to copy directly. + f = tokenize.open(script) + + first_line = f.readline() + if not first_line: + self.warn(f"{script} is an empty file (skipping)") + return + + shebang_match = shebang_pattern.match(first_line) + + updated_files.append(outfile) + if shebang_match: + log.info("copying and adjusting %s -> %s", script, self.build_dir) + post_interp = shebang_match.group(1) or '' + shebang = "#!" + self.executable + post_interp + "\n" + self._validate_shebang(shebang, f.encoding) + with open(outfile, "w", encoding=f.encoding) as outf: + outf.write(shebang) + outf.writelines(f.readlines()) + if f: + f.close() + else: + if f: + f.close() + self.copy_file(script, outfile) + + def _change_modes(self, outfiles): + if os.name != 'posix': + return + + for file in outfiles: + self._change_mode(file) + + def _change_mode(self, file): + oldmode = os.stat(file)[ST_MODE] & 0o7777 + newmode = (oldmode | 0o555) & 0o7777 + if newmode != oldmode: + log.info("changing mode of %s from %o to %o", file, oldmode, newmode) + os.chmod(file, newmode) + + @staticmethod + def _validate_shebang(shebang, encoding): + # Python parser starts to read a script using UTF-8 until + # it gets a #coding:xxx cookie. The shebang has to be the + # first line of a file, the #coding:xxx cookie cannot be + # written before. So the shebang has to be encodable to + # UTF-8. + try: + shebang.encode('utf-8') + except UnicodeEncodeError: + raise ValueError(f"The shebang ({shebang!r}) is not encodable to utf-8") + + # If the script is encoded to a custom encoding (use a + # #coding:xxx cookie), the shebang has to be encodable to + # the script encoding too. + try: + shebang.encode(encoding) + except UnicodeEncodeError: + raise ValueError( + f"The shebang ({shebang!r}) is not encodable " + f"to the script encoding ({encoding})" + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/check.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/check.py new file mode 100644 index 0000000000000000000000000000000000000000..58a823dd3904cf105ed432e458a45d94948fbb4c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/check.py @@ -0,0 +1,152 @@ +"""distutils.command.check + +Implements the Distutils 'check' command. +""" + +import contextlib +from typing import ClassVar + +from ..core import Command +from ..errors import DistutilsSetupError + +with contextlib.suppress(ImportError): + import docutils.frontend + import docutils.nodes + import docutils.parsers.rst + import docutils.utils + + class SilentReporter(docutils.utils.Reporter): + def __init__( + self, + source, + report_level, + halt_level, + stream=None, + debug=False, + encoding='ascii', + error_handler='replace', + ): + self.messages = [] + super().__init__( + source, report_level, halt_level, stream, debug, encoding, error_handler + ) + + def system_message(self, level, message, *children, **kwargs): + self.messages.append((level, message, children, kwargs)) + return docutils.nodes.system_message( + message, *children, level=level, type=self.levels[level], **kwargs + ) + + +class check(Command): + """This command checks the meta-data of the package.""" + + description = "perform some checks on the package" + user_options: ClassVar[list[tuple[str, str, str]]] = [ + ('metadata', 'm', 'Verify meta-data'), + ( + 'restructuredtext', + 'r', + 'Checks if long string meta-data syntax are reStructuredText-compliant', + ), + ('strict', 's', 'Will exit with an error if a check fails'), + ] + + boolean_options: ClassVar[list[str]] = ['metadata', 'restructuredtext', 'strict'] + + def initialize_options(self): + """Sets default values for options.""" + self.restructuredtext = False + self.metadata = 1 + self.strict = False + self._warnings = 0 + + def finalize_options(self): + pass + + def warn(self, msg): + """Counts the number of warnings that occurs.""" + self._warnings += 1 + return Command.warn(self, msg) + + def run(self): + """Runs the command.""" + # perform the various tests + if self.metadata: + self.check_metadata() + if self.restructuredtext: + if 'docutils' in globals(): + try: + self.check_restructuredtext() + except TypeError as exc: + raise DistutilsSetupError(str(exc)) + elif self.strict: + raise DistutilsSetupError('The docutils package is needed.') + + # let's raise an error in strict mode, if we have at least + # one warning + if self.strict and self._warnings > 0: + raise DistutilsSetupError('Please correct your package.') + + def check_metadata(self): + """Ensures that all required elements of meta-data are supplied. + + Required fields: + name, version + + Warns if any are missing. + """ + metadata = self.distribution.metadata + + missing = [ + attr for attr in ('name', 'version') if not getattr(metadata, attr, None) + ] + + if missing: + self.warn("missing required meta-data: {}".format(', '.join(missing))) + + def check_restructuredtext(self): + """Checks if the long string fields are reST-compliant.""" + data = self.distribution.get_long_description() + for warning in self._check_rst_data(data): + line = warning[-1].get('line') + if line is None: + warning = warning[1] + else: + warning = f'{warning[1]} (line {line})' + self.warn(warning) + + def _check_rst_data(self, data): + """Returns warnings when the provided data doesn't compile.""" + # the include and csv_table directives need this to be a path + source_path = self.distribution.script_name or 'setup.py' + parser = docutils.parsers.rst.Parser() + settings = docutils.frontend.OptionParser( + components=(docutils.parsers.rst.Parser,) + ).get_default_values() + settings.tab_width = 4 + settings.pep_references = None + settings.rfc_references = None + reporter = SilentReporter( + source_path, + settings.report_level, + settings.halt_level, + stream=settings.warning_stream, + debug=settings.debug, + encoding=settings.error_encoding, + error_handler=settings.error_encoding_error_handler, + ) + + document = docutils.nodes.document(settings, reporter, source=source_path) + document.note_source(source_path, -1) + try: + parser.parse(data, document) + except (AttributeError, TypeError) as e: + reporter.messages.append(( + -1, + f'Could not finish the parsing: {e}.', + '', + {}, + )) + + return reporter.messages diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/clean.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/clean.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1711be8ef51e2bcd5fe2742588f95a65bcd153 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/clean.py @@ -0,0 +1,76 @@ +"""distutils.command.clean + +Implements the Distutils 'clean' command.""" + +# contributed by Bastian Kleineidam , added 2000-03-18 + +import os +from distutils._log import log +from typing import ClassVar + +from ..core import Command +from ..dir_util import remove_tree + + +class clean(Command): + description = "clean up temporary files from 'build' command" + user_options = [ + ('build-base=', 'b', "base build directory [default: 'build.build-base']"), + ( + 'build-lib=', + None, + "build directory for all modules [default: 'build.build-lib']", + ), + ('build-temp=', 't', "temporary build directory [default: 'build.build-temp']"), + ( + 'build-scripts=', + None, + "build directory for scripts [default: 'build.build-scripts']", + ), + ('bdist-base=', None, "temporary directory for built distributions"), + ('all', 'a', "remove all build output, not just temporary by-products"), + ] + + boolean_options: ClassVar[list[str]] = ['all'] + + def initialize_options(self): + self.build_base = None + self.build_lib = None + self.build_temp = None + self.build_scripts = None + self.bdist_base = None + self.all = None + + def finalize_options(self): + self.set_undefined_options( + 'build', + ('build_base', 'build_base'), + ('build_lib', 'build_lib'), + ('build_scripts', 'build_scripts'), + ('build_temp', 'build_temp'), + ) + self.set_undefined_options('bdist', ('bdist_base', 'bdist_base')) + + def run(self): + # remove the build/temp. directory (unless it's already + # gone) + if os.path.exists(self.build_temp): + remove_tree(self.build_temp) + else: + log.debug("'%s' does not exist -- can't clean it", self.build_temp) + + if self.all: + # remove build directories + for directory in (self.build_lib, self.bdist_base, self.build_scripts): + if os.path.exists(directory): + remove_tree(directory) + else: + log.warning("'%s' does not exist -- can't clean it", directory) + + # just for the heck of it, try to remove the base build directory: + # we might have emptied it right now, but if not we don't care + try: + os.rmdir(self.build_base) + log.info("removing '%s'", self.build_base) + except OSError: + pass diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/config.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9818418f2675125631e7d9d1ad74c30487e9dd5b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/config.py @@ -0,0 +1,348 @@ +"""distutils.command.config + +Implements the Distutils 'config' command, a (mostly) empty command class +that exists mainly to be sub-classed by specific module distributions and +applications. The idea is that while every "config" command is different, +at least they're all named the same, and users always see "config" in the +list of standard commands. Also, this is a good place to put common +configure-like tasks: "try to compile this C code", or "figure out where +this header file lives". +""" + +from __future__ import annotations + +import os +import pathlib +import re +from collections.abc import Sequence +from distutils._log import log + +from ..ccompiler import CCompiler, CompileError, LinkError, new_compiler +from ..core import Command +from ..errors import DistutilsExecError +from ..sysconfig import customize_compiler + +LANG_EXT = {"c": ".c", "c++": ".cxx"} + + +class config(Command): + description = "prepare to build" + + user_options = [ + ('compiler=', None, "specify the compiler type"), + ('cc=', None, "specify the compiler executable"), + ('include-dirs=', 'I', "list of directories to search for header files"), + ('define=', 'D', "C preprocessor macros to define"), + ('undef=', 'U', "C preprocessor macros to undefine"), + ('libraries=', 'l', "external C libraries to link with"), + ('library-dirs=', 'L', "directories to search for external C libraries"), + ('noisy', None, "show every action (compile, link, run, ...) taken"), + ( + 'dump-source', + None, + "dump generated source files before attempting to compile them", + ), + ] + + # The three standard command methods: since the "config" command + # does nothing by default, these are empty. + + def initialize_options(self): + self.compiler = None + self.cc = None + self.include_dirs = None + self.libraries = None + self.library_dirs = None + + # maximal output for now + self.noisy = 1 + self.dump_source = 1 + + # list of temporary files generated along-the-way that we have + # to clean at some point + self.temp_files = [] + + def finalize_options(self): + if self.include_dirs is None: + self.include_dirs = self.distribution.include_dirs or [] + elif isinstance(self.include_dirs, str): + self.include_dirs = self.include_dirs.split(os.pathsep) + + if self.libraries is None: + self.libraries = [] + elif isinstance(self.libraries, str): + self.libraries = [self.libraries] + + if self.library_dirs is None: + self.library_dirs = [] + elif isinstance(self.library_dirs, str): + self.library_dirs = self.library_dirs.split(os.pathsep) + + def run(self): + pass + + # Utility methods for actual "config" commands. The interfaces are + # loosely based on Autoconf macros of similar names. Sub-classes + # may use these freely. + + def _check_compiler(self): + """Check that 'self.compiler' really is a CCompiler object; + if not, make it one. + """ + if not isinstance(self.compiler, CCompiler): + self.compiler = new_compiler(compiler=self.compiler, force=True) + customize_compiler(self.compiler) + if self.include_dirs: + self.compiler.set_include_dirs(self.include_dirs) + if self.libraries: + self.compiler.set_libraries(self.libraries) + if self.library_dirs: + self.compiler.set_library_dirs(self.library_dirs) + + def _gen_temp_sourcefile(self, body, headers, lang): + filename = "_configtest" + LANG_EXT[lang] + with open(filename, "w", encoding='utf-8') as file: + if headers: + for header in headers: + file.write(f"#include <{header}>\n") + file.write("\n") + file.write(body) + if body[-1] != "\n": + file.write("\n") + return filename + + def _preprocess(self, body, headers, include_dirs, lang): + src = self._gen_temp_sourcefile(body, headers, lang) + out = "_configtest.i" + self.temp_files.extend([src, out]) + self.compiler.preprocess(src, out, include_dirs=include_dirs) + return (src, out) + + def _compile(self, body, headers, include_dirs, lang): + src = self._gen_temp_sourcefile(body, headers, lang) + if self.dump_source: + dump_file(src, f"compiling '{src}':") + (obj,) = self.compiler.object_filenames([src]) + self.temp_files.extend([src, obj]) + self.compiler.compile([src], include_dirs=include_dirs) + return (src, obj) + + def _link(self, body, headers, include_dirs, libraries, library_dirs, lang): + (src, obj) = self._compile(body, headers, include_dirs, lang) + prog = os.path.splitext(os.path.basename(src))[0] + self.compiler.link_executable( + [obj], + prog, + libraries=libraries, + library_dirs=library_dirs, + target_lang=lang, + ) + + if self.compiler.exe_extension is not None: + prog = prog + self.compiler.exe_extension + self.temp_files.append(prog) + + return (src, obj, prog) + + def _clean(self, *filenames): + if not filenames: + filenames = self.temp_files + self.temp_files = [] + log.info("removing: %s", ' '.join(filenames)) + for filename in filenames: + try: + os.remove(filename) + except OSError: + pass + + # XXX need access to the header search path and maybe default macros. + + def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"): + """Construct a source file from 'body' (a string containing lines + of C/C++ code) and 'headers' (a list of header files to include) + and run it through the preprocessor. Return true if the + preprocessor succeeded, false if there were any errors. + ('body' probably isn't of much use, but what the heck.) + """ + self._check_compiler() + ok = True + try: + self._preprocess(body, headers, include_dirs, lang) + except CompileError: + ok = False + + self._clean() + return ok + + def search_cpp(self, pattern, body=None, headers=None, include_dirs=None, lang="c"): + """Construct a source file (just like 'try_cpp()'), run it through + the preprocessor, and return true if any line of the output matches + 'pattern'. 'pattern' should either be a compiled regex object or a + string containing a regex. If both 'body' and 'headers' are None, + preprocesses an empty file -- which can be useful to determine the + symbols the preprocessor and compiler set by default. + """ + self._check_compiler() + src, out = self._preprocess(body, headers, include_dirs, lang) + + if isinstance(pattern, str): + pattern = re.compile(pattern) + + with open(out, encoding='utf-8') as file: + match = any(pattern.search(line) for line in file) + + self._clean() + return match + + def try_compile(self, body, headers=None, include_dirs=None, lang="c"): + """Try to compile a source file built from 'body' and 'headers'. + Return true on success, false otherwise. + """ + self._check_compiler() + try: + self._compile(body, headers, include_dirs, lang) + ok = True + except CompileError: + ok = False + + log.info(ok and "success!" or "failure.") + self._clean() + return ok + + def try_link( + self, + body, + headers=None, + include_dirs=None, + libraries=None, + library_dirs=None, + lang="c", + ): + """Try to compile and link a source file, built from 'body' and + 'headers', to executable form. Return true on success, false + otherwise. + """ + self._check_compiler() + try: + self._link(body, headers, include_dirs, libraries, library_dirs, lang) + ok = True + except (CompileError, LinkError): + ok = False + + log.info(ok and "success!" or "failure.") + self._clean() + return ok + + def try_run( + self, + body, + headers=None, + include_dirs=None, + libraries=None, + library_dirs=None, + lang="c", + ): + """Try to compile, link to an executable, and run a program + built from 'body' and 'headers'. Return true on success, false + otherwise. + """ + self._check_compiler() + try: + src, obj, exe = self._link( + body, headers, include_dirs, libraries, library_dirs, lang + ) + self.spawn([exe]) + ok = True + except (CompileError, LinkError, DistutilsExecError): + ok = False + + log.info(ok and "success!" or "failure.") + self._clean() + return ok + + # -- High-level methods -------------------------------------------- + # (these are the ones that are actually likely to be useful + # when implementing a real-world config command!) + + def check_func( + self, + func, + headers=None, + include_dirs=None, + libraries=None, + library_dirs=None, + decl=False, + call=False, + ): + """Determine if function 'func' is available by constructing a + source file that refers to 'func', and compiles and links it. + If everything succeeds, returns true; otherwise returns false. + + The constructed source file starts out by including the header + files listed in 'headers'. If 'decl' is true, it then declares + 'func' (as "int func()"); you probably shouldn't supply 'headers' + and set 'decl' true in the same call, or you might get errors about + a conflicting declarations for 'func'. Finally, the constructed + 'main()' function either references 'func' or (if 'call' is true) + calls it. 'libraries' and 'library_dirs' are used when + linking. + """ + self._check_compiler() + body = [] + if decl: + body.append(f"int {func} ();") + body.append("int main () {") + if call: + body.append(f" {func}();") + else: + body.append(f" {func};") + body.append("}") + body = "\n".join(body) + "\n" + + return self.try_link(body, headers, include_dirs, libraries, library_dirs) + + def check_lib( + self, + library, + library_dirs=None, + headers=None, + include_dirs=None, + other_libraries: Sequence[str] = [], + ): + """Determine if 'library' is available to be linked against, + without actually checking that any particular symbols are provided + by it. 'headers' will be used in constructing the source file to + be compiled, but the only effect of this is to check if all the + header files listed are available. Any libraries listed in + 'other_libraries' will be included in the link, in case 'library' + has symbols that depend on other libraries. + """ + self._check_compiler() + return self.try_link( + "int main (void) { }", + headers, + include_dirs, + [library] + list(other_libraries), + library_dirs, + ) + + def check_header(self, header, include_dirs=None, library_dirs=None, lang="c"): + """Determine if the system header file named by 'header_file' + exists and can be found by the preprocessor; return true if so, + false otherwise. + """ + return self.try_cpp( + body="/* No body */", headers=[header], include_dirs=include_dirs + ) + + +def dump_file(filename, head=None): + """Dumps a file content into log.info. + + If head is not None, will be dumped before the file content. + """ + if head is None: + log.info('%s', filename) + else: + log.info(head) + log.info(pathlib.Path(filename).read_text(encoding='utf-8')) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install.py new file mode 100644 index 0000000000000000000000000000000000000000..dc17e56a8070b26f0e3d09c82250e006f1aed826 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install.py @@ -0,0 +1,805 @@ +"""distutils.command.install + +Implements the Distutils 'install' command.""" + +from __future__ import annotations + +import collections +import contextlib +import itertools +import os +import sys +import sysconfig +from distutils._log import log +from site import USER_BASE, USER_SITE +from typing import ClassVar + +from ..core import Command +from ..debug import DEBUG +from ..errors import DistutilsOptionError, DistutilsPlatformError +from ..file_util import write_file +from ..sysconfig import get_config_vars +from ..util import change_root, convert_path, get_platform, subst_vars +from . import _framework_compat as fw + +HAS_USER_SITE = True + +WINDOWS_SCHEME = { + 'purelib': '{base}/Lib/site-packages', + 'platlib': '{base}/Lib/site-packages', + 'headers': '{base}/Include/{dist_name}', + 'scripts': '{base}/Scripts', + 'data': '{base}', +} + +INSTALL_SCHEMES = { + 'posix_prefix': { + 'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages', + 'platlib': '{platbase}/{platlibdir}/{implementation_lower}' + '{py_version_short}/site-packages', + 'headers': '{base}/include/{implementation_lower}' + '{py_version_short}{abiflags}/{dist_name}', + 'scripts': '{base}/bin', + 'data': '{base}', + }, + 'posix_home': { + 'purelib': '{base}/lib/{implementation_lower}', + 'platlib': '{base}/{platlibdir}/{implementation_lower}', + 'headers': '{base}/include/{implementation_lower}/{dist_name}', + 'scripts': '{base}/bin', + 'data': '{base}', + }, + 'nt': WINDOWS_SCHEME, + 'pypy': { + 'purelib': '{base}/site-packages', + 'platlib': '{base}/site-packages', + 'headers': '{base}/include/{dist_name}', + 'scripts': '{base}/bin', + 'data': '{base}', + }, + 'pypy_nt': { + 'purelib': '{base}/site-packages', + 'platlib': '{base}/site-packages', + 'headers': '{base}/include/{dist_name}', + 'scripts': '{base}/Scripts', + 'data': '{base}', + }, +} + +# user site schemes +if HAS_USER_SITE: + INSTALL_SCHEMES['nt_user'] = { + 'purelib': '{usersite}', + 'platlib': '{usersite}', + 'headers': '{userbase}/{implementation}{py_version_nodot_plat}' + '/Include/{dist_name}', + 'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts', + 'data': '{userbase}', + } + + INSTALL_SCHEMES['posix_user'] = { + 'purelib': '{usersite}', + 'platlib': '{usersite}', + 'headers': '{userbase}/include/{implementation_lower}' + '{py_version_short}{abiflags}/{dist_name}', + 'scripts': '{userbase}/bin', + 'data': '{userbase}', + } + + +INSTALL_SCHEMES.update(fw.schemes) + + +# The keys to an installation scheme; if any new types of files are to be +# installed, be sure to add an entry to every installation scheme above, +# and to SCHEME_KEYS here. +SCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data') + + +def _load_sysconfig_schemes(): + with contextlib.suppress(AttributeError): + return { + scheme: sysconfig.get_paths(scheme, expand=False) + for scheme in sysconfig.get_scheme_names() + } + + +def _load_schemes(): + """ + Extend default schemes with schemes from sysconfig. + """ + + sysconfig_schemes = _load_sysconfig_schemes() or {} + + return { + scheme: { + **INSTALL_SCHEMES.get(scheme, {}), + **sysconfig_schemes.get(scheme, {}), + } + for scheme in set(itertools.chain(INSTALL_SCHEMES, sysconfig_schemes)) + } + + +def _get_implementation(): + if hasattr(sys, 'pypy_version_info'): + return 'PyPy' + else: + return 'Python' + + +def _select_scheme(ob, name): + scheme = _inject_headers(name, _load_scheme(_resolve_scheme(name))) + vars(ob).update(_remove_set(ob, _scheme_attrs(scheme))) + + +def _remove_set(ob, attrs): + """ + Include only attrs that are None in ob. + """ + return {key: value for key, value in attrs.items() if getattr(ob, key) is None} + + +def _resolve_scheme(name): + os_name, sep, key = name.partition('_') + try: + resolved = sysconfig.get_preferred_scheme(key) + except Exception: + resolved = fw.scheme(name) + return resolved + + +def _load_scheme(name): + return _load_schemes()[name] + + +def _inject_headers(name, scheme): + """ + Given a scheme name and the resolved scheme, + if the scheme does not include headers, resolve + the fallback scheme for the name and use headers + from it. pypa/distutils#88 + """ + # Bypass the preferred scheme, which may not + # have defined headers. + fallback = _load_scheme(name) + scheme.setdefault('headers', fallback['headers']) + return scheme + + +def _scheme_attrs(scheme): + """Resolve install directories by applying the install schemes.""" + return {f'install_{key}': scheme[key] for key in SCHEME_KEYS} + + +class install(Command): + description = "install everything from build directory" + + user_options = [ + # Select installation scheme and set base director(y|ies) + ('prefix=', None, "installation prefix"), + ('exec-prefix=', None, "(Unix only) prefix for platform-specific files"), + ('home=', None, "(Unix only) home directory to install under"), + # Or, just set the base director(y|ies) + ( + 'install-base=', + None, + "base installation directory (instead of --prefix or --home)", + ), + ( + 'install-platbase=', + None, + "base installation directory for platform-specific files (instead of --exec-prefix or --home)", + ), + ('root=', None, "install everything relative to this alternate root directory"), + # Or, explicitly set the installation scheme + ( + 'install-purelib=', + None, + "installation directory for pure Python module distributions", + ), + ( + 'install-platlib=', + None, + "installation directory for non-pure module distributions", + ), + ( + 'install-lib=', + None, + "installation directory for all module distributions (overrides --install-purelib and --install-platlib)", + ), + ('install-headers=', None, "installation directory for C/C++ headers"), + ('install-scripts=', None, "installation directory for Python scripts"), + ('install-data=', None, "installation directory for data files"), + # Byte-compilation options -- see install_lib.py for details, as + # these are duplicated from there (but only install_lib does + # anything with them). + ('compile', 'c', "compile .py to .pyc [default]"), + ('no-compile', None, "don't compile .py files"), + ( + 'optimize=', + 'O', + "also compile with optimization: -O1 for \"python -O\", " + "-O2 for \"python -OO\", and -O0 to disable [default: -O0]", + ), + # Miscellaneous control options + ('force', 'f', "force installation (overwrite any existing files)"), + ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), + # Where to install documentation (eventually!) + # ('doc-format=', None, "format of documentation to generate"), + # ('install-man=', None, "directory for Unix man pages"), + # ('install-html=', None, "directory for HTML documentation"), + # ('install-info=', None, "directory for GNU info files"), + ('record=', None, "filename in which to record list of installed files"), + ] + + boolean_options: ClassVar[list[str]] = ['compile', 'force', 'skip-build'] + + if HAS_USER_SITE: + user_options.append(( + 'user', + None, + f"install in user site-package '{USER_SITE}'", + )) + boolean_options.append('user') + + negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'} + + def initialize_options(self) -> None: + """Initializes options.""" + # High-level options: these select both an installation base + # and scheme. + self.prefix: str | None = None + self.exec_prefix: str | None = None + self.home: str | None = None + self.user = False + + # These select only the installation base; it's up to the user to + # specify the installation scheme (currently, that means supplying + # the --install-{platlib,purelib,scripts,data} options). + self.install_base = None + self.install_platbase = None + self.root: str | None = None + + # These options are the actual installation directories; if not + # supplied by the user, they are filled in using the installation + # scheme implied by prefix/exec-prefix/home and the contents of + # that installation scheme. + 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: str | None = None # set to either purelib or platlib + self.install_scripts = None + self.install_data = None + self.install_userbase = USER_BASE + self.install_usersite = USER_SITE + + self.compile = None + self.optimize = None + + # Deprecated + # These two are for putting non-packagized distributions into their + # own directory and creating a .pth file if it makes sense. + # 'extra_path' comes from the setup file; 'install_path_file' can + # be turned off if it makes no sense to install a .pth file. (But + # better to install it uselessly than to guess wrong and not + # install it when it's necessary and would be used!) Currently, + # 'install_path_file' is always true unless some outsider meddles + # with it. + self.extra_path = None + self.install_path_file = True + + # 'force' forces installation, even if target files are not + # out-of-date. 'skip_build' skips running the "build" command, + # handy if you know it's not necessary. 'warn_dir' (which is *not* + # a user option, it's just there so the bdist_* commands can turn + # it off) determines whether we warn about installing to a + # directory not in sys.path. + self.force = False + self.skip_build = False + self.warn_dir = True + + # These are only here as a conduit from the 'build' command to the + # 'install_*' commands that do the real work. ('build_base' isn't + # actually used anywhere, but it might be useful in future.) They + # are not user options, because if the user told the install + # command where the build directory is, that wouldn't affect the + # build command. + self.build_base = None + self.build_lib = None + + # Not defined yet because we don't know anything about + # documentation yet. + # self.install_man = None + # self.install_html = None + # self.install_info = None + + self.record = None + + # -- Option finalizing methods ------------------------------------- + # (This is rather more involved than for most commands, + # because this is where the policy for installing third- + # party Python modules on various platforms given a wide + # array of user input is decided. Yes, it's quite complex!) + + def finalize_options(self) -> None: # noqa: C901 + """Finalizes options.""" + # This method (and its helpers, like 'finalize_unix()', + # 'finalize_other()', and 'select_scheme()') is where the default + # installation directories for modules, extension modules, and + # anything else we care to install from a Python module + # distribution. Thus, this code makes a pretty important policy + # statement about how third-party stuff is added to a Python + # installation! Note that the actual work of installation is done + # by the relatively simple 'install_*' commands; they just take + # their orders from the installation directory options determined + # here. + + # Check for errors/inconsistencies in the options; first, stuff + # that's wrong on any platform. + + if (self.prefix or self.exec_prefix or self.home) and ( + self.install_base or self.install_platbase + ): + raise DistutilsOptionError( + "must supply either prefix/exec-prefix/home or install-base/install-platbase -- not both" + ) + + if self.home and (self.prefix or self.exec_prefix): + raise DistutilsOptionError( + "must supply either home or prefix/exec-prefix -- not both" + ) + + if self.user and ( + self.prefix + or self.exec_prefix + or self.home + or self.install_base + or self.install_platbase + ): + raise DistutilsOptionError( + "can't combine user with prefix, " + "exec_prefix/home, or install_(plat)base" + ) + + # Next, stuff that's wrong (or dubious) only on certain platforms. + if os.name != "posix": + if self.exec_prefix: + self.warn("exec-prefix option ignored on this platform") + self.exec_prefix = None + + # Now the interesting logic -- so interesting that we farm it out + # to other methods. The goal of these methods is to set the final + # values for the install_{lib,scripts,data,...} options, using as + # input a heady brew of prefix, exec_prefix, home, install_base, + # install_platbase, user-supplied versions of + # install_{purelib,platlib,lib,scripts,data,...}, and the + # install schemes. Phew! + + self.dump_dirs("pre-finalize_{unix,other}") + + if os.name == 'posix': + self.finalize_unix() + else: + self.finalize_other() + + self.dump_dirs("post-finalize_{unix,other}()") + + # Expand configuration variables, tilde, etc. in self.install_base + # and self.install_platbase -- that way, we can use $base or + # $platbase in the other installation directories and not worry + # about needing recursive variable expansion (shudder). + + py_version = sys.version.split()[0] + (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix') + try: + abiflags = sys.abiflags + except AttributeError: + # sys.abiflags may not be defined on all platforms. + abiflags = '' + local_vars = { + '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': prefix, + 'prefix': prefix, + 'sys_exec_prefix': exec_prefix, + 'exec_prefix': exec_prefix, + 'abiflags': abiflags, + 'platlibdir': getattr(sys, 'platlibdir', 'lib'), + 'implementation_lower': _get_implementation().lower(), + 'implementation': _get_implementation(), + } + + # vars for compatibility on older Pythons + compat_vars = dict( + # Python 3.9 and earlier + py_version_nodot_plat=getattr(sys, 'winver', '').replace('.', ''), + ) + + if HAS_USER_SITE: + local_vars['userbase'] = self.install_userbase + local_vars['usersite'] = self.install_usersite + + self.config_vars = collections.ChainMap( + local_vars, + sysconfig.get_config_vars(), + compat_vars, + fw.vars(), + ) + + self.expand_basedirs() + + self.dump_dirs("post-expand_basedirs()") + + # Now define config vars for the base directories so we can expand + # everything else. + local_vars['base'] = self.install_base + local_vars['platbase'] = self.install_platbase + + if DEBUG: + from pprint import pprint + + print("config vars:") + pprint(dict(self.config_vars)) + + # Expand "~" and configuration variables in the installation + # directories. + self.expand_dirs() + + self.dump_dirs("post-expand_dirs()") + + # Create directories in the home dir: + if self.user: + self.create_home_path() + + # Pick the actual directory to install all modules to: either + # install_purelib or install_platlib, depending on whether this + # module distribution is pure or not. Of course, if the user + # already specified install_lib, use their selection. + if self.install_lib is None: + if self.distribution.has_ext_modules(): # has extensions: non-pure + self.install_lib = self.install_platlib + else: + self.install_lib = self.install_purelib + + # Convert directories from Unix /-separated syntax to the local + # convention. + self.convert_paths( + 'lib', + 'purelib', + 'platlib', + 'scripts', + 'data', + 'headers', + 'userbase', + 'usersite', + ) + + # Deprecated + # Well, we're not actually fully completely finalized yet: we still + # have to deal with 'extra_path', which is the hack for allowing + # non-packagized module distributions (hello, Numerical Python!) to + # get their own directories. + self.handle_extra_path() + self.install_libbase = self.install_lib # needed for .pth file + self.install_lib = os.path.join(self.install_lib, self.extra_dirs) + + # If a new root directory was supplied, make all the installation + # dirs relative to it. + if self.root is not None: + self.change_roots( + 'libbase', 'lib', 'purelib', 'platlib', 'scripts', 'data', 'headers' + ) + + self.dump_dirs("after prepending root") + + # Find out the build directories, ie. where to install from. + self.set_undefined_options( + 'build', ('build_base', 'build_base'), ('build_lib', 'build_lib') + ) + + # Punt on doc directories for now -- after all, we're punting on + # documentation completely! + + def dump_dirs(self, msg) -> None: + """Dumps the list of user options.""" + if not DEBUG: + return + from ..fancy_getopt import longopt_xlate + + log.debug(msg + ":") + for opt in self.user_options: + opt_name = opt[0] + if opt_name[-1] == "=": + opt_name = opt_name[0:-1] + if opt_name in self.negative_opt: + opt_name = self.negative_opt[opt_name] + opt_name = opt_name.translate(longopt_xlate) + val = not getattr(self, opt_name) + else: + opt_name = opt_name.translate(longopt_xlate) + val = getattr(self, opt_name) + log.debug(" %s: %s", opt_name, val) + + def finalize_unix(self) -> None: + """Finalizes options for posix platforms.""" + if self.install_base is not None or self.install_platbase is not None: + incomplete_scheme = ( + ( + self.install_lib is None + and self.install_purelib is None + and self.install_platlib is None + ) + or self.install_headers is None + or self.install_scripts is None + or self.install_data is None + ) + if incomplete_scheme: + raise DistutilsOptionError( + "install-base or install-platbase supplied, but " + "installation scheme is incomplete" + ) + return + + if self.user: + if self.install_userbase is None: + raise DistutilsPlatformError("User base directory is not specified") + self.install_base = self.install_platbase = self.install_userbase + self.select_scheme("posix_user") + elif self.home is not None: + self.install_base = self.install_platbase = self.home + self.select_scheme("posix_home") + else: + if self.prefix is None: + if self.exec_prefix is not None: + raise DistutilsOptionError( + "must not supply exec-prefix without prefix" + ) + + # Allow Fedora to add components to the prefix + _prefix_addition = getattr(sysconfig, '_prefix_addition', "") + + self.prefix = os.path.normpath(sys.prefix) + _prefix_addition + self.exec_prefix = os.path.normpath(sys.exec_prefix) + _prefix_addition + + else: + if self.exec_prefix is None: + self.exec_prefix = self.prefix + + self.install_base = self.prefix + self.install_platbase = self.exec_prefix + self.select_scheme("posix_prefix") + + def finalize_other(self) -> None: + """Finalizes options for non-posix platforms""" + if self.user: + if self.install_userbase is None: + raise DistutilsPlatformError("User base directory is not specified") + self.install_base = self.install_platbase = self.install_userbase + self.select_scheme(os.name + "_user") + elif self.home is not None: + self.install_base = self.install_platbase = self.home + self.select_scheme("posix_home") + else: + if self.prefix is None: + self.prefix = os.path.normpath(sys.prefix) + + self.install_base = self.install_platbase = self.prefix + try: + self.select_scheme(os.name) + except KeyError: + raise DistutilsPlatformError( + f"I don't know how to install stuff on '{os.name}'" + ) + + def select_scheme(self, name) -> None: + _select_scheme(self, name) + + def _expand_attrs(self, attrs): + for attr in attrs: + val = getattr(self, attr) + if val is not None: + if os.name in ('posix', '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.""" + self._expand_attrs([ + 'install_purelib', + 'install_platlib', + 'install_lib', + 'install_headers', + 'install_scripts', + 'install_data', + ]) + + def convert_paths(self, *names) -> None: + """Call `convert_path` over `names`.""" + for name in names: + attr = "install_" + name + setattr(self, attr, convert_path(getattr(self, attr))) + + def handle_extra_path(self) -> None: + """Set `path_file` and `extra_dirs` using `extra_path`.""" + if self.extra_path is None: + self.extra_path = self.distribution.extra_path + + if self.extra_path is not None: + log.warning( + "Distribution option extra_path is deprecated. " + "See issue27919 for details." + ) + if isinstance(self.extra_path, str): + self.extra_path = self.extra_path.split(',') + + if len(self.extra_path) == 1: + path_file = extra_dirs = self.extra_path[0] + elif len(self.extra_path) == 2: + path_file, extra_dirs = self.extra_path + else: + raise DistutilsOptionError( + "'extra_path' option must be a list, tuple, or " + "comma-separated string with 1 or 2 elements" + ) + + # convert to local form in case Unix notation used (as it + # should be in setup scripts) + extra_dirs = convert_path(extra_dirs) + else: + path_file = None + extra_dirs = '' + + # XXX should we warn if path_file and not extra_dirs? (in which + # case the path file would be harmless but pointless) + self.path_file = path_file + self.extra_dirs = extra_dirs + + def change_roots(self, *names) -> None: + """Change the install directories pointed by name using root.""" + for name in names: + attr = "install_" + name + setattr(self, attr, change_root(self.root, getattr(self, attr))) + + def create_home_path(self) -> None: + """Create directories under ~.""" + if not self.user: + return + home = convert_path(os.path.expanduser("~")) + for path in self.config_vars.values(): + if str(path).startswith(home) and not os.path.isdir(path): + self.debug_print(f"os.makedirs('{path}', 0o700)") + os.makedirs(path, 0o700) + + # -- Command execution methods ------------------------------------- + + def run(self): + """Runs the command.""" + # Obviously have to build before we can install + if not self.skip_build: + self.run_command('build') + # If we built for any other platform, we can't install. + build_plat = self.distribution.get_command_obj('build').plat_name + # check warn_dir - it is a clue that the 'install' is happening + # internally, and not to sys.path, so we don't check the platform + # matches what we are running. + if self.warn_dir and build_plat != get_platform(): + raise DistutilsPlatformError("Can't install when cross-compiling") + + # Run all sub-commands (at least those that need to be run) + for cmd_name in self.get_sub_commands(): + self.run_command(cmd_name) + + if self.path_file: + self.create_path_file() + + # write list of installed files, if requested. + if self.record: + outputs = self.get_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:] + self.execute( + write_file, + (self.record, outputs), + f"writing list of installed files to '{self.record}'", + ) + + sys_path = map(os.path.normpath, sys.path) + sys_path = map(os.path.normcase, sys_path) + install_lib = os.path.normcase(os.path.normpath(self.install_lib)) + if ( + self.warn_dir + and not (self.path_file and self.install_path_file) + and install_lib not in sys_path + ): + log.debug( + ( + "modules installed to '%s', which is not in " + "Python's module search path (sys.path) -- " + "you'll have to change the search path yourself" + ), + self.install_lib, + ) + + def create_path_file(self): + """Creates the .pth file""" + filename = os.path.join(self.install_libbase, self.path_file + ".pth") + if self.install_path_file: + self.execute( + write_file, (filename, [self.extra_dirs]), f"creating {filename}" + ) + else: + self.warn(f"path file '{filename}' not created") + + # -- Reporting methods --------------------------------------------- + + def get_outputs(self): + """Assembles the outputs of all the sub-commands.""" + outputs = [] + for cmd_name in self.get_sub_commands(): + cmd = self.get_finalized_command(cmd_name) + # Add the contents of cmd.get_outputs(), ensuring + # that outputs doesn't contain duplicate entries + for filename in cmd.get_outputs(): + if filename not in outputs: + outputs.append(filename) + + if self.path_file and self.install_path_file: + outputs.append(os.path.join(self.install_libbase, self.path_file + ".pth")) + + return outputs + + def get_inputs(self): + """Returns the inputs of all the sub-commands""" + # XXX gee, this looks familiar ;-( + inputs = [] + for cmd_name in self.get_sub_commands(): + cmd = self.get_finalized_command(cmd_name) + inputs.extend(cmd.get_inputs()) + + return inputs + + # -- Predicates for sub-command list ------------------------------- + + def has_lib(self): + """Returns true if the current distribution has any Python + modules to install.""" + return ( + self.distribution.has_pure_modules() or self.distribution.has_ext_modules() + ) + + def has_headers(self): + """Returns true if the current distribution has any headers to + install.""" + return self.distribution.has_headers() + + def has_scripts(self): + """Returns true if the current distribution has any scripts to. + install.""" + return self.distribution.has_scripts() + + def has_data(self): + """Returns true if the current distribution has any data to. + install.""" + return self.distribution.has_data_files() + + # 'sub_commands': a list of commands this command might have to run to + # get its work done. See cmd.py for more info. + sub_commands = [ + ('install_lib', has_lib), + ('install_headers', has_headers), + ('install_scripts', has_scripts), + ('install_data', has_data), + ('install_egg_info', lambda self: True), + ] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_data.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_data.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad186e8ec61b92967ea1c12cdca51d00e82dd15 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_data.py @@ -0,0 +1,94 @@ +"""distutils.command.install_data + +Implements the Distutils 'install_data' command, for installing +platform-independent data files.""" + +# contributed by Bastian Kleineidam + +from __future__ import annotations + +import functools +import os +from collections.abc import Iterable +from typing import ClassVar + +from ..core import Command +from ..util import change_root, convert_path + + +class install_data(Command): + description = "install data files" + + user_options = [ + ( + 'install-dir=', + 'd', + "base directory for installing data files [default: installation base dir]", + ), + ('root=', None, "install everything relative to this alternate root directory"), + ('force', 'f', "force installation (overwrite existing files)"), + ] + + boolean_options: ClassVar[list[str]] = ['force'] + + def initialize_options(self): + self.install_dir = None + self.outfiles = [] + self.root = None + self.force = False + self.data_files = self.distribution.data_files + self.warn_dir = True + + def finalize_options(self) -> None: + self.set_undefined_options( + 'install', + ('install_data', 'install_dir'), + ('root', 'root'), + ('force', 'force'), + ) + + def run(self) -> None: + self.mkpath(self.install_dir) + for f in self.data_files: + self._copy(f) + + @functools.singledispatchmethod + def _copy(self, f: tuple[str | os.PathLike, Iterable[str | os.PathLike]]): + # it's a tuple with path to install to and a list of files + dir = convert_path(f[0]) + if not os.path.isabs(dir): + dir = os.path.join(self.install_dir, dir) + elif self.root: + dir = change_root(self.root, dir) + self.mkpath(dir) + + if f[1] == []: + # If there are no files listed, the user must be + # trying to create an empty directory, so add the + # directory to the list of output files. + self.outfiles.append(dir) + else: + # Copy files, adding them to the list of output files. + for data in f[1]: + data = convert_path(data) + (out, _) = self.copy_file(data, dir) + self.outfiles.append(out) + + @_copy.register(str) + @_copy.register(os.PathLike) + def _(self, f: str | os.PathLike): + # it's a simple file, so copy it + f = convert_path(f) + if self.warn_dir: + self.warn( + "setup script did not provide a directory for " + f"'{f}' -- installing right in '{self.install_dir}'" + ) + (out, _) = self.copy_file(f, self.install_dir) + self.outfiles.append(out) + + def get_inputs(self): + return self.data_files or [] + + def get_outputs(self): + return self.outfiles diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_egg_info.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_egg_info.py new file mode 100644 index 0000000000000000000000000000000000000000..6840b34ec2b5e2a3f9514cda5e940bc6cd90c731 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_egg_info.py @@ -0,0 +1,90 @@ +""" +distutils.command.install_egg_info + +Implements the Distutils 'install_egg_info' command, for installing +a package's PKG-INFO metadata. +""" + +import os +import re +import sys +from typing import ClassVar + +from .. import dir_util +from .._log import log +from ..cmd import Command + + +class install_egg_info(Command): + """Install an .egg-info file for the package""" + + description = "Install package's PKG-INFO metadata as an .egg-info file" + user_options: ClassVar[list[tuple[str, str, str]]] = [ + ('install-dir=', 'd', "directory to install to"), + ] + + def initialize_options(self): + self.install_dir = None + + @property + def basename(self): + """ + Allow basename to be overridden by child class. + Ref pypa/distutils#2. + """ + name = to_filename(safe_name(self.distribution.get_name())) + version = to_filename(safe_version(self.distribution.get_version())) + return f"{name}-{version}-py{sys.version_info.major}.{sys.version_info.minor}.egg-info" + + def finalize_options(self): + self.set_undefined_options('install_lib', ('install_dir', 'install_dir')) + self.target = os.path.join(self.install_dir, self.basename) + self.outputs = [self.target] + + def run(self): + target = self.target + if os.path.isdir(target) and not os.path.islink(target): + dir_util.remove_tree(target) + elif os.path.exists(target): + self.execute(os.unlink, (self.target,), "Removing " + target) + elif not os.path.isdir(self.install_dir): + self.execute( + os.makedirs, (self.install_dir,), "Creating " + self.install_dir + ) + log.info("Writing %s", target) + with open(target, 'w', encoding='UTF-8') as f: + self.distribution.metadata.write_pkg_file(f) + + def get_outputs(self): + return self.outputs + + +# The following routines are taken from setuptools' pkg_resources module and +# can be replaced by importing them from pkg_resources once it is included +# in the stdlib. + + +def safe_name(name): + """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): + """Convert an arbitrary string to a standard version string + + Spaces become dots, and all other non-alphanumeric characters become + dashes, with runs of multiple dashes condensed to a single dash. + """ + version = version.replace(' ', '.') + return re.sub('[^A-Za-z0-9.]+', '-', version) + + +def to_filename(name): + """Convert a project or version name to its filename-escaped form + + Any '-' characters are currently replaced with '_'. + """ + return name.replace('-', '_') diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_headers.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..97af1371efcc73423e9b91d7b3ced684ff936377 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_headers.py @@ -0,0 +1,46 @@ +"""distutils.command.install_headers + +Implements the Distutils 'install_headers' command, to install C/C++ header +files to the Python include directory.""" + +from typing import ClassVar + +from ..core import Command + + +# XXX force is never used +class install_headers(Command): + description = "install C/C++ header files" + + user_options: ClassVar[list[tuple[str, str, str]]] = [ + ('install-dir=', 'd', "directory to install header files to"), + ('force', 'f', "force installation (overwrite existing files)"), + ] + + boolean_options: ClassVar[list[str]] = ['force'] + + def initialize_options(self): + self.install_dir = None + self.force = False + self.outfiles = [] + + def finalize_options(self): + self.set_undefined_options( + 'install', ('install_headers', 'install_dir'), ('force', 'force') + ) + + def run(self): + headers = self.distribution.headers + if not headers: + return + + self.mkpath(self.install_dir) + for header in headers: + (out, _) = self.copy_file(header, self.install_dir) + self.outfiles.append(out) + + def get_inputs(self): + return self.distribution.headers or [] + + def get_outputs(self): + return self.outfiles diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_lib.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..9909a61762bd658f837057f07fa1d1200fe4e6ac --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_lib.py @@ -0,0 +1,236 @@ +"""distutils.command.install_lib + +Implements the Distutils 'install_lib' command +(install all Python modules).""" + +from __future__ import annotations + +import importlib.util +import os +import sys +from typing import Any, ClassVar + +from ..core import Command +from ..errors import DistutilsOptionError + +# Extension for Python source files. +PYTHON_SOURCE_EXTENSION = ".py" + + +class install_lib(Command): + description = "install all Python modules (extensions and pure Python)" + + # The byte-compilation options are a tad confusing. Here are the + # possible scenarios: + # 1) no compilation at all (--no-compile --no-optimize) + # 2) compile .pyc only (--compile --no-optimize; default) + # 3) compile .pyc and "opt-1" .pyc (--compile --optimize) + # 4) compile "opt-1" .pyc only (--no-compile --optimize) + # 5) compile .pyc and "opt-2" .pyc (--compile --optimize-more) + # 6) compile "opt-2" .pyc only (--no-compile --optimize-more) + # + # The UI for this is two options, 'compile' and 'optimize'. + # 'compile' is strictly boolean, and only decides whether to + # generate .pyc files. 'optimize' is three-way (0, 1, or 2), and + # decides both whether to generate .pyc files and what level of + # optimization to use. + + user_options = [ + ('install-dir=', 'd', "directory to install to"), + ('build-dir=', 'b', "build directory (where to install from)"), + ('force', 'f', "force installation (overwrite existing files)"), + ('compile', 'c', "compile .py to .pyc [default]"), + ('no-compile', None, "don't compile .py files"), + ( + 'optimize=', + 'O', + "also compile with optimization: -O1 for \"python -O\", " + "-O2 for \"python -OO\", and -O0 to disable [default: -O0]", + ), + ('skip-build', None, "skip the build steps"), + ] + + boolean_options: ClassVar[list[str]] = ['force', 'compile', 'skip-build'] + negative_opt: ClassVar[dict[str, str]] = {'no-compile': 'compile'} + + def initialize_options(self): + # let the 'install' command dictate our installation directory + self.install_dir = None + self.build_dir = None + self.force = False + self.compile = None + self.optimize = None + self.skip_build = None + + def finalize_options(self) -> None: + # Get all the information we need to install pure Python modules + # from the umbrella 'install' command -- build (source) directory, + # install (target) directory, and whether to compile .py files. + self.set_undefined_options( + 'install', + ('build_lib', 'build_dir'), + ('install_lib', 'install_dir'), + ('force', 'force'), + ('compile', 'compile'), + ('optimize', 'optimize'), + ('skip_build', 'skip_build'), + ) + + if self.compile is None: + self.compile = True + if self.optimize is None: + self.optimize = False + + if not isinstance(self.optimize, int): + try: + self.optimize = int(self.optimize) + except ValueError: + pass + if self.optimize not in (0, 1, 2): + raise DistutilsOptionError("optimize must be 0, 1, or 2") + + def run(self) -> None: + # Make sure we have built everything we need first + self.build() + + # Install everything: simply dump the entire contents of the build + # directory to the installation directory (that's the beauty of + # having a build directory!) + outfiles = self.install() + + # (Optionally) compile .py to .pyc + if outfiles is not None and self.distribution.has_pure_modules(): + self.byte_compile(outfiles) + + # -- Top-level worker functions ------------------------------------ + # (called from 'run()') + + def build(self) -> None: + if not self.skip_build: + if self.distribution.has_pure_modules(): + self.run_command('build_py') + if self.distribution.has_ext_modules(): + self.run_command('build_ext') + + # Any: https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#the-any-trick + def install(self) -> list[str] | Any: + if os.path.isdir(self.build_dir): + outfiles = self.copy_tree(self.build_dir, self.install_dir) + else: + self.warn( + f"'{self.build_dir}' does not exist -- no Python modules to install" + ) + return + return outfiles + + def byte_compile(self, files) -> None: + if sys.dont_write_bytecode: + self.warn('byte-compiling is disabled, skipping.') + return + + from ..util import byte_compile + + # Get the "--root" directory supplied to the "install" command, + # and use it as a prefix to strip off the purported filename + # encoded in bytecode files. This is far from complete, but it + # should at least generate usable bytecode in RPM distributions. + install_root = self.get_finalized_command('install').root + + if self.compile: + byte_compile( + files, + optimize=0, + force=self.force, + prefix=install_root, + ) + if self.optimize > 0: + byte_compile( + files, + optimize=self.optimize, + force=self.force, + prefix=install_root, + verbose=self.verbose, + ) + + # -- Utility methods ----------------------------------------------- + + def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir): + if not has_any: + return [] + + build_cmd = self.get_finalized_command(build_cmd) + build_files = build_cmd.get_outputs() + build_dir = getattr(build_cmd, cmd_option) + + prefix_len = len(build_dir) + len(os.sep) + outputs = [os.path.join(output_dir, file[prefix_len:]) for file in build_files] + + return outputs + + def _bytecode_filenames(self, py_filenames): + bytecode_files = [] + for py_file in py_filenames: + # Since build_py handles package data installation, the + # list of outputs can contain more than just .py files. + # Make sure we only report bytecode for the .py files. + ext = os.path.splitext(os.path.normcase(py_file))[1] + if ext != PYTHON_SOURCE_EXTENSION: + continue + if self.compile: + bytecode_files.append( + importlib.util.cache_from_source(py_file, optimization='') + ) + if self.optimize > 0: + bytecode_files.append( + importlib.util.cache_from_source( + py_file, optimization=self.optimize + ) + ) + + return bytecode_files + + # -- External interface -------------------------------------------- + # (called by outsiders) + + def get_outputs(self): + """Return the list of files that would be installed if this command + were actually run. Not affected by the "dry-run" flag or whether + modules have actually been built yet. + """ + pure_outputs = self._mutate_outputs( + self.distribution.has_pure_modules(), + 'build_py', + 'build_lib', + self.install_dir, + ) + if self.compile: + bytecode_outputs = self._bytecode_filenames(pure_outputs) + else: + bytecode_outputs = [] + + ext_outputs = self._mutate_outputs( + self.distribution.has_ext_modules(), + 'build_ext', + 'build_lib', + self.install_dir, + ) + + return pure_outputs + bytecode_outputs + ext_outputs + + def get_inputs(self): + """Get the list of files that are input to this command, ie. the + files that get installed as they are named in the build tree. + The files in this list correspond one-to-one to the output + filenames returned by 'get_outputs()'. + """ + inputs = [] + + if self.distribution.has_pure_modules(): + build_py = self.get_finalized_command('build_py') + inputs.extend(build_py.get_outputs()) + + if self.distribution.has_ext_modules(): + build_ext = self.get_finalized_command('build_ext') + inputs.extend(build_ext.get_outputs()) + + return inputs diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_scripts.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..33d235d976e39db426aaff628b8b9bb5b832dcb6 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/install_scripts.py @@ -0,0 +1,59 @@ +"""distutils.command.install_scripts + +Implements the Distutils 'install_scripts' command, for installing +Python scripts.""" + +# contributed by Bastian Kleineidam + +import os +from distutils._log import log +from stat import ST_MODE +from typing import ClassVar + +from ..core import Command + + +class install_scripts(Command): + description = "install scripts (Python or otherwise)" + + user_options = [ + ('install-dir=', 'd', "directory to install scripts to"), + ('build-dir=', 'b', "build directory (where to install from)"), + ('force', 'f', "force installation (overwrite existing files)"), + ('skip-build', None, "skip the build steps"), + ] + + boolean_options: ClassVar[list[str]] = ['force', 'skip-build'] + + def initialize_options(self): + self.install_dir = None + self.force = False + self.build_dir = None + self.skip_build = None + + def finalize_options(self) -> None: + self.set_undefined_options('build', ('build_scripts', 'build_dir')) + self.set_undefined_options( + 'install', + ('install_scripts', 'install_dir'), + ('force', 'force'), + ('skip_build', 'skip_build'), + ) + + def run(self) -> None: + if not self.skip_build: + self.run_command('build_scripts') + self.outfiles = self.copy_tree(self.build_dir, self.install_dir) + if os.name == 'posix': + # Set the executable bits (owner, group, and world) on + # all the scripts we just installed. + for file in self.get_outputs(): + mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777 + log.info("changing mode of %s to %o", file, mode) + os.chmod(file, mode) + + def get_inputs(self): + return self.distribution.scripts or [] + + def get_outputs(self): + return self.outfiles or [] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/sdist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..e64cc82902ac292fa391a219ff8eae117b252fe7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/command/sdist.py @@ -0,0 +1,521 @@ +"""distutils.command.sdist + +Implements the Distutils 'sdist' command (create a source distribution).""" + +from __future__ import annotations + +import os +import sys +from collections.abc import Callable +from distutils import archive_util, dir_util, file_util +from distutils._log import log +from glob import glob +from itertools import filterfalse +from typing import ClassVar + +from ..core import Command +from ..errors import DistutilsOptionError, DistutilsTemplateError +from ..filelist import FileList +from ..text_file import TextFile +from ..util import convert_path + + +def show_formats(): + """Print all possible values for the 'formats' option (used by + the "--help-formats" command-line option). + """ + from ..archive_util import ARCHIVE_FORMATS + from ..fancy_getopt import FancyGetopt + + formats = sorted( + ("formats=" + format, None, ARCHIVE_FORMATS[format][2]) + for format in ARCHIVE_FORMATS.keys() + ) + FancyGetopt(formats).print_help("List of available source distribution formats:") + + +class sdist(Command): + description = "create a source distribution (tarball, zip file, etc.)" + + def checking_metadata(self) -> bool: + """Callable used for the check sub-command. + + Placed here so user_options can view it""" + return self.metadata_check + + user_options = [ + ('template=', 't', "name of manifest template file [default: MANIFEST.in]"), + ('manifest=', 'm', "name of manifest file [default: MANIFEST]"), + ( + 'use-defaults', + None, + "include the default file set in the manifest " + "[default; disable with --no-defaults]", + ), + ('no-defaults', None, "don't include the default file set"), + ( + 'prune', + None, + "specifically exclude files/directories that should not be " + "distributed (build tree, RCS/CVS dirs, etc.) " + "[default; disable with --no-prune]", + ), + ('no-prune', None, "don't automatically exclude anything"), + ( + 'manifest-only', + 'o', + "just regenerate the manifest and then stop (implies --force-manifest)", + ), + ( + 'force-manifest', + 'f', + "forcibly regenerate the manifest and carry on as usual. " + "Deprecated: now the manifest is always regenerated.", + ), + ('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]", + ), + ( + 'metadata-check', + None, + "Ensure that all required elements of meta-data " + "are supplied. Warn if any missing. [default]", + ), + ( + '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]", + ), + ] + + boolean_options: ClassVar[list[str]] = [ + 'use-defaults', + 'prune', + 'manifest-only', + 'force-manifest', + 'keep-temp', + 'metadata-check', + ] + + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], object]]]] = [ + ('help-formats', None, "list available distribution formats", show_formats), + ] + + negative_opt: ClassVar[dict[str, str]] = { + 'no-defaults': 'use-defaults', + 'no-prune': 'prune', + } + + sub_commands = [('check', checking_metadata)] + + READMES: ClassVar[tuple[str, ...]] = ('README', 'README.txt', 'README.rst') + + def initialize_options(self): + # 'template' and 'manifest' are, respectively, the names of + # the manifest template and manifest file. + self.template = None + self.manifest = None + + # 'use_defaults': if true, we will include the default file set + # in the manifest + self.use_defaults = True + self.prune = True + + self.manifest_only = False + self.force_manifest = False + + self.formats = ['gztar'] + self.keep_temp = False + self.dist_dir = None + + self.archive_files = None + self.metadata_check = True + self.owner = None + self.group = None + + def finalize_options(self) -> None: + if self.manifest is None: + self.manifest = "MANIFEST" + if self.template is None: + self.template = "MANIFEST.in" + + self.ensure_string_list('formats') + + bad_format = archive_util.check_archive_formats(self.formats) + if bad_format: + raise DistutilsOptionError(f"unknown archive format '{bad_format}'") + + if self.dist_dir is None: + self.dist_dir = "dist" + + def run(self) -> None: + # 'filelist' contains the list of files that will make up the + # manifest + self.filelist = FileList() + + # Run sub commands + for cmd_name in self.get_sub_commands(): + self.run_command(cmd_name) + + # Do whatever it takes to get the list of files to process + # (process the manifest template, read an existing manifest, + # whatever). File list is accumulated in 'self.filelist'. + self.get_file_list() + + # If user just wanted us to regenerate the manifest, stop now. + if self.manifest_only: + return + + # Otherwise, go ahead and create the source distribution tarball, + # or zipfile, or whatever. + self.make_distribution() + + def get_file_list(self) -> None: + """Figure out the list of files to include in the source + distribution, and put it in 'self.filelist'. This might involve + reading the manifest template (and writing the manifest), or just + reading the manifest, or just using the default file set -- it all + depends on the user's options. + """ + # new behavior when using a template: + # the file list is recalculated every time because + # even if MANIFEST.in or setup.py are not changed + # the user might have added some files in the tree that + # need to be included. + # + # This makes --force the default and only behavior with templates. + template_exists = os.path.isfile(self.template) + if not template_exists and self._manifest_is_not_generated(): + self.read_manifest() + self.filelist.sort() + self.filelist.remove_duplicates() + return + + if not template_exists: + self.warn( + ("manifest template '%s' does not exist " + "(using default file list)") + % self.template + ) + self.filelist.findall() + + if self.use_defaults: + self.add_defaults() + + if template_exists: + self.read_template() + + if self.prune: + self.prune_file_list() + + self.filelist.sort() + self.filelist.remove_duplicates() + self.write_manifest() + + def add_defaults(self) -> None: + """Add all the default files to self.filelist: + - README or README.txt + - setup.py + - tests/test*.py and test/test*.py + - all pure Python modules mentioned in setup script + - all files pointed by package_data (build_py) + - all files defined in data_files. + - all files defined as scripts. + - all C sources listed as part of extensions or C libraries + in the setup script (doesn't catch C headers!) + Warns if (README or README.txt) or setup.py are missing; everything + else is optional. + """ + self._add_defaults_standards() + self._add_defaults_optional() + self._add_defaults_python() + self._add_defaults_data_files() + self._add_defaults_ext() + self._add_defaults_c_libs() + self._add_defaults_scripts() + + @staticmethod + def _cs_path_exists(fspath): + """ + Case-sensitive path existence check + + >>> sdist._cs_path_exists(__file__) + True + >>> sdist._cs_path_exists(__file__.upper()) + False + """ + if not os.path.exists(fspath): + return False + # make absolute so we always have a directory + abspath = os.path.abspath(fspath) + directory, filename = os.path.split(abspath) + return filename in os.listdir(directory) + + def _add_defaults_standards(self): + standards = [self.READMES, self.distribution.script_name] + for fn in standards: + if isinstance(fn, tuple): + alts = fn + got_it = False + for fn in alts: + if self._cs_path_exists(fn): + got_it = True + self.filelist.append(fn) + break + + if not got_it: + self.warn( + "standard file not found: should have one of " + ', '.join(alts) + ) + else: + if self._cs_path_exists(fn): + self.filelist.append(fn) + else: + self.warn(f"standard file '{fn}' not found") + + def _add_defaults_optional(self): + optional = ['tests/test*.py', 'test/test*.py', 'setup.cfg'] + for pattern in optional: + files = filter(os.path.isfile, glob(pattern)) + self.filelist.extend(files) + + def _add_defaults_python(self): + # build_py is used to get: + # - python modules + # - files defined in package_data + build_py = self.get_finalized_command('build_py') + + # getting python files + if self.distribution.has_pure_modules(): + self.filelist.extend(build_py.get_source_files()) + + # getting package_data files + # (computed in build_py.data_files by build_py.finalize_options) + for _pkg, src_dir, _build_dir, filenames in build_py.data_files: + for filename in filenames: + self.filelist.append(os.path.join(src_dir, filename)) + + def _add_defaults_data_files(self): + # getting distribution.data_files + if self.distribution.has_data_files(): + for item in self.distribution.data_files: + if isinstance(item, str): + # plain file + item = convert_path(item) + if os.path.isfile(item): + self.filelist.append(item) + else: + # a (dirname, filenames) tuple + dirname, filenames = item + for f in filenames: + f = convert_path(f) + if os.path.isfile(f): + self.filelist.append(f) + + def _add_defaults_ext(self): + if self.distribution.has_ext_modules(): + build_ext = self.get_finalized_command('build_ext') + self.filelist.extend(build_ext.get_source_files()) + + def _add_defaults_c_libs(self): + if self.distribution.has_c_libraries(): + build_clib = self.get_finalized_command('build_clib') + self.filelist.extend(build_clib.get_source_files()) + + def _add_defaults_scripts(self): + if self.distribution.has_scripts(): + build_scripts = self.get_finalized_command('build_scripts') + self.filelist.extend(build_scripts.get_source_files()) + + def read_template(self) -> None: + """Read and parse manifest template file named by self.template. + + (usually "MANIFEST.in") The parsing and processing is done by + 'self.filelist', which updates itself accordingly. + """ + log.info("reading manifest template '%s'", self.template) + template = TextFile( + self.template, + strip_comments=True, + skip_blanks=True, + join_lines=True, + lstrip_ws=True, + rstrip_ws=True, + collapse_join=True, + ) + + try: + while True: + line = template.readline() + if line is None: # end of file + break + + try: + self.filelist.process_template_line(line) + # the call above can raise a DistutilsTemplateError for + # malformed lines, or a ValueError from the lower-level + # convert_path function + except (DistutilsTemplateError, ValueError) as msg: + self.warn( + f"{template.filename}, line {int(template.current_line)}: {msg}" + ) + finally: + template.close() + + def prune_file_list(self) -> None: + """Prune off branches that might slip into the file list as created + by 'read_template()', but really don't belong there: + * the build tree (typically "build") + * the release tree itself (only an issue if we ran "sdist" + previously with --keep-temp, or it aborted) + * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories + """ + build = self.get_finalized_command('build') + base_dir = self.distribution.get_fullname() + + self.filelist.exclude_pattern(None, prefix=os.fspath(build.build_base)) + self.filelist.exclude_pattern(None, prefix=base_dir) + + if sys.platform == 'win32': + seps = r'/|\\' + else: + seps = '/' + + vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] + vcs_ptrn = r'(^|{})({})({}).*'.format(seps, '|'.join(vcs_dirs), seps) + self.filelist.exclude_pattern(vcs_ptrn, is_regex=True) + + def write_manifest(self) -> None: + """Write the file list in 'self.filelist' (presumably as filled in + by 'add_defaults()' and 'read_template()') to the manifest file + named by 'self.manifest'. + """ + if self._manifest_is_not_generated(): + log.info( + f"not writing to manually maintained manifest file '{self.manifest}'" + ) + return + + content = self.filelist.files[:] + content.insert(0, '# file GENERATED by distutils, do NOT edit') + self.execute( + file_util.write_file, + (self.manifest, content), + f"writing manifest file '{self.manifest}'", + ) + + def _manifest_is_not_generated(self): + # check for special comment used in 3.1.3 and higher + if not os.path.isfile(self.manifest): + return False + + with open(self.manifest, encoding='utf-8') as fp: + first_line = next(fp) + return first_line != '# file GENERATED by distutils, do NOT edit\n' + + def read_manifest(self) -> None: + """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) + with open(self.manifest, encoding='utf-8') as lines: + self.filelist.extend( + # ignore comments and blank lines + filter(None, filterfalse(is_comment, map(str.strip, lines))) + ) + + def make_release_tree(self, base_dir, files) -> None: + """Create the directory tree that will become the source + distribution archive. All directories implied by the filenames in + 'files' are created under 'base_dir', and then we hard link or copy + (if hard linking is unavailable) those files into place. + Essentially, this duplicates the developer's source tree, but in a + directory named after the distribution, containing only the files + to be distributed. + """ + # Create all the directories under 'base_dir' necessary to + # put 'files' there; the 'mkpath()' is just so we don't die + # if the manifest happens to be empty. + self.mkpath(base_dir) + dir_util.create_tree(base_dir, files) + + # And walk over the list of files, either making a hard link (if + # os.link exists) to each one that doesn't already exist in its + # corresponding location under 'base_dir', or copying each file + # that's out-of-date in 'base_dir'. (Usually, all files will be + # out-of-date, because by default we blow away 'base_dir' when + # we're done making the distribution archives.) + + if hasattr(os, 'link'): # can make hard links on this system + link = 'hard' + msg = f"making hard links in {base_dir}..." + else: # nope, have to copy + link = None + msg = f"copying files to {base_dir}..." + + if not files: + log.warning("no files to distribute -- empty manifest?") + else: + log.info(msg) + for file in files: + if not os.path.isfile(file): + log.warning("'%s' not a regular file -- skipping", file) + else: + dest = os.path.join(base_dir, file) + self.copy_file(file, dest, link=link) + + self.distribution.metadata.write_pkg_info(base_dir) + + def make_distribution(self) -> None: + """Create the source distribution(s). First, we create the release + tree with 'make_release_tree()'; then, we create all required + archive files (according to 'self.formats') from the release tree. + Finally, we clean up by blowing away the release tree (unless + 'self.keep_temp' is true). The list of archive files created is + stored so it can be retrieved later by 'get_archive_files()'. + """ + # Don't warn about missing meta-data here -- should be (and is!) + # done elsewhere. + base_dir = self.distribution.get_fullname() + base_name = os.path.join(self.dist_dir, base_dir) + + self.make_release_tree(base_dir, self.filelist.files) + archive_files = [] # remember names of files we create + # tar archive must be created last to avoid overwrite and remove + if 'tar' in self.formats: + self.formats.append(self.formats.pop(self.formats.index('tar'))) + + for fmt in self.formats: + file = self.make_archive( + base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group + ) + archive_files.append(file) + self.distribution.dist_files.append(('sdist', '', file)) + + self.archive_files = archive_files + + if not self.keep_temp: + dir_util.remove_tree(base_dir) + + def get_archive_files(self): + """Return the list of archive files created when the command + was run, or None if the command hasn't run yet. + """ + return self.archive_files + + +def is_comment(line: str) -> bool: + return line.startswith('#') diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c43729b09ea5e5bf9d8c0708e63c69b5114a279 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__init__.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from collections.abc import Iterable +from typing import TypeVar + +_IterableT = TypeVar("_IterableT", bound="Iterable[str]") + + +def consolidate_linker_args(args: _IterableT) -> _IterableT | str: + """ + Ensure the return value is a string for backward compatibility. + + Retain until at least 2025-04-31. See pypa/distutils#246 + """ + + if not all(arg.startswith('-Wl,') for arg in args): + return args + return '-Wl,' + ','.join(arg.removeprefix('-Wl,') for arg in args) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e99d2a59fb4f383d2e5ae3f665ac748b5aa894f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/numpy.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/numpy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e7201209bd6ad9dfbe2a00dcfaad8de014a23b3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/numpy.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/py39.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/py39.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53f8e1023ba7ce506795ee986ba798e980903be0 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/__pycache__/py39.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/numpy.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..73eca7acb103b7c7ca8e7a9f7f2d772a64aa344b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/numpy.py @@ -0,0 +1,2 @@ +# required for older numpy versions on Pythons prior to 3.12; see pypa/setuptools#4876 +from ..compilers.C.base import _default_compilers, compiler_class # noqa: F401 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/py39.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/py39.py new file mode 100644 index 0000000000000000000000000000000000000000..1b436d76586cbcf38164548f3fc849ce1a3ff600 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compat/py39.py @@ -0,0 +1,66 @@ +import functools +import itertools +import platform +import sys + + +def add_ext_suffix_39(vars): + """ + Ensure vars contains 'EXT_SUFFIX'. pypa/distutils#130 + """ + import _imp + + ext_suffix = _imp.extension_suffixes()[0] + vars.update( + EXT_SUFFIX=ext_suffix, + # sysconfig sets SO to match EXT_SUFFIX, so maintain + # that expectation. + # https://github.com/python/cpython/blob/785cc6770588de087d09e89a69110af2542be208/Lib/sysconfig.py#L671-L673 + SO=ext_suffix, + ) + + +needs_ext_suffix = sys.version_info < (3, 10) and platform.system() == 'Windows' +add_ext_suffix = add_ext_suffix_39 if needs_ext_suffix else lambda vars: None + + +# from more_itertools +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) + + +# from more_itertools +def _zip_equal_generator(iterables): + _marker = object() + for combo in itertools.zip_longest(*iterables, fillvalue=_marker): + for val in combo: + if val is _marker: + raise UnequalIterablesError() + yield combo + + +# from more_itertools +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) + + +zip_strict = ( + _zip_equal if sys.version_info < (3, 10) else functools.partial(zip, strict=True) +) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/base.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eccf6fa676204e3ee45afa5bda684d138d260e3b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/base.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/cygwin.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/cygwin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48d211f49d50ac23a081ff9677ea23d7a0470846 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/cygwin.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/errors.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b8ccff669f681dd4effba6946c077d0d60fa85a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/errors.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/msvc.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/msvc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d2f2b534b8eb054503578cc144ccf372d9a323b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/msvc.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/unix.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/unix.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ce6745e50837b626ebf07264d833e85e08b8844 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/unix.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/zos.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/zos.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71859099b53670d6ada788a793aa0d83577d0e42 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/__pycache__/zos.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/base.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ea6b5458ef2b1d0c936cbfd9aaea19f5e41bbea9 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/base.py @@ -0,0 +1,1386 @@ +"""distutils.ccompiler + +Contains Compiler, an abstract base class that defines the interface +for the Distutils compiler abstraction model.""" + +from __future__ import annotations + +import os +import pathlib +import re +import sys +import warnings +from collections.abc import Callable, Iterable, MutableSequence, Sequence +from typing import ( + TYPE_CHECKING, + ClassVar, + Literal, + TypeVar, + Union, + overload, +) + +from more_itertools import always_iterable + +from ..._log import log +from ..._modified import newer_group +from ...dir_util import mkpath +from ...errors import ( + DistutilsModuleError, + DistutilsPlatformError, +) +from ...file_util import move_file +from ...spawn import spawn +from ...util import execute, is_mingw, split_quoted +from .errors import ( + CompileError, + LinkError, + UnknownFileType, +) + +if TYPE_CHECKING: + from typing_extensions import TypeAlias, TypeVarTuple, Unpack + + _Ts = TypeVarTuple("_Ts") + +_Macro: TypeAlias = Union[tuple[str], tuple[str, Union[str, None]]] +_StrPathT = TypeVar("_StrPathT", bound="str | os.PathLike[str]") +_BytesPathT = TypeVar("_BytesPathT", bound="bytes | os.PathLike[bytes]") + + +class Compiler: + """Abstract base class to define the interface that must be implemented + by real compiler classes. Also has some utility methods used by + several compiler classes. + + The basic idea behind a compiler abstraction class is that each + instance can be used for all the compile/link steps in building a + single project. Thus, attributes common to all of those compile and + link steps -- include directories, macros to define, libraries to link + against, etc. -- are attributes of the compiler instance. To allow for + variability in how individual files are treated, most of those + attributes may be varied on a per-compilation or per-link basis. + """ + + # 'compiler_type' is a class attribute that identifies this class. It + # keeps code that wants to know what kind of compiler it's dealing with + # from having to import all possible compiler classes just to do an + # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type' + # should really, really be one of the keys of the 'compiler_class' + # dictionary (see below -- used by the 'new_compiler()' factory + # function) -- authors of new compiler interface classes are + # responsible for updating 'compiler_class'! + compiler_type: ClassVar[str] = None # type: ignore[assignment] + + # XXX things not handled by this compiler abstraction model: + # * client can't provide additional options for a compiler, + # e.g. warning, optimization, debugging flags. Perhaps this + # should be the domain of concrete compiler abstraction classes + # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base + # class should have methods for the common ones. + # * can't completely override the include or library searchg + # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2". + # I'm not sure how widely supported this is even by Unix + # compilers, much less on other platforms. And I'm even less + # sure how useful it is; maybe for cross-compiling, but + # support for that is a ways off. (And anyways, cross + # compilers probably have a dedicated binary with the + # right paths compiled in. I hope.) + # * can't do really freaky things with the library list/library + # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against + # different versions of libfoo.a in different locations. I + # think this is useless without the ability to null out the + # library search path anyways. + + executables: ClassVar[dict] + + # Subclasses that rely on the standard filename generation methods + # implemented below should override these; see the comment near + # those methods ('object_filenames()' et. al.) for details: + src_extensions: ClassVar[list[str] | None] = None + obj_extension: ClassVar[str | None] = None + static_lib_extension: ClassVar[str | None] = None + shared_lib_extension: ClassVar[str | None] = None + static_lib_format: ClassVar[str | None] = None # format string + shared_lib_format: ClassVar[str | None] = None # prob. same as static_lib_format + exe_extension: ClassVar[str | None] = None + + # Default language settings. language_map is used to detect a source + # file or Extension target language, checking source filenames. + # language_order is used to detect the language precedence, when deciding + # what language to use when mixing source types. For example, if some + # extension has two files with ".c" extension, and one with ".cpp", it + # is still linked as c++. + language_map: ClassVar[dict[str, str]] = { + ".c": "c", + ".cc": "c++", + ".cpp": "c++", + ".cxx": "c++", + ".m": "objc", + } + language_order: ClassVar[list[str]] = ["c++", "objc", "c"] + + include_dirs: list[str] = [] + """ + include dirs specific to this compiler class + """ + + library_dirs: list[str] = [] + """ + library dirs specific to this compiler class + """ + + def __init__(self, verbose: bool = False, force: bool = False) -> None: + self.force = force + self.verbose = verbose + + # 'output_dir': a common output directory for object, library, + # shared object, and shared library files + self.output_dir: str | None = None + + # 'macros': a list of macro definitions (or undefinitions). A + # macro definition is a 2-tuple (name, value), where the value is + # either a string or None (no explicit value). A macro + # undefinition is a 1-tuple (name,). + self.macros: list[_Macro] = [] + + # 'include_dirs': a list of directories to search for include files + self.include_dirs = [] + + # 'libraries': a list of libraries to include in any link + # (library names, not filenames: eg. "foo" not "libfoo.a") + self.libraries: list[str] = [] + + # 'library_dirs': a list of directories to search for libraries + self.library_dirs = [] + + # 'runtime_library_dirs': a list of directories to search for + # shared libraries/objects at runtime + self.runtime_library_dirs: list[str] = [] + + # 'objects': a list of object files (or similar, such as explicitly + # named library files) to include on any link + self.objects: list[str] = [] + + for key in self.executables.keys(): + self.set_executable(key, self.executables[key]) + + def set_executables(self, **kwargs: str) -> None: + """Define the executables (and options for them) that will be run + to perform the various stages of compilation. The exact set of + executables that may be specified here depends on the compiler + class (via the 'executables' class attribute), but most will have: + compiler the C/C++ compiler + linker_so linker used to create shared objects and libraries + linker_exe linker used to create binary executables + archiver static library creator + + On platforms with a command-line (Unix, DOS/Windows), each of these + is a string that will be split into executable name and (optional) + list of arguments. (Splitting the string is done similarly to how + Unix shells operate: words are delimited by spaces, but quotes and + backslashes can override this. See + 'distutils.util.split_quoted()'.) + """ + + # Note that some CCompiler implementation classes will define class + # attributes 'cpp', 'cc', etc. with hard-coded executable names; + # this is appropriate when a compiler class is for exactly one + # compiler/OS combination (eg. MSVCCompiler). Other compiler + # classes (UnixCCompiler, in particular) are driven by information + # discovered at run-time, since there are many different ways to do + # basically the same things with Unix C compilers. + + for key in kwargs: + if key not in self.executables: + raise ValueError( + f"unknown executable '{key}' for class {self.__class__.__name__}" + ) + self.set_executable(key, kwargs[key]) + + def set_executable(self, key, value): + if isinstance(value, str): + setattr(self, key, split_quoted(value)) + else: + setattr(self, key, value) + + def _find_macro(self, name): + i = 0 + for defn in self.macros: + if defn[0] == name: + return i + i += 1 + return None + + def _check_macro_definitions(self, definitions): + """Ensure that every element of 'definitions' is valid.""" + for defn in definitions: + self._check_macro_definition(*defn) + + def _check_macro_definition(self, defn): + """ + Raise a TypeError if defn is not valid. + + A valid definition is either a (name, value) 2-tuple or a (name,) tuple. + """ + if not isinstance(defn, tuple) or not self._is_valid_macro(*defn): + raise TypeError( + f"invalid macro definition '{defn}': " + "must be tuple (string,), (string, string), or (string, None)" + ) + + @staticmethod + def _is_valid_macro(name, value=None): + """ + A valid macro is a ``name : str`` and a ``value : str | None``. + + >>> Compiler._is_valid_macro('foo', None) + True + """ + return isinstance(name, str) and isinstance(value, (str, type(None))) + + # -- Bookkeeping methods ------------------------------------------- + + def define_macro(self, name: str, value: str | None = None) -> None: + """Define a preprocessor macro for all compilations driven by this + compiler object. The optional parameter 'value' should be a + string; if it is not supplied, then the macro will be defined + without an explicit value and the exact outcome depends on the + compiler used (XXX true? does ANSI say anything about this?) + """ + # Delete from the list of macro definitions/undefinitions if + # already there (so that this one will take precedence). + i = self._find_macro(name) + if i is not None: + del self.macros[i] + + self.macros.append((name, value)) + + def undefine_macro(self, name: str) -> None: + """Undefine a preprocessor macro for all compilations driven by + this compiler object. If the same macro is defined by + 'define_macro()' and undefined by 'undefine_macro()' the last call + takes precedence (including multiple redefinitions or + undefinitions). If the macro is redefined/undefined on a + per-compilation basis (ie. in the call to 'compile()'), then that + takes precedence. + """ + # Delete from the list of macro definitions/undefinitions if + # already there (so that this one will take precedence). + i = self._find_macro(name) + if i is not None: + del self.macros[i] + + undefn = (name,) + self.macros.append(undefn) + + def add_include_dir(self, dir: str) -> None: + """Add 'dir' to the list of directories that will be searched for + header files. The compiler is instructed to search directories in + the order in which they are supplied by successive calls to + 'add_include_dir()'. + """ + self.include_dirs.append(dir) + + def set_include_dirs(self, dirs: list[str]) -> None: + """Set the list of directories that will be searched to 'dirs' (a + list of strings). Overrides any preceding calls to + 'add_include_dir()'; subsequence calls to 'add_include_dir()' add + to the list passed to 'set_include_dirs()'. This does not affect + any list of standard include directories that the compiler may + search by default. + """ + self.include_dirs = dirs[:] + + def add_library(self, libname: str) -> None: + """Add 'libname' to the list of libraries that will be included in + all links driven by this compiler object. Note that 'libname' + should *not* be the name of a file containing a library, but the + name of the library itself: the actual filename will be inferred by + the linker, the compiler, or the compiler class (depending on the + platform). + + The linker will be instructed to link against libraries in the + order they were supplied to 'add_library()' and/or + 'set_libraries()'. It is perfectly valid to duplicate library + names; the linker will be instructed to link against libraries as + many times as they are mentioned. + """ + self.libraries.append(libname) + + def set_libraries(self, libnames: list[str]) -> None: + """Set the list of libraries to be included in all links driven by + this compiler object to 'libnames' (a list of strings). This does + not affect any standard system libraries that the linker may + include by default. + """ + self.libraries = libnames[:] + + def add_library_dir(self, dir: str) -> None: + """Add 'dir' to the list of directories that will be searched for + libraries specified to 'add_library()' and 'set_libraries()'. The + linker will be instructed to search for libraries in the order they + are supplied to 'add_library_dir()' and/or 'set_library_dirs()'. + """ + self.library_dirs.append(dir) + + def set_library_dirs(self, dirs: list[str]) -> None: + """Set the list of library search directories to 'dirs' (a list of + strings). This does not affect any standard library search path + that the linker may search by default. + """ + self.library_dirs = dirs[:] + + def add_runtime_library_dir(self, dir: str) -> None: + """Add 'dir' to the list of directories that will be searched for + shared libraries at runtime. + """ + self.runtime_library_dirs.append(dir) + + def set_runtime_library_dirs(self, dirs: list[str]) -> None: + """Set the list of directories to search for shared libraries at + runtime to 'dirs' (a list of strings). This does not affect any + standard search path that the runtime linker may search by + default. + """ + self.runtime_library_dirs = dirs[:] + + def add_link_object(self, object: str) -> None: + """Add 'object' to the list of object files (or analogues, such as + explicitly named library files or the output of "resource + compilers") to be included in every link driven by this compiler + object. + """ + self.objects.append(object) + + def set_link_objects(self, objects: list[str]) -> None: + """Set the list of object files (or analogues) to be included in + every link to 'objects'. This does not affect any standard object + files that the linker may include by default (such as system + libraries). + """ + self.objects = objects[:] + + # -- Private utility methods -------------------------------------- + # (here for the convenience of subclasses) + + # Helper method to prep compiler in subclass compile() methods + + def _setup_compile( + self, + outdir: str | None, + macros: list[_Macro] | None, + incdirs: list[str] | tuple[str, ...] | None, + sources, + depends, + extra, + ): + """Process arguments and decide which source files to compile.""" + outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs) + + if extra is None: + extra = [] + + # Get the list of expected output (object) files + objects = self.object_filenames(sources, strip_dir=False, output_dir=outdir) + assert len(objects) == len(sources) + + pp_opts = gen_preprocess_options(macros, incdirs) + + build = {} + for i in range(len(sources)): + src = sources[i] + obj = objects[i] + ext = os.path.splitext(src)[1] + self.mkpath(os.path.dirname(obj)) + build[obj] = (src, ext) + + return macros, objects, extra, pp_opts, build + + def _get_cc_args(self, pp_opts, debug, before): + # works for unixccompiler, cygwinccompiler + cc_args = pp_opts + ['-c'] + if debug: + cc_args[:0] = ['-g'] + if before: + cc_args[:0] = before + return cc_args + + def _fix_compile_args( + self, + output_dir: str | None, + macros: list[_Macro] | None, + include_dirs: list[str] | tuple[str, ...] | None, + ) -> tuple[str, list[_Macro], list[str]]: + """Typecheck and fix-up some of the arguments to the 'compile()' + method, and return fixed-up values. Specifically: if 'output_dir' + is None, replaces it with 'self.output_dir'; ensures that 'macros' + is a list, and augments it with 'self.macros'; ensures that + 'include_dirs' is a list, and augments it with 'self.include_dirs'. + Guarantees that the returned values are of the correct type, + i.e. for 'output_dir' either string or None, and for 'macros' and + 'include_dirs' either list or None. + """ + if output_dir is None: + output_dir = self.output_dir + elif not isinstance(output_dir, str): + raise TypeError("'output_dir' must be a string or None") + + if macros is None: + macros = list(self.macros) + elif isinstance(macros, list): + macros = macros + (self.macros or []) + else: + raise TypeError("'macros' (if supplied) must be a list of tuples") + + if include_dirs is None: + include_dirs = list(self.include_dirs) + elif isinstance(include_dirs, (list, tuple)): + include_dirs = list(include_dirs) + (self.include_dirs or []) + else: + raise TypeError("'include_dirs' (if supplied) must be a list of strings") + + # add include dirs for class + include_dirs += self.__class__.include_dirs + + return output_dir, macros, include_dirs + + def _prep_compile(self, sources, output_dir, depends=None): + """Decide which source files must be recompiled. + + Determine the list of object files corresponding to 'sources', + and figure out which ones really need to be recompiled. + Return a list of all object files and a dictionary telling + which source files can be skipped. + """ + # Get the list of expected output (object) files + objects = self.object_filenames(sources, output_dir=output_dir) + assert len(objects) == len(sources) + + # Return an empty dict for the "which source files can be skipped" + # return value to preserve API compatibility. + return objects, {} + + def _fix_object_args( + self, objects: list[str] | tuple[str, ...], output_dir: str | None + ) -> tuple[list[str], str]: + """Typecheck and fix up some arguments supplied to various methods. + Specifically: ensure that 'objects' is a list; if output_dir is + None, replace with self.output_dir. Return fixed versions of + 'objects' and 'output_dir'. + """ + if not isinstance(objects, (list, tuple)): + raise TypeError("'objects' must be a list or tuple of strings") + objects = list(objects) + + if output_dir is None: + output_dir = self.output_dir + elif not isinstance(output_dir, str): + raise TypeError("'output_dir' must be a string or None") + + return (objects, output_dir) + + def _fix_lib_args( + self, + libraries: list[str] | tuple[str, ...] | None, + library_dirs: list[str] | tuple[str, ...] | None, + runtime_library_dirs: list[str] | tuple[str, ...] | None, + ) -> tuple[list[str], list[str], list[str]]: + """Typecheck and fix up some of the arguments supplied to the + 'link_*' methods. Specifically: ensure that all arguments are + lists, and augment them with their permanent versions + (eg. 'self.libraries' augments 'libraries'). Return a tuple with + fixed versions of all arguments. + """ + if libraries is None: + libraries = list(self.libraries) + elif isinstance(libraries, (list, tuple)): + libraries = list(libraries) + (self.libraries or []) + else: + raise TypeError("'libraries' (if supplied) must be a list of strings") + + if library_dirs is None: + library_dirs = list(self.library_dirs) + elif isinstance(library_dirs, (list, tuple)): + library_dirs = list(library_dirs) + (self.library_dirs or []) + else: + raise TypeError("'library_dirs' (if supplied) must be a list of strings") + + # add library dirs for class + library_dirs += self.__class__.library_dirs + + if runtime_library_dirs is None: + runtime_library_dirs = list(self.runtime_library_dirs) + elif isinstance(runtime_library_dirs, (list, tuple)): + runtime_library_dirs = list(runtime_library_dirs) + ( + self.runtime_library_dirs or [] + ) + else: + raise TypeError( + "'runtime_library_dirs' (if supplied) must be a list of strings" + ) + + return (libraries, library_dirs, runtime_library_dirs) + + def _need_link(self, objects, output_file): + """Return true if we need to relink the files listed in 'objects' + to recreate 'output_file'. + """ + if self.force: + return True + newer = newer_group(objects, output_file) + return newer + + def detect_language(self, sources: str | list[str]) -> str | None: + """Detect the language of a given file, or list of files. Uses + language_map, and language_order to do the job. + """ + if not isinstance(sources, list): + sources = [sources] + lang = None + index = len(self.language_order) + for source in sources: + base, ext = os.path.splitext(source) + extlang = self.language_map.get(ext) + try: + extindex = self.language_order.index(extlang) + if extindex < index: + lang = extlang + index = extindex + except ValueError: + pass + return lang + + # -- Worker methods ------------------------------------------------ + # (must be implemented by subclasses) + + def preprocess( + self, + source: str | os.PathLike[str], + output_file: str | os.PathLike[str] | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + extra_preargs: list[str] | None = None, + extra_postargs: Iterable[str] | None = None, + ): + """Preprocess a single C/C++ source file, named in 'source'. + Output will be written to file named 'output_file', or stdout if + 'output_file' not supplied. 'macros' is a list of macro + definitions as for 'compile()', which will augment the macros set + with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a + list of directory names that will be added to the default list. + + Raises PreprocessError on failure. + """ + pass + + def compile( + self, + sources: Sequence[str | os.PathLike[str]], + output_dir: str | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + depends: list[str] | tuple[str, ...] | None = None, + ) -> list[str]: + """Compile one or more source files. + + 'sources' must be a list of filenames, most likely C/C++ + files, but in reality anything that can be handled by a + particular compiler and compiler class (eg. MSVCCompiler can + handle resource files in 'sources'). Return a list of object + filenames, one per source filename in 'sources'. Depending on + the implementation, not all source files will necessarily be + compiled, but all corresponding object filenames will be + returned. + + If 'output_dir' is given, object files will be put under it, while + retaining their original path component. That is, "foo/bar.c" + normally compiles to "foo/bar.o" (for a Unix implementation); if + 'output_dir' is "build", then it would compile to + "build/foo/bar.o". + + 'macros', if given, must be a list of macro definitions. A macro + definition is either a (name, value) 2-tuple or a (name,) 1-tuple. + The former defines a macro; if the value is None, the macro is + defined without an explicit value. The 1-tuple case undefines a + macro. Later definitions/redefinitions/ undefinitions take + precedence. + + 'include_dirs', if given, must be a list of strings, the + directories to add to the default include file search path for this + compilation only. + + 'debug' is a boolean; if true, the compiler will be instructed to + output debug symbols in (or alongside) the object file(s). + + 'extra_preargs' and 'extra_postargs' are implementation- dependent. + On platforms that have the notion of a command-line (e.g. Unix, + DOS/Windows), they are most likely lists of strings: extra + command-line arguments to prepend/append to the compiler command + line. On other platforms, consult the implementation class + documentation. In any event, they are intended as an escape hatch + for those occasions when the abstract compiler framework doesn't + cut the mustard. + + 'depends', if given, is a list of filenames that all targets + depend on. If a source file is older than any file in + depends, then the source file will be recompiled. This + supports dependency tracking, but only at a coarse + granularity. + + Raises CompileError on failure. + """ + # A concrete compiler class can either override this method + # entirely or implement _compile(). + macros, objects, extra_postargs, pp_opts, build = self._setup_compile( + output_dir, macros, include_dirs, sources, depends, extra_postargs + ) + cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) + + for obj in objects: + try: + src, ext = build[obj] + except KeyError: + continue + self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) + + # Return *all* object filenames, not just the ones we just built. + return objects + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + """Compile 'src' to product 'obj'.""" + # A concrete compiler class that does not override compile() + # should implement _compile(). + pass + + def create_static_lib( + self, + objects: list[str] | tuple[str, ...], + output_libname: str, + output_dir: str | None = None, + debug: bool = False, + target_lang: str | None = None, + ) -> None: + """Link a bunch of stuff together to create a static library file. + The "bunch of stuff" consists of the list of object files supplied + as 'objects', the extra object files supplied to + 'add_link_object()' and/or 'set_link_objects()', the libraries + supplied to 'add_library()' and/or 'set_libraries()', and the + libraries supplied as 'libraries' (if any). + + 'output_libname' should be a library name, not a filename; the + filename will be inferred from the library name. 'output_dir' is + the directory where the library file will be put. + + 'debug' is a boolean; if true, debugging information will be + included in the library (note that on most platforms, it is the + compile step where this matters: the 'debug' flag is included here + just for consistency). + + 'target_lang' is the target language for which the given objects + are being compiled. This allows specific linkage time treatment of + certain languages. + + Raises LibError on failure. + """ + pass + + # values for target_desc parameter in link() + SHARED_OBJECT = "shared_object" + SHARED_LIBRARY = "shared_library" + EXECUTABLE = "executable" + + def link( + self, + target_desc: str, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | os.PathLike[str] | None = None, + target_lang: str | None = None, + ): + """Link a bunch of stuff together to create an executable or + shared library file. + + The "bunch of stuff" consists of the list of object files supplied + as 'objects'. 'output_filename' should be a filename. If + 'output_dir' is supplied, 'output_filename' is relative to it + (i.e. 'output_filename' can provide directory components if + needed). + + 'libraries' is a list of libraries to link against. These are + library names, not filenames, since they're translated into + filenames in a platform-specific way (eg. "foo" becomes "libfoo.a" + on Unix and "foo.lib" on DOS/Windows). However, they can include a + directory component, which means the linker will look in that + specific directory rather than searching all the normal locations. + + 'library_dirs', if supplied, should be a list of directories to + search for libraries that were specified as bare library names + (ie. no directory component). These are on top of the system + default and those supplied to 'add_library_dir()' and/or + 'set_library_dirs()'. 'runtime_library_dirs' is a list of + directories that will be embedded into the shared library and used + to search for other shared libraries that *it* depends on at + run-time. (This may only be relevant on Unix.) + + 'export_symbols' is a list of symbols that the shared library will + export. (This appears to be relevant only on Windows.) + + 'debug' is as for 'compile()' and 'create_static_lib()', with the + slight distinction that it actually matters on most platforms (as + opposed to 'create_static_lib()', which includes a 'debug' flag + mostly for form's sake). + + 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except + of course that they supply command-line arguments for the + particular linker being used). + + 'target_lang' is the target language for which the given objects + are being compiled. This allows specific linkage time treatment of + certain languages. + + Raises LinkError on failure. + """ + raise NotImplementedError + + # Old 'link_*()' methods, rewritten to use the new 'link()' method. + + def link_shared_lib( + self, + objects: list[str] | tuple[str, ...], + output_libname: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | os.PathLike[str] | None = None, + target_lang: str | None = None, + ): + self.link( + Compiler.SHARED_LIBRARY, + objects, + self.library_filename(output_libname, lib_type='shared'), + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols, + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) + + def link_shared_object( + self, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | os.PathLike[str] | None = None, + target_lang: str | None = None, + ): + self.link( + Compiler.SHARED_OBJECT, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols, + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) + + def link_executable( + self, + objects: list[str] | tuple[str, ...], + output_progname: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + target_lang: str | None = None, + ): + self.link( + Compiler.EXECUTABLE, + objects, + self.executable_filename(output_progname), + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + None, + debug, + extra_preargs, + extra_postargs, + None, + target_lang, + ) + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function; there is + # no appropriate default implementation so subclasses should + # implement all of these. + + def library_dir_option(self, dir: str) -> str: + """Return the compiler option to add 'dir' to the list of + directories searched for libraries. + """ + raise NotImplementedError + + def runtime_library_dir_option(self, dir: str) -> str: + """Return the compiler option to add 'dir' to the list of + directories searched for runtime libraries. + """ + raise NotImplementedError + + def library_option(self, lib: str) -> str: + """Return the compiler option to add 'lib' to the list of libraries + linked into the shared library or executable. + """ + raise NotImplementedError + + def has_function( # noqa: C901 + self, + funcname: str, + includes: Iterable[str] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + ) -> bool: + """Return a boolean indicating whether funcname is provided as + a symbol on the current platform. The optional arguments can + be used to augment the compilation environment. + + The libraries argument is a list of flags to be passed to the + linker to make additional symbol definitions available for + linking. + + The includes and include_dirs arguments are deprecated. + Usually, supplying include files with function declarations + will cause function detection to fail even in cases where the + symbol is available for linking. + + """ + # this can't be included at module scope because it tries to + # import math which might not be available at that point - maybe + # the necessary logic should just be inlined? + import tempfile + + if includes is None: + includes = [] + else: + warnings.warn("includes is deprecated", DeprecationWarning) + if include_dirs is None: + include_dirs = [] + else: + warnings.warn("include_dirs is deprecated", DeprecationWarning) + if libraries is None: + libraries = [] + if library_dirs is None: + library_dirs = [] + fd, fname = tempfile.mkstemp(".c", funcname, text=True) + with os.fdopen(fd, "w", encoding='utf-8') as f: + for incl in includes: + f.write(f"""#include "{incl}"\n""") + if not includes: + # Use "char func(void);" as the prototype to follow + # what autoconf does. This prototype does not match + # any well-known function the compiler might recognize + # as a builtin, so this ends up as a true link test. + # Without a fake prototype, the test would need to + # know the exact argument types, and the has_function + # interface does not provide that level of information. + f.write( + f"""\ +#ifdef __cplusplus +extern "C" +#endif +char {funcname}(void); +""" + ) + f.write( + f"""\ +int main (int argc, char **argv) {{ + {funcname}(); + return 0; +}} +""" + ) + + try: + objects = self.compile([fname], include_dirs=include_dirs) + except CompileError: + return False + finally: + os.remove(fname) + + try: + self.link_executable( + objects, "a.out", libraries=libraries, library_dirs=library_dirs + ) + except (LinkError, TypeError): + return False + else: + os.remove( + self.executable_filename("a.out", output_dir=self.output_dir or '') + ) + finally: + for fn in objects: + os.remove(fn) + return True + + def find_library_file( + self, dirs: Iterable[str], lib: str, debug: bool = False + ) -> str | None: + """Search the specified list of directories for a static or shared + library file 'lib' and return the full path to that file. If + 'debug' true, look for a debugging version (if that makes sense on + the current platform). Return None if 'lib' wasn't found in any of + the specified directories. + """ + raise NotImplementedError + + # -- Filename generation methods ----------------------------------- + + # The default implementation of the filename generating methods are + # prejudiced towards the Unix/DOS/Windows view of the world: + # * object files are named by replacing the source file extension + # (eg. .c/.cpp -> .o/.obj) + # * library files (shared or static) are named by plugging the + # library name and extension into a format string, eg. + # "lib%s.%s" % (lib_name, ".a") for Unix static libraries + # * executables are named by appending an extension (possibly + # empty) to the program name: eg. progname + ".exe" for + # Windows + # + # To reduce redundant code, these methods expect to find + # several attributes in the current object (presumably defined + # as class attributes): + # * src_extensions - + # list of C/C++ source file extensions, eg. ['.c', '.cpp'] + # * obj_extension - + # object file extension, eg. '.o' or '.obj' + # * static_lib_extension - + # extension for static library files, eg. '.a' or '.lib' + # * shared_lib_extension - + # extension for shared library/object files, eg. '.so', '.dll' + # * static_lib_format - + # format string for generating static library filenames, + # eg. 'lib%s.%s' or '%s.%s' + # * shared_lib_format + # format string for generating shared library filenames + # (probably same as static_lib_format, since the extension + # is one of the intended parameters to the format string) + # * exe_extension - + # extension for executable files, eg. '' or '.exe' + + def object_filenames( + self, + source_filenames: Iterable[str | os.PathLike[str]], + strip_dir: bool = False, + output_dir: str | os.PathLike[str] | None = '', + ) -> list[str]: + if output_dir is None: + output_dir = '' + return list( + self._make_out_path(output_dir, strip_dir, src_name) + for src_name in source_filenames + ) + + @property + def out_extensions(self): + return dict.fromkeys(self.src_extensions, self.obj_extension) + + def _make_out_path(self, output_dir, strip_dir, src_name): + return self._make_out_path_exts( + output_dir, strip_dir, src_name, self.out_extensions + ) + + @classmethod + def _make_out_path_exts(cls, output_dir, strip_dir, src_name, extensions): + r""" + >>> exts = {'.c': '.o'} + >>> Compiler._make_out_path_exts('.', False, '/foo/bar.c', exts).replace('\\', '/') + './foo/bar.o' + >>> Compiler._make_out_path_exts('.', True, '/foo/bar.c', exts).replace('\\', '/') + './bar.o' + """ + src = pathlib.PurePath(src_name) + # Ensure base is relative to honor output_dir (python/cpython#37775). + base = cls._make_relative(src) + try: + new_ext = extensions[src.suffix] + except LookupError: + raise UnknownFileType(f"unknown file type '{src.suffix}' (from '{src}')") + if strip_dir: + base = pathlib.PurePath(base.name) + return os.path.join(output_dir, base.with_suffix(new_ext)) + + @staticmethod + def _make_relative(base: pathlib.Path): + return base.relative_to(base.anchor) + + @overload + def shared_object_filename( + self, + basename: str, + strip_dir: Literal[False] = False, + output_dir: str | os.PathLike[str] = "", + ) -> str: ... + @overload + def shared_object_filename( + self, + basename: str | os.PathLike[str], + strip_dir: Literal[True], + output_dir: str | os.PathLike[str] = "", + ) -> str: ... + def shared_object_filename( + self, + basename: str | os.PathLike[str], + strip_dir: bool = False, + output_dir: str | os.PathLike[str] = '', + ) -> str: + assert output_dir is not None + if strip_dir: + basename = os.path.basename(basename) + return os.path.join(output_dir, basename + self.shared_lib_extension) + + @overload + def executable_filename( + self, + basename: str, + strip_dir: Literal[False] = False, + output_dir: str | os.PathLike[str] = "", + ) -> str: ... + @overload + def executable_filename( + self, + basename: str | os.PathLike[str], + strip_dir: Literal[True], + output_dir: str | os.PathLike[str] = "", + ) -> str: ... + def executable_filename( + self, + basename: str | os.PathLike[str], + strip_dir: bool = False, + output_dir: str | os.PathLike[str] = '', + ) -> str: + assert output_dir is not None + if strip_dir: + basename = os.path.basename(basename) + return os.path.join(output_dir, basename + (self.exe_extension or '')) + + def library_filename( + self, + libname: str, + lib_type: str = "static", + strip_dir: bool = False, + output_dir: str | os.PathLike[str] = "", # or 'shared' + ): + assert output_dir is not None + expected = '"static", "shared", "dylib", "xcode_stub"' + if lib_type not in eval(expected): + raise ValueError(f"'lib_type' must be {expected}") + fmt = getattr(self, lib_type + "_lib_format") + ext = getattr(self, lib_type + "_lib_extension") + + dir, base = os.path.split(libname) + filename = fmt % (base, ext) + if strip_dir: + dir = '' + + return os.path.join(output_dir, dir, filename) + + # -- Utility methods ----------------------------------------------- + + def announce(self, msg: object, level: int = 1) -> None: + log.debug(msg) + + def debug_print(self, msg: object) -> None: + from distutils.debug import DEBUG + + if DEBUG: + print(msg) + + def warn(self, msg: object) -> None: + sys.stderr.write(f"warning: {msg}\n") + + def execute( + self, + func: Callable[[Unpack[_Ts]], object], + args: tuple[Unpack[_Ts]], + msg: object = None, + level: int = 1, + ) -> None: + execute(func, args, msg) + + def spawn( + self, cmd: MutableSequence[bytes | str | os.PathLike[str]], **kwargs + ) -> None: + spawn(cmd, **kwargs) + + @overload + def move_file( + self, src: str | os.PathLike[str], dst: _StrPathT + ) -> _StrPathT | str: ... + @overload + def move_file( + self, src: bytes | os.PathLike[bytes], dst: _BytesPathT + ) -> _BytesPathT | bytes: ... + def move_file( + self, + src: str | os.PathLike[str] | bytes | os.PathLike[bytes], + dst: str | os.PathLike[str] | bytes | os.PathLike[bytes], + ) -> str | os.PathLike[str] | bytes | os.PathLike[bytes]: + return move_file(src, dst) + + def mkpath(self, name, mode=0o777): + mkpath(name, mode) + + +# Map a sys.platform/os.name ('posix', 'nt') to the default compiler +# type for that platform. Keys are interpreted as re match +# patterns. Order is important; platform mappings are preferred over +# OS names. +_default_compilers = ( + # Platform string mappings + # on a cygwin built python we can use gcc like an ordinary UNIXish + # compiler + ('cygwin.*', 'unix'), + ('zos', 'zos'), + # OS name mappings + ('posix', 'unix'), + ('nt', 'msvc'), +) + + +def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str: + """Determine the default compiler to use for the given platform. + + osname should be one of the standard Python OS names (i.e. the + ones returned by os.name) and platform the common value + returned by sys.platform for the platform in question. + + The default values are os.name and sys.platform in case the + parameters are not given. + """ + if osname is None: + osname = os.name + if platform is None: + platform = sys.platform + # Mingw is a special case where sys.platform is 'win32' but we + # want to use the 'mingw32' compiler, so check it first + if is_mingw(): + return 'mingw32' + for pattern, compiler in _default_compilers: + if ( + re.match(pattern, platform) is not None + or re.match(pattern, osname) is not None + ): + return compiler + # Default to Unix compiler + return 'unix' + + +# Map compiler types to (module_name, class_name) pairs -- ie. where to +# find the code that implements an interface to this compiler. (The module +# is assumed to be in the 'distutils' package.) +compiler_class = { + 'unix': ('unixccompiler', 'UnixCCompiler', "standard UNIX-style compiler"), + 'msvc': ('_msvccompiler', 'MSVCCompiler', "Microsoft Visual C++"), + 'cygwin': ( + 'cygwinccompiler', + 'CygwinCCompiler', + "Cygwin port of GNU C Compiler for Win32", + ), + 'mingw32': ( + 'cygwinccompiler', + 'Mingw32CCompiler', + "Mingw32 port of GNU C Compiler for Win32", + ), + 'bcpp': ('bcppcompiler', 'BCPPCompiler', "Borland C++ Compiler"), + 'zos': ('zosccompiler', 'zOSCCompiler', 'IBM XL C/C++ Compilers'), +} + + +def show_compilers() -> None: + """Print list of available compilers (used by the "--help-compiler" + options to "build", "build_ext", "build_clib"). + """ + # XXX this "knows" that the compiler option it's describing is + # "--compiler", which just happens to be the case for the three + # commands that use it. + from distutils.fancy_getopt import FancyGetopt + + compilers = sorted( + ("compiler=" + compiler, None, compiler_class[compiler][2]) + for compiler in compiler_class.keys() + ) + pretty_printer = FancyGetopt(compilers) + pretty_printer.print_help("List of available compilers:") + + +def new_compiler( + plat: str | None = None, + compiler: str | None = None, + verbose: bool = False, + force: bool = False, +) -> Compiler: + """Generate an instance of some CCompiler subclass for the supplied + platform/compiler combination. 'plat' defaults to 'os.name' + (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler + for that platform. Currently only 'posix' and 'nt' are supported, and + the default compilers are "traditional Unix interface" (UnixCCompiler + class) and Visual C++ (MSVCCompiler class). Note that it's perfectly + possible to ask for a Unix compiler object under Windows, and a + Microsoft compiler object under Unix -- if you supply a value for + 'compiler', 'plat' is ignored. + """ + if plat is None: + plat = os.name + + try: + if compiler is None: + compiler = get_default_compiler(plat) + + (module_name, class_name, long_description) = compiler_class[compiler] + except KeyError: + msg = f"don't know how to compile C/C++ code on platform '{plat}'" + if compiler is not None: + msg = msg + f" with '{compiler}' compiler" + raise DistutilsPlatformError(msg) + + try: + module_name = "distutils." + module_name + __import__(module_name) + module = sys.modules[module_name] + klass = vars(module)[class_name] + except ImportError: + raise DistutilsModuleError( + f"can't compile C/C++ code: unable to load module '{module_name}'" + ) + except KeyError: + raise DistutilsModuleError( + f"can't compile C/C++ code: unable to find class '{class_name}' " + f"in module '{module_name}'" + ) + + # XXX The None is necessary to preserve backwards compatibility + # with classes that expect verbose to be the first positional + # argument. + return klass(None, force=force) + + +def gen_preprocess_options( + macros: Iterable[_Macro], include_dirs: Iterable[str] +) -> list[str]: + """Generate C pre-processor options (-D, -U, -I) as used by at least + two types of compilers: the typical Unix compiler and Visual C++. + 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,) + means undefine (-U) macro 'name', and (name,value) means define (-D) + macro 'name' to 'value'. 'include_dirs' is just a list of directory + names to be added to the header file search path (-I). Returns a list + of command-line options suitable for either Unix compilers or Visual + C++. + """ + # XXX it would be nice (mainly aesthetic, and so we don't generate + # stupid-looking command lines) to go over 'macros' and eliminate + # redundant definitions/undefinitions (ie. ensure that only the + # latest mention of a particular macro winds up on the command + # line). I don't think it's essential, though, since most (all?) + # Unix C compilers only pay attention to the latest -D or -U + # mention of a macro on their command line. Similar situation for + # 'include_dirs'. I'm punting on both for now. Anyways, weeding out + # redundancies like this should probably be the province of + # CCompiler, since the data structures used are inherited from it + # and therefore common to all CCompiler classes. + pp_opts = [] + for macro in macros: + if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2): + raise TypeError( + f"bad macro definition '{macro}': " + "each element of 'macros' list must be a 1- or 2-tuple" + ) + + if len(macro) == 1: # undefine this macro + pp_opts.append(f"-U{macro[0]}") + elif len(macro) == 2: + if macro[1] is None: # define with no explicit value + pp_opts.append(f"-D{macro[0]}") + else: + # XXX *don't* need to be clever about quoting the + # macro value here, because we're going to avoid the + # shell at all costs when we spawn the command! + pp_opts.append("-D{}={}".format(*macro)) + + pp_opts.extend(f"-I{dir}" for dir in include_dirs) + return pp_opts + + +def gen_lib_options( + compiler: Compiler, + library_dirs: Iterable[str], + runtime_library_dirs: Iterable[str], + libraries: Iterable[str], +) -> list[str]: + """Generate linker options for searching library directories and + linking with specific libraries. 'libraries' and 'library_dirs' are, + respectively, lists of library names (not filenames!) and search + directories. Returns a list of command-line options suitable for use + with some compiler (depending on the two format strings passed in). + """ + lib_opts = [compiler.library_dir_option(dir) for dir in library_dirs] + + for dir in runtime_library_dirs: + lib_opts.extend(always_iterable(compiler.runtime_library_dir_option(dir))) + + # XXX it's important that we *not* remove redundant library mentions! + # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to + # resolve all symbols. I just hope we never have to say "-lfoo obj.o + # -lbar" to get things to work -- that's certainly a possibility, but a + # pretty nasty way to arrange your C code. + + for lib in libraries: + (lib_dir, lib_name) = os.path.split(lib) + if lib_dir: + lib_file = compiler.find_library_file([lib_dir], lib_name) + if lib_file: + lib_opts.append(lib_file) + else: + compiler.warn( + f"no library file corresponding to '{lib}' found (skipping)" + ) + else: + lib_opts.append(compiler.library_option(lib)) + return lib_opts diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/cygwin.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/cygwin.py new file mode 100644 index 0000000000000000000000000000000000000000..f349e9decd083ad60a9b9d1181b57e1bbcce2c98 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/cygwin.py @@ -0,0 +1,340 @@ +"""distutils.cygwinccompiler + +Provides the CygwinCCompiler class, a subclass of UnixCCompiler that +handles the Cygwin port of the GNU C compiler to Windows. It also contains +the Mingw32CCompiler class which handles the mingw32 port of GCC (same as +cygwin in no-cygwin mode). +""" + +import copy +import os +import pathlib +import shlex +import sys +import warnings +from subprocess import check_output + +from ...errors import ( + DistutilsExecError, + DistutilsPlatformError, +) +from ...file_util import write_file +from ...sysconfig import get_config_vars +from ...version import LooseVersion, suppress_known_deprecation +from . import unix +from .errors import ( + CompileError, + Error, +) + + +def get_msvcr(): + """No longer needed, but kept for backward compatibility.""" + return [] + + +_runtime_library_dirs_msg = ( + "Unable to set runtime library search path on Windows, " + "usually indicated by `runtime_library_dirs` parameter to Extension" +) + + +class Compiler(unix.Compiler): + """Handles the Cygwin port of the GNU C compiler to Windows.""" + + compiler_type = 'cygwin' + obj_extension = ".o" + static_lib_extension = ".a" + shared_lib_extension = ".dll.a" + dylib_lib_extension = ".dll" + static_lib_format = "lib%s%s" + shared_lib_format = "lib%s%s" + dylib_lib_format = "cyg%s%s" + exe_extension = ".exe" + + def __init__(self, verbose=False, force=False): + super().__init__(verbose, force=force) + + status, details = check_config_h() + self.debug_print(f"Python's GCC status: {status} (details: {details})") + if status is not CONFIG_H_OK: + self.warn( + "Python's pyconfig.h doesn't seem to support your compiler. " + f"Reason: {details}. " + "Compiling may fail because of undefined preprocessor macros." + ) + + self.cc, self.cxx = get_config_vars('CC', 'CXX') + + # Override 'CC' and 'CXX' environment variables for + # building using MINGW compiler for MSVC python. + self.cc = os.environ.get('CC', self.cc or 'gcc') + self.cxx = os.environ.get('CXX', self.cxx or 'g++') + + self.linker_dll = self.cc + self.linker_dll_cxx = self.cxx + shared_option = "-shared" + + self.set_executables( + compiler=f'{self.cc} -mcygwin -O -Wall', + compiler_so=f'{self.cc} -mcygwin -mdll -O -Wall', + compiler_cxx=f'{self.cxx} -mcygwin -O -Wall', + compiler_so_cxx=f'{self.cxx} -mcygwin -mdll -O -Wall', + linker_exe=f'{self.cc} -mcygwin', + linker_so=f'{self.linker_dll} -mcygwin {shared_option}', + linker_exe_cxx=f'{self.cxx} -mcygwin', + linker_so_cxx=f'{self.linker_dll_cxx} -mcygwin {shared_option}', + ) + + self.dll_libraries = get_msvcr() + + @property + def gcc_version(self): + # Older numpy depended on this existing to check for ancient + # gcc versions. This doesn't make much sense with clang etc so + # just hardcode to something recent. + # https://github.com/numpy/numpy/pull/20333 + warnings.warn( + "gcc_version attribute of CygwinCCompiler is deprecated. " + "Instead of returning actual gcc version a fixed value 11.2.0 is returned.", + DeprecationWarning, + stacklevel=2, + ) + with suppress_known_deprecation(): + return LooseVersion("11.2.0") + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + """Compiles the source by spawning GCC and windres if needed.""" + if ext in ('.rc', '.res'): + # gcc needs '.res' and '.rc' compiled to object files !!! + try: + self.spawn(["windres", "-i", src, "-o", obj]) + except DistutilsExecError as msg: + raise CompileError(msg) + else: # for other files use the C-compiler + try: + if self.detect_language(src) == 'c++': + self.spawn( + self.compiler_so_cxx + + cc_args + + [src, '-o', obj] + + extra_postargs + ) + else: + self.spawn( + self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs + ) + except DistutilsExecError as msg: + raise CompileError(msg) + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + """Link the objects.""" + # use separate copies, so we can modify the lists + extra_preargs = copy.copy(extra_preargs or []) + libraries = copy.copy(libraries or []) + objects = copy.copy(objects or []) + + if runtime_library_dirs: + self.warn(_runtime_library_dirs_msg) + + # Additional libraries + libraries.extend(self.dll_libraries) + + # handle export symbols by creating a def-file + # with executables this only works with gcc/ld as linker + if (export_symbols is not None) and ( + target_desc != self.EXECUTABLE or self.linker_dll == "gcc" + ): + # (The linker doesn't do anything if output is up-to-date. + # So it would probably better to check if we really need this, + # but for this we had to insert some unchanged parts of + # UnixCCompiler, and this is not what we want.) + + # we want to put some files in the same directory as the + # object files are, build_temp doesn't help much + # where are the object files + temp_dir = os.path.dirname(objects[0]) + # name of dll to give the helper files the same base name + (dll_name, dll_extension) = os.path.splitext( + os.path.basename(output_filename) + ) + + # generate the filenames for these files + def_file = os.path.join(temp_dir, dll_name + ".def") + + # Generate .def file + contents = [f"LIBRARY {os.path.basename(output_filename)}", "EXPORTS"] + contents.extend(export_symbols) + self.execute(write_file, (def_file, contents), f"writing {def_file}") + + # next add options for def-file + + # for gcc/ld the def-file is specified as any object files + objects.append(def_file) + + # end: if ((export_symbols is not None) and + # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")): + + # who wants symbols and a many times larger output file + # should explicitly switch the debug mode on + # otherwise we let ld strip the output file + # (On my machine: 10KiB < stripped_file < ??100KiB + # unstripped_file = stripped_file + XXX KiB + # ( XXX=254 for a typical python extension)) + if not debug: + extra_preargs.append("-s") + + super().link( + target_desc, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + None, # export_symbols, we do this in our def-file + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) + + def runtime_library_dir_option(self, dir): + # cygwin doesn't support rpath. While in theory we could error + # out like MSVC does, code might expect it to work like on Unix, so + # just warn and hope for the best. + self.warn(_runtime_library_dirs_msg) + return [] + + # -- Miscellaneous methods ----------------------------------------- + + def _make_out_path(self, output_dir, strip_dir, src_name): + # use normcase to make sure '.rc' is really '.rc' and not '.RC' + norm_src_name = os.path.normcase(src_name) + return super()._make_out_path(output_dir, strip_dir, norm_src_name) + + @property + def out_extensions(self): + """ + Add support for rc and res files. + """ + return { + **super().out_extensions, + **{ext: ext + self.obj_extension for ext in ('.res', '.rc')}, + } + + +# the same as cygwin plus some additional parameters +class MinGW32Compiler(Compiler): + """Handles the Mingw32 port of the GNU C compiler to Windows.""" + + compiler_type = 'mingw32' + + def __init__(self, verbose=False, force=False): + super().__init__(verbose, force) + + shared_option = "-shared" + + if is_cygwincc(self.cc): + raise Error('Cygwin gcc cannot be used with --compiler=mingw32') + + self.set_executables( + compiler=f'{self.cc} -O -Wall', + compiler_so=f'{self.cc} -shared -O -Wall', + compiler_so_cxx=f'{self.cxx} -shared -O -Wall', + compiler_cxx=f'{self.cxx} -O -Wall', + linker_exe=f'{self.cc}', + linker_so=f'{self.linker_dll} {shared_option}', + linker_exe_cxx=f'{self.cxx}', + linker_so_cxx=f'{self.linker_dll_cxx} {shared_option}', + ) + + def runtime_library_dir_option(self, dir): + raise DistutilsPlatformError(_runtime_library_dirs_msg) + + +# Because these compilers aren't configured in Python's pyconfig.h file by +# default, we should at least warn the user if he is using an unmodified +# version. + +CONFIG_H_OK = "ok" +CONFIG_H_NOTOK = "not ok" +CONFIG_H_UNCERTAIN = "uncertain" + + +def check_config_h(): + """Check if the current Python installation appears amenable to building + extensions with GCC. + + Returns a tuple (status, details), where 'status' is one of the following + constants: + + - CONFIG_H_OK: all is well, go ahead and compile + - CONFIG_H_NOTOK: doesn't look good + - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h + + 'details' is a human-readable string explaining the situation. + + Note there are two ways to conclude "OK": either 'sys.version' contains + the string "GCC" (implying that this Python was built with GCC), or the + installed "pyconfig.h" contains the string "__GNUC__". + """ + + # XXX since this function also checks sys.version, it's not strictly a + # "pyconfig.h" check -- should probably be renamed... + + from distutils import sysconfig + + # if sys.version contains GCC then python was compiled with GCC, and the + # pyconfig.h file should be OK + if "GCC" in sys.version: + return CONFIG_H_OK, "sys.version mentions 'GCC'" + + # Clang would also work + if "Clang" in sys.version: + return CONFIG_H_OK, "sys.version mentions 'Clang'" + + # let's see if __GNUC__ is mentioned in python.h + fn = sysconfig.get_config_h_filename() + try: + config_h = pathlib.Path(fn).read_text(encoding='utf-8') + except OSError as exc: + return (CONFIG_H_UNCERTAIN, f"couldn't read '{fn}': {exc.strerror}") + else: + substring = '__GNUC__' + if substring in config_h: + code = CONFIG_H_OK + mention_inflected = 'mentions' + else: + code = CONFIG_H_NOTOK + mention_inflected = 'does not mention' + return code, f"{fn!r} {mention_inflected} {substring!r}" + + +def is_cygwincc(cc): + """Try to determine if the compiler that would be used is from cygwin.""" + out_string = check_output(shlex.split(cc) + ['-dumpmachine']) + return out_string.strip().endswith(b'cygwin') + + +get_versions = None +""" +A stand-in for the previous get_versions() function to prevent failures +when monkeypatched. See pypa/setuptools#2969. +""" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/errors.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..01328592b2dad80f4d16c55cd9db9829b3c650f1 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/errors.py @@ -0,0 +1,24 @@ +class Error(Exception): + """Some compile/link operation failed.""" + + +class PreprocessError(Error): + """Failure to preprocess one or more C/C++ files.""" + + +class CompileError(Error): + """Failure to compile one or more C/C++ source files.""" + + +class LibError(Error): + """Failure to create a static library from one or more C/C++ object + files.""" + + +class LinkError(Error): + """Failure to link one or more C/C++ object files into an executable + or shared library file.""" + + +class UnknownFileType(Error): + """Attempt to process an unknown file type.""" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/msvc.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/msvc.py new file mode 100644 index 0000000000000000000000000000000000000000..1f50fa50880e02ea7adf64e94a234af25f8284c7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/msvc.py @@ -0,0 +1,614 @@ +"""distutils._msvccompiler + +Contains MSVCCompiler, an implementation of the abstract CCompiler class +for Microsoft Visual Studio 2015. + +This module requires VS 2015 or later. +""" + +# Written by Perry Stoll +# hacked by Robin Becker and Thomas Heller to do a better job of +# finding DevStudio (through the registry) +# ported to VS 2005 and VS 2008 by Christian Heimes +# ported to VS 2015 by Steve Dower +from __future__ import annotations + +import contextlib +import os +import subprocess +import unittest.mock as mock +import warnings +from collections.abc import Iterable + +with contextlib.suppress(ImportError): + import winreg + +from itertools import count + +from ..._log import log +from ...errors import ( + DistutilsExecError, + DistutilsPlatformError, +) +from ...util import get_host_platform, get_platform +from . import base +from .base import gen_lib_options +from .errors import ( + CompileError, + LibError, + LinkError, +) + + +def _find_vc2015(): + try: + key = winreg.OpenKeyEx( + winreg.HKEY_LOCAL_MACHINE, + r"Software\Microsoft\VisualStudio\SxS\VC7", + access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY, + ) + except OSError: + log.debug("Visual C++ is not registered") + return None, None + + best_version = 0 + best_dir = None + with key: + for i in count(): + try: + v, vc_dir, vt = winreg.EnumValue(key, i) + except OSError: + break + if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir): + try: + version = int(float(v)) + except (ValueError, TypeError): + continue + if version >= 14 and version > best_version: + best_version, best_dir = version, vc_dir + return best_version, best_dir + + +def _find_vc2017(): + """Returns "15, path" based on the result of invoking vswhere.exe + If no install is found, returns "None, None" + + The version is returned to avoid unnecessarily changing the function + result. It may be ignored when the path is not None. + + If vswhere.exe is not available, by definition, VS 2017 is not + installed. + """ + root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles") + if not root: + return None, None + + variant = 'arm64' if get_platform() == 'win-arm64' else 'x86.x64' + suitable_components = ( + f"Microsoft.VisualStudio.Component.VC.Tools.{variant}", + "Microsoft.VisualStudio.Workload.WDExpress", + ) + + for component in suitable_components: + # Workaround for `-requiresAny` (only available on VS 2017 > 15.6) + with contextlib.suppress( + subprocess.CalledProcessError, OSError, UnicodeDecodeError + ): + path = ( + subprocess.check_output([ + os.path.join( + root, "Microsoft Visual Studio", "Installer", "vswhere.exe" + ), + "-latest", + "-prerelease", + "-requires", + component, + "-property", + "installationPath", + "-products", + "*", + ]) + .decode(encoding="mbcs", errors="strict") + .strip() + ) + + path = os.path.join(path, "VC", "Auxiliary", "Build") + if os.path.isdir(path): + return 15, path + + return None, None # no suitable component found + + +PLAT_SPEC_TO_RUNTIME = { + 'x86': 'x86', + 'x86_amd64': 'x64', + 'x86_arm': 'arm', + 'x86_arm64': 'arm64', +} + + +def _find_vcvarsall(plat_spec): + # bpo-38597: Removed vcruntime return value + _, best_dir = _find_vc2017() + + if not best_dir: + best_version, best_dir = _find_vc2015() + + if not best_dir: + log.debug("No suitable Visual C++ version found") + return None, None + + vcvarsall = os.path.join(best_dir, "vcvarsall.bat") + if not os.path.isfile(vcvarsall): + log.debug("%s cannot be found", vcvarsall) + return None, None + + return vcvarsall, None + + +def _get_vc_env(plat_spec): + if os.getenv("DISTUTILS_USE_SDK"): + return {key.lower(): value for key, value in os.environ.items()} + + vcvarsall, _ = _find_vcvarsall(plat_spec) + if not vcvarsall: + raise DistutilsPlatformError( + 'Microsoft Visual C++ 14.0 or greater is required. ' + 'Get it with "Microsoft C++ Build Tools": ' + 'https://visualstudio.microsoft.com/visual-cpp-build-tools/' + ) + + try: + out = subprocess.check_output( + f'cmd /u /c "{vcvarsall}" {plat_spec} && set', + stderr=subprocess.STDOUT, + ).decode('utf-16le', errors='replace') + except subprocess.CalledProcessError as exc: + log.error(exc.output) + raise DistutilsPlatformError(f"Error executing {exc.cmd}") + + env = { + key.lower(): value + for key, _, value in (line.partition('=') for line in out.splitlines()) + if key and value + } + + return env + + +def _find_exe(exe, paths=None): + """Return path to an MSVC executable program. + + Tries to find the program in several places: first, one of the + MSVC program search paths from the registry; next, the directories + in the PATH environment variable. If any of those work, return an + absolute path that is known to exist. If none of them work, just + return the original program name, 'exe'. + """ + if not paths: + paths = os.getenv('path').split(os.pathsep) + for p in paths: + fn = os.path.join(os.path.abspath(p), exe) + if os.path.isfile(fn): + return fn + return exe + + +_vcvars_names = { + 'win32': 'x86', + 'win-amd64': 'amd64', + 'win-arm32': 'arm', + 'win-arm64': 'arm64', +} + + +def _get_vcvars_spec(host_platform, platform): + """ + Given a host platform and platform, determine the spec for vcvarsall. + + Uses the native MSVC host if the host platform would need expensive + emulation for x86. + + >>> _get_vcvars_spec('win-arm64', 'win32') + 'arm64_x86' + >>> _get_vcvars_spec('win-arm64', 'win-amd64') + 'arm64_amd64' + + Otherwise, always cross-compile from x86 to work with the + lighter-weight MSVC installs that do not include native 64-bit tools. + + >>> _get_vcvars_spec('win32', 'win32') + 'x86' + >>> _get_vcvars_spec('win-arm32', 'win-arm32') + 'x86_arm' + >>> _get_vcvars_spec('win-amd64', 'win-arm64') + 'x86_arm64' + """ + if host_platform != 'win-arm64': + host_platform = 'win32' + vc_hp = _vcvars_names[host_platform] + vc_plat = _vcvars_names[platform] + return vc_hp if vc_hp == vc_plat else f'{vc_hp}_{vc_plat}' + + +class Compiler(base.Compiler): + """Concrete class that implements an interface to Microsoft Visual C++, + as defined by the CCompiler abstract class.""" + + compiler_type = 'msvc' + + # Just set this so CCompiler's constructor doesn't barf. We currently + # don't use the 'set_executables()' bureaucracy provided by CCompiler, + # as it really isn't necessary for this sort of single-compiler class. + # Would be nice to have a consistent interface with UnixCCompiler, + # though, so it's worth thinking about. + executables = {} + + # Private class data (need to distinguish C from C++ source for compiler) + _c_extensions = ['.c'] + _cpp_extensions = ['.cc', '.cpp', '.cxx'] + _rc_extensions = ['.rc'] + _mc_extensions = ['.mc'] + + # Needed for the filename generation methods provided by the + # base class, CCompiler. + src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions + res_extension = '.res' + obj_extension = '.obj' + static_lib_extension = '.lib' + shared_lib_extension = '.dll' + static_lib_format = shared_lib_format = '%s%s' + exe_extension = '.exe' + + def __init__(self, verbose=False, force=False) -> None: + super().__init__(verbose, force=force) + # target platform (.plat_name is consistent with 'bdist') + self.plat_name = None + self.initialized = False + + @classmethod + def _configure(cls, vc_env): + """ + Set class-level include/lib dirs. + """ + cls.include_dirs = cls._parse_path(vc_env.get('include', '')) + cls.library_dirs = cls._parse_path(vc_env.get('lib', '')) + + @staticmethod + def _parse_path(val): + return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir] + + def initialize(self, plat_name: str | None = None) -> None: + # multi-init means we would need to check platform same each time... + assert not self.initialized, "don't init multiple times" + if plat_name is None: + plat_name = get_platform() + # sanity check for platforms to prevent obscure errors later. + if plat_name not in _vcvars_names: + raise DistutilsPlatformError( + f"--plat-name must be one of {tuple(_vcvars_names)}" + ) + + plat_spec = _get_vcvars_spec(get_host_platform(), plat_name) + + vc_env = _get_vc_env(plat_spec) + if not vc_env: + raise DistutilsPlatformError( + "Unable to find a compatible Visual Studio installation." + ) + self._configure(vc_env) + + self._paths = vc_env.get('path', '') + paths = self._paths.split(os.pathsep) + self.cc = _find_exe("cl.exe", paths) + self.linker = _find_exe("link.exe", paths) + self.lib = _find_exe("lib.exe", paths) + self.rc = _find_exe("rc.exe", paths) # resource compiler + self.mc = _find_exe("mc.exe", paths) # message compiler + self.mt = _find_exe("mt.exe", paths) # message compiler + + self.preprocess_options = None + # bpo-38597: Always compile with dynamic linking + # Future releases of Python 3.x will include all past + # versions of vcruntime*.dll for compatibility. + self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD'] + + self.compile_options_debug = [ + '/nologo', + '/Od', + '/MDd', + '/Zi', + '/W3', + '/D_DEBUG', + ] + + ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG'] + + ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL'] + + self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1'] + self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1'] + self.ldflags_shared = [ + *ldflags, + '/DLL', + '/MANIFEST:EMBED,ID=2', + '/MANIFESTUAC:NO', + ] + self.ldflags_shared_debug = [ + *ldflags_debug, + '/DLL', + '/MANIFEST:EMBED,ID=2', + '/MANIFESTUAC:NO', + ] + self.ldflags_static = [*ldflags] + self.ldflags_static_debug = [*ldflags_debug] + + self._ldflags = { + (base.Compiler.EXECUTABLE, None): self.ldflags_exe, + (base.Compiler.EXECUTABLE, False): self.ldflags_exe, + (base.Compiler.EXECUTABLE, True): self.ldflags_exe_debug, + (base.Compiler.SHARED_OBJECT, None): self.ldflags_shared, + (base.Compiler.SHARED_OBJECT, False): self.ldflags_shared, + (base.Compiler.SHARED_OBJECT, True): self.ldflags_shared_debug, + (base.Compiler.SHARED_LIBRARY, None): self.ldflags_static, + (base.Compiler.SHARED_LIBRARY, False): self.ldflags_static, + (base.Compiler.SHARED_LIBRARY, True): self.ldflags_static_debug, + } + + self.initialized = True + + # -- Worker methods ------------------------------------------------ + + @property + def out_extensions(self) -> dict[str, str]: + return { + **super().out_extensions, + **{ + ext: self.res_extension + for ext in self._rc_extensions + self._mc_extensions + }, + } + + def compile( # noqa: C901 + self, + sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + depends=None, + ): + if not self.initialized: + self.initialize() + compile_info = self._setup_compile( + output_dir, macros, include_dirs, sources, depends, extra_postargs + ) + macros, objects, extra_postargs, pp_opts, build = compile_info + + compile_opts = extra_preargs or [] + compile_opts.append('/c') + if debug: + compile_opts.extend(self.compile_options_debug) + else: + compile_opts.extend(self.compile_options) + + add_cpp_opts = False + + for obj in objects: + try: + src, ext = build[obj] + except KeyError: + continue + if debug: + # pass the full pathname to MSVC in debug mode, + # this allows the debugger to find the source file + # without asking the user to browse for it + src = os.path.abspath(src) + + if ext in self._c_extensions: + input_opt = f"/Tc{src}" + elif ext in self._cpp_extensions: + input_opt = f"/Tp{src}" + add_cpp_opts = True + elif ext in self._rc_extensions: + # compile .RC to .RES file + input_opt = src + output_opt = "/fo" + obj + try: + self.spawn([self.rc] + pp_opts + [output_opt, input_opt]) + except DistutilsExecError as msg: + raise CompileError(msg) + continue + elif ext in self._mc_extensions: + # Compile .MC to .RC file to .RES file. + # * '-h dir' specifies the directory for the + # generated include file + # * '-r dir' specifies the target directory of the + # generated RC file and the binary message resource + # it includes + # + # For now (since there are no options to change this), + # we use the source-directory for the include file and + # the build directory for the RC file and message + # resources. This works at least for win32all. + h_dir = os.path.dirname(src) + rc_dir = os.path.dirname(obj) + try: + # first compile .MC to .RC and .H file + self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src]) + base, _ = os.path.splitext(os.path.basename(src)) + rc_file = os.path.join(rc_dir, base + '.rc') + # then compile .RC to .RES file + self.spawn([self.rc, "/fo" + obj, rc_file]) + + except DistutilsExecError as msg: + raise CompileError(msg) + continue + else: + # how to handle this file? + raise CompileError(f"Don't know how to compile {src} to {obj}") + + args = [self.cc] + compile_opts + pp_opts + if add_cpp_opts: + args.append('/EHsc') + args.extend((input_opt, "/Fo" + obj)) + args.extend(extra_postargs) + + try: + self.spawn(args) + except DistutilsExecError as msg: + raise CompileError(msg) + + return objects + + def create_static_lib( + self, + objects: list[str] | tuple[str, ...], + output_libname: str, + output_dir: str | None = None, + debug: bool = False, + target_lang: str | None = None, + ) -> None: + if not self.initialized: + self.initialize() + objects, output_dir = self._fix_object_args(objects, output_dir) + output_filename = self.library_filename(output_libname, output_dir=output_dir) + + if self._need_link(objects, output_filename): + lib_args = objects + ['/OUT:' + output_filename] + if debug: + pass # XXX what goes here? + try: + log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args)) + self.spawn([self.lib] + lib_args) + except DistutilsExecError as msg: + raise LibError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def link( + self, + target_desc: str, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: Iterable[str] | None = None, + build_temp: str | os.PathLike[str] | None = None, + target_lang: str | None = None, + ) -> None: + if not self.initialized: + self.initialize() + objects, output_dir = self._fix_object_args(objects, output_dir) + fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) + libraries, library_dirs, runtime_library_dirs = fixed_args + + if runtime_library_dirs: + self.warn( + "I don't know what to do with 'runtime_library_dirs': " + + str(runtime_library_dirs) + ) + + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) + if output_dir is not None: + output_filename = os.path.join(output_dir, output_filename) + + if self._need_link(objects, output_filename): + ldflags = self._ldflags[target_desc, debug] + + export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])] + + ld_args = ( + ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename] + ) + + # The MSVC linker generates .lib and .exp files, which cannot be + # suppressed by any linker switches. The .lib files may even be + # needed! Make sure they are generated in the temporary build + # directory. Since they have different names for debug and release + # builds, they can go into the same directory. + build_temp = os.path.dirname(objects[0]) + if export_symbols is not None: + (dll_name, dll_ext) = os.path.splitext( + os.path.basename(output_filename) + ) + implib_file = os.path.join(build_temp, self.library_filename(dll_name)) + ld_args.append('/IMPLIB:' + implib_file) + + if extra_preargs: + ld_args[:0] = extra_preargs + if extra_postargs: + ld_args.extend(extra_postargs) + + output_dir = os.path.dirname(os.path.abspath(output_filename)) + self.mkpath(output_dir) + try: + log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args)) + self.spawn([self.linker] + ld_args) + except DistutilsExecError as msg: + raise LinkError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def spawn(self, cmd): + env = dict(os.environ, PATH=self._paths) + with self._fallback_spawn(cmd, env) as fallback: + return super().spawn(cmd, env=env) + return fallback.value + + @contextlib.contextmanager + def _fallback_spawn(self, cmd, env): + """ + Discovered in pypa/distutils#15, some tools monkeypatch the compiler, + so the 'env' kwarg causes a TypeError. Detect this condition and + restore the legacy, unsafe behavior. + """ + bag = type('Bag', (), {})() + try: + yield bag + except TypeError as exc: + if "unexpected keyword argument 'env'" not in str(exc): + raise + else: + return + warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.") + with mock.patch.dict('os.environ', env): + bag.value = super().spawn(cmd) + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function, in + # ccompiler.py. + + def library_dir_option(self, dir): + return "/LIBPATH:" + dir + + def runtime_library_dir_option(self, dir): + raise DistutilsPlatformError( + "don't know how to set runtime library search path for MSVC" + ) + + def library_option(self, lib): + return self.library_filename(lib) + + def find_library_file(self, dirs, lib, debug=False): + # Prefer a debugging library if found (and requested), but deal + # with it if we don't have one. + if debug: + try_names = [lib + "_d", lib] + else: + try_names = [lib] + for dir in dirs: + for name in try_names: + libfile = os.path.join(dir, self.library_filename(name)) + if os.path.isfile(libfile): + return libfile + else: + # Oops, didn't find it in *any* of 'dirs' + return None diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_base.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abdd618a0ffdf756283d9ef83ccb93438f8bb2cb Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_base.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_cygwin.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_cygwin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86a180f63b1c8a9336f6e613f84ab82c70f2b03a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_cygwin.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_mingw.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_mingw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c98cdda3e1cd41b6fc19175ea4357156525617d3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_mingw.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_msvc.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_msvc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f62a847fbb40fed79ce575f13fdeae716dfa070d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_msvc.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_unix.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_unix.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4006409b4bd43b946106de1e9946ad33a856f694 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/__pycache__/test_unix.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_base.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a762e2b649d7977ef42f4d35854eab26bd54e9e7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_base.py @@ -0,0 +1,83 @@ +import platform +import sysconfig +import textwrap + +import pytest + +from .. import base + +pytestmark = pytest.mark.usefixtures('suppress_path_mangle') + + +@pytest.fixture +def c_file(tmp_path): + c_file = tmp_path / 'foo.c' + gen_headers = ('Python.h',) + is_windows = platform.system() == "Windows" + plat_headers = ('windows.h',) * is_windows + all_headers = gen_headers + plat_headers + headers = '\n'.join(f'#include <{header}>\n' for header in all_headers) + payload = ( + textwrap.dedent( + """ + #headers + void PyInit_foo(void) {} + """ + ) + .lstrip() + .replace('#headers', headers) + ) + c_file.write_text(payload, encoding='utf-8') + return c_file + + +def test_set_include_dirs(c_file): + """ + Extensions should build even if set_include_dirs is invoked. + In particular, compiler-specific paths should not be overridden. + """ + compiler = base.new_compiler() + python = sysconfig.get_paths()['include'] + compiler.set_include_dirs([python]) + compiler.compile([c_file]) + + # do it again, setting include dirs after any initialization + compiler.set_include_dirs([python]) + compiler.compile([c_file]) + + +def test_has_function_prototype(): + # Issue https://github.com/pypa/setuptools/issues/3648 + # Test prototype-generating behavior. + + compiler = base.new_compiler() + + # Every C implementation should have these. + assert compiler.has_function('abort') + assert compiler.has_function('exit') + with pytest.deprecated_call(match='includes is deprecated'): + # abort() is a valid expression with the prototype. + assert compiler.has_function('abort', includes=['stdlib.h']) + with pytest.deprecated_call(match='includes is deprecated'): + # But exit() is not valid with the actual prototype in scope. + assert not compiler.has_function('exit', includes=['stdlib.h']) + # And setuptools_does_not_exist is not declared or defined at all. + assert not compiler.has_function('setuptools_does_not_exist') + with pytest.deprecated_call(match='includes is deprecated'): + assert not compiler.has_function( + 'setuptools_does_not_exist', includes=['stdio.h'] + ) + + +def test_include_dirs_after_multiple_compile_calls(c_file): + """ + Calling compile multiple times should not change the include dirs + (regression test for setuptools issue #3591). + """ + compiler = base.new_compiler() + python = sysconfig.get_paths()['include'] + compiler.set_include_dirs([python]) + compiler.compile([c_file]) + assert compiler.include_dirs == [python] + compiler.compile([c_file]) + assert compiler.include_dirs == [python] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_cygwin.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_cygwin.py new file mode 100644 index 0000000000000000000000000000000000000000..9adf6b8ebf165b4fe92a52d8a14aed21aebba539 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_cygwin.py @@ -0,0 +1,76 @@ +"""Tests for distutils.cygwinccompiler.""" + +import os +import sys +from distutils import sysconfig +from distutils.tests import support + +import pytest + +from .. import cygwin + + +@pytest.fixture(autouse=True) +def stuff(request, monkeypatch, distutils_managed_tempdir): + self = request.instance + self.python_h = os.path.join(self.mkdtemp(), 'python.h') + monkeypatch.setattr(sysconfig, 'get_config_h_filename', self._get_config_h_filename) + monkeypatch.setattr(sys, 'version', sys.version) + + +class TestCygwinCCompiler(support.TempdirManager): + def _get_config_h_filename(self): + return self.python_h + + @pytest.mark.skipif('sys.platform != "cygwin"') + @pytest.mark.skipif('not os.path.exists("/usr/lib/libbash.dll.a")') + def test_find_library_file(self): + from distutils.cygwinccompiler import CygwinCCompiler + + compiler = CygwinCCompiler() + link_name = "bash" + linkable_file = compiler.find_library_file(["/usr/lib"], link_name) + assert linkable_file is not None + assert os.path.exists(linkable_file) + assert linkable_file == f"/usr/lib/lib{link_name:s}.dll.a" + + @pytest.mark.skipif('sys.platform != "cygwin"') + def test_runtime_library_dir_option(self): + from distutils.cygwinccompiler import CygwinCCompiler + + compiler = CygwinCCompiler() + assert compiler.runtime_library_dir_option('/foo') == [] + + def test_check_config_h(self): + # check_config_h looks for "GCC" in sys.version first + # returns CONFIG_H_OK if found + sys.version = ( + '2.6.1 (r261:67515, Dec 6 2008, 16:42:21) \n[GCC ' + '4.0.1 (Apple Computer, Inc. build 5370)]' + ) + + assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_OK + + # then it tries to see if it can find "__GNUC__" in pyconfig.h + sys.version = 'something without the *CC word' + + # if the file doesn't exist it returns CONFIG_H_UNCERTAIN + assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_UNCERTAIN + + # if it exists but does not contain __GNUC__, it returns CONFIG_H_NOTOK + self.write_file(self.python_h, 'xxx') + assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_NOTOK + + # and CONFIG_H_OK if __GNUC__ is found + self.write_file(self.python_h, 'xxx __GNUC__ xxx') + assert cygwin.check_config_h()[0] == cygwin.CONFIG_H_OK + + def test_get_msvcr(self): + assert cygwin.get_msvcr() == [] + + @pytest.mark.skipif('sys.platform != "cygwin"') + def test_dll_libraries_not_none(self): + from distutils.cygwinccompiler import CygwinCCompiler + + compiler = CygwinCCompiler() + assert compiler.dll_libraries is not None diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_mingw.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_mingw.py new file mode 100644 index 0000000000000000000000000000000000000000..dc45687a917808edbf692ced18b0c99183d21e2d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_mingw.py @@ -0,0 +1,48 @@ +from distutils import sysconfig +from distutils.errors import DistutilsPlatformError +from distutils.util import is_mingw, split_quoted + +import pytest + +from .. import cygwin, errors + + +class TestMinGW32Compiler: + @pytest.mark.skipif(not is_mingw(), reason='not on mingw') + def test_compiler_type(self): + compiler = cygwin.MinGW32Compiler() + assert compiler.compiler_type == 'mingw32' + + @pytest.mark.skipif(not is_mingw(), reason='not on mingw') + def test_set_executables(self, monkeypatch): + monkeypatch.setenv('CC', 'cc') + monkeypatch.setenv('CXX', 'c++') + + compiler = cygwin.MinGW32Compiler() + + assert compiler.compiler == split_quoted('cc -O -Wall') + assert compiler.compiler_so == split_quoted('cc -shared -O -Wall') + assert compiler.compiler_cxx == split_quoted('c++ -O -Wall') + assert compiler.linker_exe == split_quoted('cc') + assert compiler.linker_so == split_quoted('cc -shared') + + @pytest.mark.skipif(not is_mingw(), reason='not on mingw') + def test_runtime_library_dir_option(self): + compiler = cygwin.MinGW32Compiler() + with pytest.raises(DistutilsPlatformError): + compiler.runtime_library_dir_option('/usr/lib') + + @pytest.mark.skipif(not is_mingw(), reason='not on mingw') + def test_cygwincc_error(self, monkeypatch): + monkeypatch.setattr(cygwin, 'is_cygwincc', lambda _: True) + + with pytest.raises(errors.Error): + cygwin.MinGW32Compiler() + + @pytest.mark.skipif('sys.platform == "cygwin"') + def test_customize_compiler_with_msvc_python(self): + # In case we have an MSVC Python build, but still want to use + # MinGW32Compiler, then customize_compiler() shouldn't fail at least. + # https://github.com/pypa/setuptools/issues/4456 + compiler = cygwin.MinGW32Compiler() + sysconfig.customize_compiler(compiler) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_msvc.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_msvc.py new file mode 100644 index 0000000000000000000000000000000000000000..eca831996adcb07f05560581fe4285cdb29392d3 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_msvc.py @@ -0,0 +1,136 @@ +import os +import sys +import sysconfig +import threading +import unittest.mock as mock +from distutils.errors import DistutilsPlatformError +from distutils.tests import support +from distutils.util import get_platform + +import pytest + +from .. import msvc + +needs_winreg = pytest.mark.skipif('not hasattr(msvc, "winreg")') + + +class Testmsvccompiler(support.TempdirManager): + def test_no_compiler(self, monkeypatch): + # makes sure query_vcvarsall raises + # a DistutilsPlatformError if the compiler + # is not found + def _find_vcvarsall(plat_spec): + return None, None + + monkeypatch.setattr(msvc, '_find_vcvarsall', _find_vcvarsall) + + with pytest.raises(DistutilsPlatformError): + msvc._get_vc_env( + 'wont find this version', + ) + + @pytest.mark.skipif( + not sysconfig.get_platform().startswith("win"), + reason="Only run test for non-mingw Windows platforms", + ) + @pytest.mark.parametrize( + "plat_name, expected", + [ + ("win-arm64", "win-arm64"), + ("win-amd64", "win-amd64"), + (None, get_platform()), + ], + ) + def test_cross_platform_compilation_paths(self, monkeypatch, plat_name, expected): + """ + Ensure a specified target platform is passed to _get_vcvars_spec. + """ + compiler = msvc.Compiler() + + def _get_vcvars_spec(host_platform, platform): + assert platform == expected + + monkeypatch.setattr(msvc, '_get_vcvars_spec', _get_vcvars_spec) + compiler.initialize(plat_name) + + @needs_winreg + def test_get_vc_env_unicode(self): + test_var = 'ṰḖṤṪ┅ṼẨṜ' + test_value = '₃⁴₅' + + # Ensure we don't early exit from _get_vc_env + old_distutils_use_sdk = os.environ.pop('DISTUTILS_USE_SDK', None) + os.environ[test_var] = test_value + try: + env = msvc._get_vc_env('x86') + assert test_var.lower() in env + assert test_value == env[test_var.lower()] + finally: + os.environ.pop(test_var) + if old_distutils_use_sdk: + os.environ['DISTUTILS_USE_SDK'] = old_distutils_use_sdk + + @needs_winreg + @pytest.mark.parametrize('ver', (2015, 2017)) + def test_get_vc(self, ver): + # This function cannot be mocked, so pass if VC is found + # and skip otherwise. + lookup = getattr(msvc, f'_find_vc{ver}') + expected_version = {2015: 14, 2017: 15}[ver] + version, path = lookup() + if not version: + pytest.skip(f"VS {ver} is not installed") + assert version >= expected_version + assert os.path.isdir(path) + + +class CheckThread(threading.Thread): + exc_info = None + + def run(self): + try: + super().run() + except Exception: + self.exc_info = sys.exc_info() + + def __bool__(self): + return not self.exc_info + + +class TestSpawn: + def test_concurrent_safe(self): + """ + Concurrent calls to spawn should have consistent results. + """ + compiler = msvc.Compiler() + compiler._paths = "expected" + inner_cmd = 'import os; assert os.environ["PATH"] == "expected"' + command = [sys.executable, '-c', inner_cmd] + + threads = [ + CheckThread(target=compiler.spawn, args=[command]) for n in range(100) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert all(threads) + + def test_concurrent_safe_fallback(self): + """ + If CCompiler.spawn has been monkey-patched without support + for an env, it should still execute. + """ + from distutils import ccompiler + + compiler = msvc.Compiler() + compiler._paths = "expected" + + def CCompiler_spawn(self, cmd): + "A spawn without an env argument." + assert os.environ["PATH"] == "expected" + + with mock.patch.object(ccompiler.CCompiler, 'spawn', CCompiler_spawn): + compiler.spawn(["n/a"]) + + assert os.environ.get("PATH") != "expected" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_unix.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_unix.py new file mode 100644 index 0000000000000000000000000000000000000000..35b6b0e050c654bd9eff711ec3b94bea9adff2af --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/tests/test_unix.py @@ -0,0 +1,413 @@ +"""Tests for distutils.unixccompiler.""" + +import os +import sys +import unittest.mock as mock +from distutils import sysconfig +from distutils.compat import consolidate_linker_args +from distutils.errors import DistutilsPlatformError +from distutils.tests import support +from distutils.tests.compat.py39 import EnvironmentVarGuard +from distutils.util import _clear_cached_macosx_ver + +import pytest + +from .. import unix + + +@pytest.fixture(autouse=True) +def save_values(monkeypatch): + monkeypatch.setattr(sys, 'platform', sys.platform) + monkeypatch.setattr(sysconfig, 'get_config_var', sysconfig.get_config_var) + monkeypatch.setattr(sysconfig, 'get_config_vars', sysconfig.get_config_vars) + + +@pytest.fixture(autouse=True) +def compiler_wrapper(request): + class CompilerWrapper(unix.Compiler): + def rpath_foo(self): + return self.runtime_library_dir_option('/foo') + + request.instance.cc = CompilerWrapper() + + +class TestUnixCCompiler(support.TempdirManager): + @pytest.mark.skipif('platform.system == "Windows"') + def test_runtime_libdir_option(self): # noqa: C901 + # Issue #5900; GitHub Issue #37 + # + # Ensure RUNPATH is added to extension modules with RPATH if + # GNU ld is used + + # darwin + sys.platform = 'darwin' + darwin_ver_var = 'MACOSX_DEPLOYMENT_TARGET' + darwin_rpath_flag = '-Wl,-rpath,/foo' + darwin_lib_flag = '-L/foo' + + # (macOS version from syscfg, macOS version from env var) -> flag + # Version value of None generates two tests: as None and as empty string + # Expected flag value of None means an mismatch exception is expected + darwin_test_cases = [ + ((None, None), darwin_lib_flag), + ((None, '11'), darwin_rpath_flag), + (('10', None), darwin_lib_flag), + (('10.3', None), darwin_lib_flag), + (('10.3.1', None), darwin_lib_flag), + (('10.5', None), darwin_rpath_flag), + (('10.5.1', None), darwin_rpath_flag), + (('10.3', '10.3'), darwin_lib_flag), + (('10.3', '10.5'), darwin_rpath_flag), + (('10.5', '10.3'), darwin_lib_flag), + (('10.5', '11'), darwin_rpath_flag), + (('10.4', '10'), None), + ] + + def make_darwin_gcv(syscfg_macosx_ver): + def gcv(var): + if var == darwin_ver_var: + return syscfg_macosx_ver + return "xxx" + + return gcv + + def do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag): + env = os.environ + msg = f"macOS version = (sysconfig={syscfg_macosx_ver!r}, env={env_macosx_ver!r})" + + # Save + old_gcv = sysconfig.get_config_var + old_env_macosx_ver = env.get(darwin_ver_var) + + # Setup environment + _clear_cached_macosx_ver() + sysconfig.get_config_var = make_darwin_gcv(syscfg_macosx_ver) + if env_macosx_ver is not None: + env[darwin_ver_var] = env_macosx_ver + elif darwin_ver_var in env: + env.pop(darwin_ver_var) + + # Run the test + if expected_flag is not None: + assert self.cc.rpath_foo() == expected_flag, msg + else: + with pytest.raises( + DistutilsPlatformError, match=darwin_ver_var + r' mismatch' + ): + self.cc.rpath_foo() + + # Restore + if old_env_macosx_ver is not None: + env[darwin_ver_var] = old_env_macosx_ver + elif darwin_ver_var in env: + env.pop(darwin_ver_var) + sysconfig.get_config_var = old_gcv + _clear_cached_macosx_ver() + + for macosx_vers, expected_flag in darwin_test_cases: + syscfg_macosx_ver, env_macosx_ver = macosx_vers + do_darwin_test(syscfg_macosx_ver, env_macosx_ver, expected_flag) + # Bonus test cases with None interpreted as empty string + if syscfg_macosx_ver is None: + do_darwin_test("", env_macosx_ver, expected_flag) + if env_macosx_ver is None: + do_darwin_test(syscfg_macosx_ver, "", expected_flag) + if syscfg_macosx_ver is None and env_macosx_ver is None: + do_darwin_test("", "", expected_flag) + + old_gcv = sysconfig.get_config_var + + # hp-ux + sys.platform = 'hp-ux' + + def gcv(v): + return 'xxx' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == ['+s', '-L/foo'] + + def gcv(v): + return 'gcc' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == ['-Wl,+s', '-L/foo'] + + def gcv(v): + return 'g++' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == ['-Wl,+s', '-L/foo'] + + sysconfig.get_config_var = old_gcv + + # GCC GNULD + sys.platform = 'bar' + + def gcv(v): + if v == 'CC': + return 'gcc' + elif v == 'GNULD': + return 'yes' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == consolidate_linker_args([ + '-Wl,--enable-new-dtags', + '-Wl,-rpath,/foo', + ]) + + def gcv(v): + if v == 'CC': + return 'gcc -pthread -B /bar' + elif v == 'GNULD': + return 'yes' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == consolidate_linker_args([ + '-Wl,--enable-new-dtags', + '-Wl,-rpath,/foo', + ]) + + # GCC non-GNULD + sys.platform = 'bar' + + def gcv(v): + if v == 'CC': + return 'gcc' + elif v == 'GNULD': + return 'no' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == '-Wl,-R/foo' + + # GCC GNULD with fully qualified configuration prefix + # see #7617 + sys.platform = 'bar' + + def gcv(v): + if v == 'CC': + return 'x86_64-pc-linux-gnu-gcc-4.4.2' + elif v == 'GNULD': + return 'yes' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == consolidate_linker_args([ + '-Wl,--enable-new-dtags', + '-Wl,-rpath,/foo', + ]) + + # non-GCC GNULD + sys.platform = 'bar' + + def gcv(v): + if v == 'CC': + return 'cc' + elif v == 'GNULD': + return 'yes' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == consolidate_linker_args([ + '-Wl,--enable-new-dtags', + '-Wl,-rpath,/foo', + ]) + + # non-GCC non-GNULD + sys.platform = 'bar' + + def gcv(v): + if v == 'CC': + return 'cc' + elif v == 'GNULD': + return 'no' + + sysconfig.get_config_var = gcv + assert self.cc.rpath_foo() == '-Wl,-R/foo' + + @pytest.mark.skipif('platform.system == "Windows"') + def test_cc_overrides_ldshared(self): + # Issue #18080: + # ensure that setting CC env variable also changes default linker + def gcv(v): + if v == 'LDSHARED': + return 'gcc-4.2 -bundle -undefined dynamic_lookup ' + return 'gcc-4.2' + + def gcvs(*args, _orig=sysconfig.get_config_vars): + if args: + return list(map(sysconfig.get_config_var, args)) + return _orig() + + sysconfig.get_config_var = gcv + sysconfig.get_config_vars = gcvs + with EnvironmentVarGuard() as env: + env['CC'] = 'my_cc' + del env['LDSHARED'] + sysconfig.customize_compiler(self.cc) + assert self.cc.linker_so[0] == 'my_cc' + + @pytest.mark.skipif('platform.system == "Windows"') + def test_cxx_commands_used_are_correct(self): + def gcv(v): + if v == 'LDSHARED': + return 'ccache gcc-4.2 -bundle -undefined dynamic_lookup' + elif v == 'LDCXXSHARED': + return 'ccache g++-4.2 -bundle -undefined dynamic_lookup' + elif v == 'CXX': + return 'ccache g++-4.2' + elif v == 'CC': + return 'ccache gcc-4.2' + return '' + + def gcvs(*args, _orig=sysconfig.get_config_vars): + if args: + return list(map(sysconfig.get_config_var, args)) + return _orig() # pragma: no cover + + sysconfig.get_config_var = gcv + sysconfig.get_config_vars = gcvs + with ( + mock.patch.object(self.cc, 'spawn', return_value=None) as mock_spawn, + mock.patch.object(self.cc, '_need_link', return_value=True), + mock.patch.object(self.cc, 'mkpath', return_value=None), + EnvironmentVarGuard() as env, + ): + # override environment overrides in case they're specified by CI + del env['CXX'] + del env['LDCXXSHARED'] + + sysconfig.customize_compiler(self.cc) + assert self.cc.linker_so_cxx[0:2] == ['ccache', 'g++-4.2'] + assert self.cc.linker_exe_cxx[0:2] == ['ccache', 'g++-4.2'] + self.cc.link(None, [], 'a.out', target_lang='c++') + call_args = mock_spawn.call_args[0][0] + expected = ['ccache', 'g++-4.2', '-bundle', '-undefined', 'dynamic_lookup'] + assert call_args[:5] == expected + + self.cc.link_executable([], 'a.out', target_lang='c++') + call_args = mock_spawn.call_args[0][0] + expected = ['ccache', 'g++-4.2', '-o', self.cc.executable_filename('a.out')] + assert call_args[:4] == expected + + env['LDCXXSHARED'] = 'wrapper g++-4.2 -bundle -undefined dynamic_lookup' + env['CXX'] = 'wrapper g++-4.2' + sysconfig.customize_compiler(self.cc) + assert self.cc.linker_so_cxx[0:2] == ['wrapper', 'g++-4.2'] + assert self.cc.linker_exe_cxx[0:2] == ['wrapper', 'g++-4.2'] + self.cc.link(None, [], 'a.out', target_lang='c++') + call_args = mock_spawn.call_args[0][0] + expected = ['wrapper', 'g++-4.2', '-bundle', '-undefined', 'dynamic_lookup'] + assert call_args[:5] == expected + + self.cc.link_executable([], 'a.out', target_lang='c++') + call_args = mock_spawn.call_args[0][0] + expected = [ + 'wrapper', + 'g++-4.2', + '-o', + self.cc.executable_filename('a.out'), + ] + assert call_args[:4] == expected + + @pytest.mark.skipif('platform.system == "Windows"') + @pytest.mark.usefixtures('disable_macos_customization') + def test_cc_overrides_ldshared_for_cxx_correctly(self): + """ + Ensure that setting CC env variable also changes default linker + correctly when building C++ extensions. + + pypa/distutils#126 + """ + + def gcv(v): + if v == 'LDSHARED': + return 'gcc-4.2 -bundle -undefined dynamic_lookup ' + elif v == 'LDCXXSHARED': + return 'g++-4.2 -bundle -undefined dynamic_lookup ' + elif v == 'CXX': + return 'g++-4.2' + elif v == 'CC': + return 'gcc-4.2' + return '' + + def gcvs(*args, _orig=sysconfig.get_config_vars): + if args: + return list(map(sysconfig.get_config_var, args)) + return _orig() + + sysconfig.get_config_var = gcv + sysconfig.get_config_vars = gcvs + with ( + mock.patch.object(self.cc, 'spawn', return_value=None) as mock_spawn, + mock.patch.object(self.cc, '_need_link', return_value=True), + mock.patch.object(self.cc, 'mkpath', return_value=None), + EnvironmentVarGuard() as env, + ): + env['CC'] = 'ccache my_cc' + env['CXX'] = 'my_cxx' + del env['LDSHARED'] + sysconfig.customize_compiler(self.cc) + assert self.cc.linker_so[0:2] == ['ccache', 'my_cc'] + self.cc.link(None, [], 'a.out', target_lang='c++') + call_args = mock_spawn.call_args[0][0] + expected = ['my_cxx', '-bundle', '-undefined', 'dynamic_lookup'] + assert call_args[:4] == expected + + @pytest.mark.skipif('platform.system == "Windows"') + def test_explicit_ldshared(self): + # Issue #18080: + # ensure that setting CC env variable does not change + # explicit LDSHARED setting for linker + def gcv(v): + if v == 'LDSHARED': + return 'gcc-4.2 -bundle -undefined dynamic_lookup ' + return 'gcc-4.2' + + def gcvs(*args, _orig=sysconfig.get_config_vars): + if args: + return list(map(sysconfig.get_config_var, args)) + return _orig() + + sysconfig.get_config_var = gcv + sysconfig.get_config_vars = gcvs + with EnvironmentVarGuard() as env: + env['CC'] = 'my_cc' + env['LDSHARED'] = 'my_ld -bundle -dynamic' + sysconfig.customize_compiler(self.cc) + assert self.cc.linker_so[0] == 'my_ld' + + def test_has_function(self): + # Issue https://github.com/pypa/distutils/issues/64: + # ensure that setting output_dir does not raise + # FileNotFoundError: [Errno 2] No such file or directory: 'a.out' + self.cc.output_dir = 'scratch' + os.chdir(self.mkdtemp()) + self.cc.has_function('abort') + + def test_find_library_file(self, monkeypatch): + compiler = unix.Compiler() + compiler._library_root = lambda dir: dir + monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d) + + libname = 'libabc.dylib' if sys.platform != 'cygwin' else 'cygabc.dll' + dirs = ('/foo/bar/missing', '/foo/bar/existing') + assert ( + compiler.find_library_file(dirs, 'abc').replace('\\', '/') + == f'/foo/bar/existing/{libname}' + ) + assert ( + compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/') + == f'/foo/bar/existing/{libname}' + ) + + monkeypatch.setattr( + os.path, + 'exists', + lambda d: 'existing' in d and '.a' in d and '.dll.a' not in d, + ) + assert ( + compiler.find_library_file(dirs, 'abc').replace('\\', '/') + == '/foo/bar/existing/libabc.a' + ) + assert ( + compiler.find_library_file(reversed(dirs), 'abc').replace('\\', '/') + == '/foo/bar/existing/libabc.a' + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/unix.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/unix.py new file mode 100644 index 0000000000000000000000000000000000000000..1231b32d20fc0524ea50f6a70d7e017211c69e9b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/unix.py @@ -0,0 +1,422 @@ +"""distutils.unixccompiler + +Contains the UnixCCompiler class, a subclass of CCompiler that handles +the "typical" Unix-style command-line C compiler: + * macros defined with -Dname[=value] + * macros undefined with -Uname + * include search directories specified with -Idir + * libraries specified with -lllib + * library search directories specified with -Ldir + * compile handled by 'cc' (or similar) executable with -c option: + compiles .c to .o + * link static library handled by 'ar' command (possibly with 'ranlib') + * link shared library handled by 'cc -shared' +""" + +from __future__ import annotations + +import itertools +import os +import re +import shlex +import sys +from collections.abc import Iterable + +from ... import sysconfig +from ..._log import log +from ..._macos_compat import compiler_fixup +from ..._modified import newer +from ...compat import consolidate_linker_args +from ...errors import DistutilsExecError +from . import base +from .base import _Macro, gen_lib_options, gen_preprocess_options +from .errors import ( + CompileError, + LibError, + LinkError, +) + +# XXX Things not currently handled: +# * optimization/debug/warning flags; we just use whatever's in Python's +# Makefile and live with it. Is this adequate? If not, we might +# have to have a bunch of subclasses GNUCCompiler, SGICCompiler, +# SunCCompiler, and I suspect down that road lies madness. +# * even if we don't know a warning flag from an optimization flag, +# we need some way for outsiders to feed preprocessor/compiler/linker +# flags in to us -- eg. a sysadmin might want to mandate certain flags +# via a site config file, or a user might want to set something for +# compiling this module distribution only via the setup.py command +# line, whatever. As long as these options come from something on the +# current system, they can be as system-dependent as they like, and we +# should just happily stuff them into the preprocessor/compiler/linker +# options and carry on. + + +def _split_env(cmd): + """ + For macOS, split command into 'env' portion (if any) + and the rest of the linker command. + + >>> _split_env(['a', 'b', 'c']) + ([], ['a', 'b', 'c']) + >>> _split_env(['/usr/bin/env', 'A=3', 'gcc']) + (['/usr/bin/env', 'A=3'], ['gcc']) + """ + pivot = 0 + if os.path.basename(cmd[0]) == "env": + pivot = 1 + while '=' in cmd[pivot]: + pivot += 1 + return cmd[:pivot], cmd[pivot:] + + +def _split_aix(cmd): + """ + AIX platforms prefix the compiler with the ld_so_aix + script, so split that from the linker command. + + >>> _split_aix(['a', 'b', 'c']) + ([], ['a', 'b', 'c']) + >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc']) + (['/bin/foo/ld_so_aix'], ['gcc']) + """ + pivot = os.path.basename(cmd[0]) == 'ld_so_aix' + return cmd[:pivot], cmd[pivot:] + + +def _linker_params(linker_cmd, compiler_cmd): + """ + The linker command usually begins with the compiler + command (possibly multiple elements), followed by zero or more + params for shared library building. + + If the LDSHARED env variable overrides the linker command, + however, the commands may not match. + + Return the best guess of the linker parameters by stripping + the linker command. If the compiler command does not + match the linker command, assume the linker command is + just the first element. + + >>> _linker_params('gcc foo bar'.split(), ['gcc']) + ['foo', 'bar'] + >>> _linker_params('gcc foo bar'.split(), ['other']) + ['foo', 'bar'] + >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split()) + ['foo', 'bar'] + >>> _linker_params(['gcc'], ['gcc']) + [] + """ + c_len = len(compiler_cmd) + pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1 + return linker_cmd[pivot:] + + +class Compiler(base.Compiler): + compiler_type = 'unix' + + # These are used by CCompiler in two places: the constructor sets + # instance attributes 'preprocessor', 'compiler', etc. from them, and + # 'set_executable()' allows any of these to be set. The defaults here + # are pretty generic; they will probably have to be set by an outsider + # (eg. using information discovered by the sysconfig about building + # Python extensions). + executables = { + 'preprocessor': None, + 'compiler': ["cc"], + 'compiler_so': ["cc"], + 'compiler_cxx': ["c++"], + 'compiler_so_cxx': ["c++"], + 'linker_so': ["cc", "-shared"], + 'linker_so_cxx': ["c++", "-shared"], + 'linker_exe': ["cc"], + 'linker_exe_cxx': ["c++", "-shared"], + 'archiver': ["ar", "-cr"], + 'ranlib': None, + } + + if sys.platform[:6] == "darwin": + executables['ranlib'] = ["ranlib"] + + # Needed for the filename generation methods provided by the base + # class, CCompiler. NB. whoever instantiates/uses a particular + # UnixCCompiler instance should set 'shared_lib_ext' -- we set a + # reasonable common default here, but it's not necessarily used on all + # Unices! + + src_extensions = [".c", ".C", ".cc", ".cxx", ".cpp", ".m"] + obj_extension = ".o" + static_lib_extension = ".a" + shared_lib_extension = ".so" + dylib_lib_extension = ".dylib" + xcode_stub_lib_extension = ".tbd" + static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s" + xcode_stub_lib_format = dylib_lib_format + if sys.platform == "cygwin": + exe_extension = ".exe" + shared_lib_extension = ".dll.a" + dylib_lib_extension = ".dll" + dylib_lib_format = "cyg%s%s" + + def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs): + """Remove standard library path from rpath""" + libraries, library_dirs, runtime_library_dirs = super()._fix_lib_args( + libraries, library_dirs, runtime_library_dirs + ) + libdir = sysconfig.get_config_var('LIBDIR') + if ( + runtime_library_dirs + and libdir.startswith("/usr/lib") + and (libdir in runtime_library_dirs) + ): + runtime_library_dirs.remove(libdir) + return libraries, library_dirs, runtime_library_dirs + + def preprocess( + self, + source: str | os.PathLike[str], + output_file: str | os.PathLike[str] | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + extra_preargs: list[str] | None = None, + extra_postargs: Iterable[str] | None = None, + ): + fixed_args = self._fix_compile_args(None, macros, include_dirs) + ignore, macros, include_dirs = fixed_args + pp_opts = gen_preprocess_options(macros, include_dirs) + pp_args = self.preprocessor + pp_opts + if output_file: + pp_args.extend(['-o', output_file]) + if extra_preargs: + pp_args[:0] = extra_preargs + if extra_postargs: + pp_args.extend(extra_postargs) + pp_args.append(source) + + # reasons to preprocess: + # - force is indicated + # - output is directed to stdout + # - source file is newer than the target + preprocess = self.force or output_file is None or newer(source, output_file) + if not preprocess: + return + + if output_file: + self.mkpath(os.path.dirname(output_file)) + + try: + self.spawn(pp_args) + except DistutilsExecError as msg: + raise CompileError(msg) + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs) + compiler_so_cxx = compiler_fixup(self.compiler_so_cxx, cc_args + extra_postargs) + try: + if self.detect_language(src) == 'c++': + self.spawn( + compiler_so_cxx + cc_args + [src, '-o', obj] + extra_postargs + ) + else: + self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs) + except DistutilsExecError as msg: + raise CompileError(msg) + + def create_static_lib( + self, objects, output_libname, output_dir=None, debug=False, target_lang=None + ): + objects, output_dir = self._fix_object_args(objects, output_dir) + + output_filename = self.library_filename(output_libname, output_dir=output_dir) + + if self._need_link(objects, output_filename): + self.mkpath(os.path.dirname(output_filename)) + self.spawn(self.archiver + [output_filename] + objects + self.objects) + + # Not many Unices required ranlib anymore -- SunOS 4.x is, I + # think the only major Unix that does. Maybe we need some + # platform intelligence here to skip ranlib if it's not + # needed -- or maybe Python's configure script took care of + # it for us, hence the check for leading colon. + if self.ranlib: + try: + self.spawn(self.ranlib + [output_filename]) + except DistutilsExecError as msg: + raise LibError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + def link( + self, + target_desc, + objects: list[str] | tuple[str, ...], + output_filename, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + objects, output_dir = self._fix_object_args(objects, output_dir) + fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) + libraries, library_dirs, runtime_library_dirs = fixed_args + + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) + if not isinstance(output_dir, (str, type(None))): + raise TypeError("'output_dir' must be a string or None") + if output_dir is not None: + output_filename = os.path.join(output_dir, output_filename) + + if self._need_link(objects, output_filename): + ld_args = objects + self.objects + lib_opts + ['-o', output_filename] + if debug: + ld_args[:0] = ['-g'] + if extra_preargs: + ld_args[:0] = extra_preargs + if extra_postargs: + ld_args.extend(extra_postargs) + self.mkpath(os.path.dirname(output_filename)) + try: + # Select a linker based on context: linker_exe when + # building an executable or linker_so (with shared options) + # when building a shared library. + building_exe = target_desc == base.Compiler.EXECUTABLE + target_cxx = target_lang == "c++" + linker = ( + (self.linker_exe_cxx if target_cxx else self.linker_exe) + if building_exe + else (self.linker_so_cxx if target_cxx else self.linker_so) + )[:] + + if target_cxx and self.compiler_cxx: + env, linker_ne = _split_env(linker) + aix, linker_na = _split_aix(linker_ne) + _, compiler_cxx_ne = _split_env(self.compiler_cxx) + _, linker_exe_ne = _split_env(self.linker_exe_cxx) + + params = _linker_params(linker_na, linker_exe_ne) + linker = env + aix + compiler_cxx_ne + params + + linker = compiler_fixup(linker, ld_args) + + self.spawn(linker + ld_args) + except DistutilsExecError as msg: + raise LinkError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + + # -- Miscellaneous methods ----------------------------------------- + # These are all used by the 'gen_lib_options() function, in + # ccompiler.py. + + def library_dir_option(self, dir): + return "-L" + dir + + def _is_gcc(self): + cc_var = sysconfig.get_config_var("CC") + compiler = os.path.basename(shlex.split(cc_var)[0]) + return "gcc" in compiler or "g++" in compiler + + def runtime_library_dir_option(self, dir: str) -> str | list[str]: # type: ignore[override] # Fixed in pypa/distutils#339 + # XXX Hackish, at the very least. See Python bug #445902: + # https://bugs.python.org/issue445902 + # Linkers on different platforms need different options to + # specify that directories need to be added to the list of + # directories searched for dependencies when a dynamic library + # is sought. GCC on GNU systems (Linux, FreeBSD, ...) has to + # be told to pass the -R option through to the linker, whereas + # other compilers and gcc on other systems just know this. + # Other compilers may need something slightly different. At + # this time, there's no way to determine this information from + # the configuration data stored in the Python installation, so + # we use this hack. + if sys.platform[:6] == "darwin": + from distutils.util import get_macosx_target_ver, split_version + + macosx_target_ver = get_macosx_target_ver() + if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]: + return "-Wl,-rpath," + dir + else: # no support for -rpath on earlier macOS versions + return "-L" + dir + elif sys.platform[:7] == "freebsd": + return "-Wl,-rpath=" + dir + elif sys.platform[:5] == "hp-ux": + return [ + "-Wl,+s" if self._is_gcc() else "+s", + "-L" + dir, + ] + + # For all compilers, `-Wl` is the presumed way to pass a + # compiler option to the linker + if sysconfig.get_config_var("GNULD") == "yes": + return consolidate_linker_args([ + # Force RUNPATH instead of RPATH + "-Wl,--enable-new-dtags", + "-Wl,-rpath," + dir, + ]) + else: + return "-Wl,-R" + dir + + def library_option(self, lib): + return "-l" + lib + + @staticmethod + def _library_root(dir): + """ + macOS users can specify an alternate SDK using'-isysroot'. + Calculate the SDK root if it is specified. + + Note that, as of Xcode 7, Apple SDKs may contain textual stub + libraries with .tbd extensions rather than the normal .dylib + shared libraries installed in /. The Apple compiler tool + chain handles this transparently but it can cause problems + for programs that are being built with an SDK and searching + for specific libraries. Callers of find_library_file need to + keep in mind that the base filename of the returned SDK library + file might have a different extension from that of the library + file installed on the running system, for example: + /Applications/Xcode.app/Contents/Developer/Platforms/ + MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/ + usr/lib/libedit.tbd + vs + /usr/lib/libedit.dylib + """ + cflags = sysconfig.get_config_var('CFLAGS') + match = re.search(r'-isysroot\s*(\S+)', cflags) + + apply_root = ( + sys.platform == 'darwin' + and match + and ( + dir.startswith('/System/') + or (dir.startswith('/usr/') and not dir.startswith('/usr/local/')) + ) + ) + + return os.path.join(match.group(1), dir[1:]) if apply_root else dir + + def find_library_file(self, dirs, lib, debug=False): + """ + Second-guess the linker with not much hard + data to go on: GCC seems to prefer the shared library, so + assume that *all* Unix C compilers do, + ignoring even GCC's "-static" option. + """ + lib_names = ( + self.library_filename(lib, lib_type=type) + for type in 'dylib xcode_stub shared static'.split() + ) + + roots = map(self._library_root, dirs) + + searched = itertools.starmap(os.path.join, itertools.product(roots, lib_names)) + + found = filter(os.path.exists, searched) + + # Return None if it could not be found in any dir. + return next(found, None) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/zos.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/zos.py new file mode 100644 index 0000000000000000000000000000000000000000..681c63166be8dfea8ec3f621586b901220abe1c5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/compilers/C/zos.py @@ -0,0 +1,230 @@ +"""distutils.zosccompiler + +Contains the selection of the c & c++ compilers on z/OS. There are several +different c compilers on z/OS, all of them are optional, so the correct +one needs to be chosen based on the users input. This is compatible with +the following compilers: + +IBM C/C++ For Open Enterprise Languages on z/OS 2.0 +IBM Open XL C/C++ 1.1 for z/OS +IBM XL C/C++ V2.4.1 for z/OS 2.4 and 2.5 +IBM z/OS XL C/C++ +""" + +import os + +from ... import sysconfig +from ...errors import DistutilsExecError +from . import unix +from .errors import CompileError + +_cc_args = { + 'ibm-openxl': [ + '-m64', + '-fvisibility=default', + '-fzos-le-char-mode=ascii', + '-fno-short-enums', + ], + 'ibm-xlclang': [ + '-q64', + '-qexportall', + '-qascii', + '-qstrict', + '-qnocsect', + '-Wa,asa,goff', + '-Wa,xplink', + '-qgonumber', + '-qenum=int', + '-Wc,DLL', + ], + 'ibm-xlc': [ + '-q64', + '-qexportall', + '-qascii', + '-qstrict', + '-qnocsect', + '-Wa,asa,goff', + '-Wa,xplink', + '-qgonumber', + '-qenum=int', + '-Wc,DLL', + '-qlanglvl=extc99', + ], +} + +_cxx_args = { + 'ibm-openxl': [ + '-m64', + '-fvisibility=default', + '-fzos-le-char-mode=ascii', + '-fno-short-enums', + ], + 'ibm-xlclang': [ + '-q64', + '-qexportall', + '-qascii', + '-qstrict', + '-qnocsect', + '-Wa,asa,goff', + '-Wa,xplink', + '-qgonumber', + '-qenum=int', + '-Wc,DLL', + ], + 'ibm-xlc': [ + '-q64', + '-qexportall', + '-qascii', + '-qstrict', + '-qnocsect', + '-Wa,asa,goff', + '-Wa,xplink', + '-qgonumber', + '-qenum=int', + '-Wc,DLL', + '-qlanglvl=extended0x', + ], +} + +_asm_args = { + 'ibm-openxl': ['-fasm', '-fno-integrated-as', '-Wa,--ASA', '-Wa,--GOFF'], + 'ibm-xlclang': [], + 'ibm-xlc': [], +} + +_ld_args = { + 'ibm-openxl': [], + 'ibm-xlclang': ['-Wl,dll', '-q64'], + 'ibm-xlc': ['-Wl,dll', '-q64'], +} + + +# Python on z/OS is built with no compiler specific options in it's CFLAGS. +# But each compiler requires it's own specific options to build successfully, +# though some of the options are common between them +class Compiler(unix.Compiler): + src_extensions = ['.c', '.C', '.cc', '.cxx', '.cpp', '.m', '.s'] + _cpp_extensions = ['.cc', '.cpp', '.cxx', '.C'] + _asm_extensions = ['.s'] + + def _get_zos_compiler_name(self): + zos_compiler_names = [ + os.path.basename(binary) + for envvar in ('CC', 'CXX', 'LDSHARED') + if (binary := os.environ.get(envvar, None)) + ] + if len(zos_compiler_names) == 0: + return 'ibm-openxl' + + zos_compilers = {} + for compiler in ( + 'ibm-clang', + 'ibm-clang64', + 'ibm-clang++', + 'ibm-clang++64', + 'clang', + 'clang++', + 'clang-14', + ): + zos_compilers[compiler] = 'ibm-openxl' + + for compiler in ('xlclang', 'xlclang++', 'njsc', 'njsc++'): + zos_compilers[compiler] = 'ibm-xlclang' + + for compiler in ('xlc', 'xlC', 'xlc++'): + zos_compilers[compiler] = 'ibm-xlc' + + return zos_compilers.get(zos_compiler_names[0], 'ibm-openxl') + + def __init__(self, verbose=False, force=False): + super().__init__(verbose, force=force) + self.zos_compiler = self._get_zos_compiler_name() + sysconfig.customize_compiler(self) + + def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): + local_args = [] + if ext in self._cpp_extensions: + compiler = self.compiler_cxx + local_args.extend(_cxx_args[self.zos_compiler]) + elif ext in self._asm_extensions: + compiler = self.compiler_so + local_args.extend(_cc_args[self.zos_compiler]) + local_args.extend(_asm_args[self.zos_compiler]) + else: + compiler = self.compiler_so + local_args.extend(_cc_args[self.zos_compiler]) + local_args.extend(cc_args) + + try: + self.spawn(compiler + local_args + [src, '-o', obj] + extra_postargs) + except DistutilsExecError as msg: + raise CompileError(msg) + + def runtime_library_dir_option(self, dir): + return '-L' + dir + + def link( + self, + target_desc, + objects, + output_filename, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug=False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, + ): + # For a built module to use functions from cpython, it needs to use Pythons + # side deck file. The side deck is located beside the libpython3.xx.so + ldversion = sysconfig.get_config_var('LDVERSION') + if sysconfig.python_build: + side_deck_path = os.path.join( + sysconfig.get_config_var('abs_builddir'), + f'libpython{ldversion}.x', + ) + else: + side_deck_path = os.path.join( + sysconfig.get_config_var('installed_base'), + sysconfig.get_config_var('platlibdir'), + f'libpython{ldversion}.x', + ) + + if os.path.exists(side_deck_path): + if extra_postargs: + extra_postargs.append(side_deck_path) + else: + extra_postargs = [side_deck_path] + + # Check and replace libraries included side deck files + if runtime_library_dirs: + for dir in runtime_library_dirs: + for library in libraries[:]: + library_side_deck = os.path.join(dir, f'{library}.x') + if os.path.exists(library_side_deck): + libraries.remove(library) + extra_postargs.append(library_side_deck) + break + + # Any required ld args for the given compiler + extra_postargs.extend(_ld_args[self.zos_compiler]) + + super().link( + target_desc, + objects, + output_filename, + output_dir, + libraries, + library_dirs, + runtime_library_dirs, + export_symbols, + debug, + extra_preargs, + extra_postargs, + build_temp, + target_lang, + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/core.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/core.py new file mode 100644 index 0000000000000000000000000000000000000000..bd62546bdd9d35dcc46e0b46a46b0c61a43fd0ba --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/core.py @@ -0,0 +1,289 @@ +"""distutils.core + +The only module that needs to be imported to use the Distutils; provides +the 'setup' function (which is to be called from the setup script). Also +indirectly provides the Distribution and Command classes, although they are +really defined in distutils.dist and distutils.cmd. +""" + +from __future__ import annotations + +import os +import sys +import tokenize +from collections.abc import Iterable + +from .cmd import Command +from .debug import DEBUG + +# Mainly import these so setup scripts can "from distutils.core import" them. +from .dist import Distribution +from .errors import ( + CCompilerError, + DistutilsArgError, + DistutilsError, + DistutilsSetupError, +) +from .extension import Extension + +__all__ = ['Distribution', 'Command', 'Extension', 'setup'] + +# This is a barebones help message generated displayed when the user +# runs the setup script with no arguments at all. More useful help +# is generated with various --help options: global help, list commands, +# and per-command help. +USAGE = """\ +usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] + or: %(script)s --help [cmd1 cmd2 ...] + or: %(script)s --help-commands + or: %(script)s cmd --help +""" + + +def gen_usage(script_name): + script = os.path.basename(script_name) + return USAGE % locals() + + +# Some mild magic to control the behaviour of 'setup()' from 'run_setup()'. +_setup_stop_after = None +_setup_distribution = None + +# Legal keyword arguments for the setup() function +setup_keywords = ( + 'distclass', + 'script_name', + 'script_args', + 'options', + 'name', + 'version', + 'author', + 'author_email', + 'maintainer', + 'maintainer_email', + 'url', + 'license', + 'description', + 'long_description', + 'keywords', + 'platforms', + 'classifiers', + 'download_url', + 'requires', + 'provides', + 'obsoletes', +) + +# Legal keyword arguments for the Extension constructor +extension_keywords = ( + 'name', + 'sources', + 'include_dirs', + 'define_macros', + 'undef_macros', + 'library_dirs', + 'libraries', + 'runtime_library_dirs', + 'extra_objects', + 'extra_compile_args', + 'extra_link_args', + 'swig_opts', + 'export_symbols', + 'depends', + 'language', +) + + +def setup(**attrs): # noqa: C901 + """The gateway to the Distutils: do everything your setup script needs + to do, in a highly flexible and user-driven way. Briefly: create a + Distribution instance; find and parse config files; parse the command + line; run each Distutils command found there, customized by the options + supplied to 'setup()' (as keyword arguments), in config files, and on + the command line. + + The Distribution instance might be an instance of a class supplied via + the 'distclass' keyword argument to 'setup'; if no such class is + supplied, then the Distribution class (in dist.py) is instantiated. + All other arguments to 'setup' (except for 'cmdclass') are used to set + attributes of the Distribution instance. + + The 'cmdclass' argument, if supplied, is a dictionary mapping command + names to command classes. Each command encountered on the command line + will be turned into a command class, which is in turn instantiated; any + class found in 'cmdclass' is used in place of the default, which is + (for command 'foo_bar') class 'foo_bar' in module + 'distutils.command.foo_bar'. The command class must provide a + 'user_options' attribute which is a list of option specifiers for + 'distutils.fancy_getopt'. Any command-line options between the current + and the next command are used to set attributes of the current command + object. + + When the entire command-line has been successfully parsed, calls the + 'run()' method on each command object in turn. This method will be + driven entirely by the Distribution object (which each command object + has a reference to, thanks to its constructor), and the + command-specific options that became attributes of each command + object. + """ + + global _setup_stop_after, _setup_distribution + + # Determine the distribution class -- either caller-supplied or + # our Distribution (see below). + klass = attrs.get('distclass') + if klass: + attrs.pop('distclass') + else: + klass = Distribution + + if 'script_name' not in attrs: + attrs['script_name'] = os.path.basename(sys.argv[0]) + if 'script_args' not in attrs: + attrs['script_args'] = sys.argv[1:] + + # Create the Distribution instance, using the remaining arguments + # (ie. everything except distclass) to initialize it + try: + _setup_distribution = dist = klass(attrs) + except DistutilsSetupError as msg: + if 'name' not in attrs: + raise SystemExit(f"error in setup command: {msg}") + else: + raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg)) + + if _setup_stop_after == "init": + return dist + + # Find and parse the config file(s): they will override options from + # the setup script, but be overridden by the command line. + dist.parse_config_files() + + if DEBUG: + print("options (after parsing config files):") + dist.dump_option_dicts() + + if _setup_stop_after == "config": + return dist + + # Parse the command line and override config files; any + # command-line errors are the end user's fault, so turn them into + # SystemExit to suppress tracebacks. + try: + ok = dist.parse_command_line() + except DistutilsArgError as msg: + raise SystemExit(gen_usage(dist.script_name) + f"\nerror: {msg}") + + if DEBUG: + print("options (after parsing command line):") + dist.dump_option_dicts() + + if _setup_stop_after == "commandline": + return dist + + # And finally, run all the commands found on the command line. + if ok: + return run_commands(dist) + + return dist + + +# setup () + + +def run_commands(dist): + """Given a Distribution object run all the commands, + raising ``SystemExit`` errors in the case of failure. + + This function assumes that either ``sys.argv`` or ``dist.script_args`` + is already set accordingly. + """ + try: + dist.run_commands() + except KeyboardInterrupt: + raise SystemExit("interrupted") + except OSError as exc: + if DEBUG: + sys.stderr.write(f"error: {exc}\n") + raise + else: + raise SystemExit(f"error: {exc}") + + except (DistutilsError, CCompilerError) as msg: + if DEBUG: + raise + else: + raise SystemExit("error: " + str(msg)) + + return dist + + +def run_setup(script_name, script_args: Iterable[str] | None = None, stop_after="run"): + """Run a setup script in a somewhat controlled environment, and + return the Distribution instance that drives things. This is useful + if you need to find out the distribution meta-data (passed as + keyword args from 'script' to 'setup()', or the contents of the + config files or command-line. + + 'script_name' is a file that will be read and run with 'exec()'; + 'sys.argv[0]' will be replaced with 'script' for the duration of the + call. 'script_args' is a list of strings; if supplied, + 'sys.argv[1:]' will be replaced by 'script_args' for the duration of + the call. + + 'stop_after' tells 'setup()' when to stop processing; possible + values: + init + stop after the Distribution instance has been created and + populated with the keyword arguments to 'setup()' + config + stop after config files have been parsed (and their data + stored in the Distribution instance) + commandline + stop after the command-line ('sys.argv[1:]' or 'script_args') + have been parsed (and the data stored in the Distribution) + run [default] + stop after all commands have been run (the same as if 'setup()' + had been called in the usual way + + Returns the Distribution instance, which provides all information + used to drive the Distutils. + """ + if stop_after not in ('init', 'config', 'commandline', 'run'): + raise ValueError(f"invalid value for 'stop_after': {stop_after!r}") + + global _setup_stop_after, _setup_distribution + _setup_stop_after = stop_after + + save_argv = sys.argv.copy() + g = {'__file__': script_name, '__name__': '__main__'} + try: + try: + sys.argv[0] = script_name + if script_args is not None: + sys.argv[1:] = script_args + # tokenize.open supports automatic encoding detection + with tokenize.open(script_name) as f: + code = f.read().replace(r'\r\n', r'\n') + exec(code, g) + finally: + sys.argv = save_argv + _setup_stop_after = None + except SystemExit: + # Hmm, should we do something if exiting with a non-zero code + # (ie. error)? + pass + + if _setup_distribution is None: + raise RuntimeError( + "'distutils.core.setup()' was never called -- " + f"perhaps '{script_name}' is not a Distutils setup script?" + ) + + # I wonder if the setup script's namespace -- g and l -- would be of + # any interest to callers? + # print "_setup_distribution:", _setup_distribution + return _setup_distribution + + +# run_setup () diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/cygwinccompiler.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/cygwinccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..de89e3cd8402c9b7048c9e456ff67601934f972b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/cygwinccompiler.py @@ -0,0 +1,31 @@ +from .compilers.C import cygwin +from .compilers.C.cygwin import ( + CONFIG_H_NOTOK, + CONFIG_H_OK, + CONFIG_H_UNCERTAIN, + check_config_h, + get_msvcr, + is_cygwincc, +) + +__all__ = [ + 'CONFIG_H_NOTOK', + 'CONFIG_H_OK', + 'CONFIG_H_UNCERTAIN', + 'CygwinCCompiler', + 'Mingw32CCompiler', + 'check_config_h', + 'get_msvcr', + 'is_cygwincc', +] + + +CygwinCCompiler = cygwin.Compiler +Mingw32CCompiler = cygwin.MinGW32Compiler + + +get_versions = None +""" +A stand-in for the previous get_versions() function to prevent failures +when monkeypatched. See pypa/setuptools#2969. +""" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/debug.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..daf1660f0d821143e388d37532a39ddfd2ca0347 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/debug.py @@ -0,0 +1,5 @@ +import os + +# If DISTUTILS_DEBUG is anything other than the empty string, we run in +# debug mode. +DEBUG = os.environ.get('DISTUTILS_DEBUG') diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dep_util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dep_util.py new file mode 100644 index 0000000000000000000000000000000000000000..09a8a2e126c8bb009dbbe61c5c4bd5e358744996 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dep_util.py @@ -0,0 +1,14 @@ +import warnings + +from . import _modified + + +def __getattr__(name): + if name not in ['newer', 'newer_group', 'newer_pairwise']: + raise AttributeError(name) + warnings.warn( + "dep_util is Deprecated. Use functions from setuptools instead.", + DeprecationWarning, + stacklevel=2, + ) + return getattr(_modified, name) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dir_util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dir_util.py new file mode 100644 index 0000000000000000000000000000000000000000..61b4575aa0318029c103f40af179cab20ed179b2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dir_util.py @@ -0,0 +1,232 @@ +"""distutils.dir_util + +Utility functions for manipulating directories and directory trees.""" + +import functools +import itertools +import os +import pathlib + +from . import file_util +from ._log import log +from .errors import DistutilsFileError, DistutilsInternalError + + +class SkipRepeatAbsolutePaths(set): + """ + Cache for mkpath. + + In addition to cheapening redundant calls, eliminates redundant + "creating /foo/bar/baz" messages in dry-run mode. + """ + + def __init__(self): + SkipRepeatAbsolutePaths.instance = self + + @classmethod + def clear(cls): + super(cls, cls.instance).clear() + + def wrap(self, func): + @functools.wraps(func) + def wrapper(path, *args, **kwargs): + if path.absolute() in self: + return + result = func(path, *args, **kwargs) + self.add(path.absolute()) + return result + + return wrapper + + +# Python 3.8 compatibility +wrapper = SkipRepeatAbsolutePaths().wrap + + +@functools.singledispatch +@wrapper +def mkpath(name: pathlib.Path, mode=0o777, verbose=True) -> None: + """Create a directory and any missing ancestor directories. + + If the directory already exists (or if 'name' is the empty string, which + means the current directory, which of course exists), then do nothing. + Raise DistutilsFileError if unable to create some directory along the way + (eg. some sub-path exists, but is a file rather than a directory). + If 'verbose' is true, log the directory created. + """ + if verbose and not name.is_dir(): + log.info("creating %s", name) + + try: + name.mkdir(mode=mode, parents=True, exist_ok=True) + except OSError as exc: + raise DistutilsFileError(f"could not create '{name}': {exc.args[-1]}") + + +@mkpath.register +def _(name: str, *args, **kwargs): + return mkpath(pathlib.Path(name), *args, **kwargs) + + +@mkpath.register +def _(name: None, *args, **kwargs): + """ + Detect a common bug -- name is None. + """ + raise DistutilsInternalError(f"mkpath: 'name' must be a string (got {name!r})") + + +def create_tree(base_dir, files, mode=0o777, verbose=True): + """Create all the empty directories under 'base_dir' needed to put 'files' + there. + + 'base_dir' is just the name of a directory which doesn't necessarily + exist yet; 'files' is a list of filenames to be interpreted relative to + 'base_dir'. 'base_dir' + the directory portion of every file in 'files' + will be created if it doesn't already exist. 'mode' and 'verbose' + flags are as for 'mkpath()'. + """ + # First get the list of directories to create + need_dir = set(os.path.join(base_dir, os.path.dirname(file)) for file in files) + + # Now create them + for dir in sorted(need_dir): + mkpath(dir, mode, verbose=verbose) + + +def copy_tree( + src, + dst, + preserve_mode=True, + preserve_times=True, + preserve_symlinks=False, + update=False, + verbose=True, +): + """Copy an entire directory tree 'src' to a new location 'dst'. + + Both 'src' and 'dst' must be directory names. If 'src' is not a + directory, raise DistutilsFileError. If 'dst' does not exist, it is + created with 'mkpath()'. The end result of the copy is that every + file in 'src' is copied to 'dst', and directories under 'src' are + recursively copied to 'dst'. Return the list of files that were + copied or might have been copied, using their output name. The + return value is unaffected by 'update': it is simply + the list of all files under 'src', with the names changed to be + under 'dst'. + + 'preserve_mode' and 'preserve_times' are the same as for + 'copy_file'; note that they only apply to regular files, not to + directories. If 'preserve_symlinks' is true, symlinks will be + copied as symlinks (on platforms that support them!); otherwise + (the default), the destination of the symlink will be copied. + 'update' and 'verbose' are the same as for 'copy_file'. + """ + if not os.path.isdir(src): + raise DistutilsFileError(f"cannot copy tree '{src}': not a directory") + try: + names = os.listdir(src) + except OSError as e: + raise DistutilsFileError(f"error listing files in '{src}': {e.strerror}") + + mkpath(dst, verbose=verbose) + + copy_one = functools.partial( + _copy_one, + src=src, + dst=dst, + preserve_symlinks=preserve_symlinks, + verbose=verbose, + preserve_mode=preserve_mode, + preserve_times=preserve_times, + update=update, + ) + return list(itertools.chain.from_iterable(map(copy_one, names))) + + +def _copy_one( + name, + *, + src, + dst, + preserve_symlinks, + verbose, + preserve_mode, + preserve_times, + update, +): + src_name = os.path.join(src, name) + dst_name = os.path.join(dst, name) + + if name.startswith('.nfs'): + # skip NFS rename files + return + + if preserve_symlinks and os.path.islink(src_name): + link_dest = os.readlink(src_name) + if verbose >= 1: + log.info("linking %s -> %s", dst_name, link_dest) + os.symlink(link_dest, dst_name) + yield dst_name + + elif os.path.isdir(src_name): + yield from copy_tree( + src_name, + dst_name, + preserve_mode, + preserve_times, + preserve_symlinks, + update, + verbose=verbose, + ) + else: + file_util.copy_file( + src_name, + dst_name, + preserve_mode, + preserve_times, + update, + verbose=verbose, + ) + yield dst_name + + +def _build_cmdtuple(path, cmdtuples): + """Helper for remove_tree().""" + for f in os.listdir(path): + real_f = os.path.join(path, f) + if os.path.isdir(real_f) and not os.path.islink(real_f): + _build_cmdtuple(real_f, cmdtuples) + else: + cmdtuples.append((os.remove, real_f)) + cmdtuples.append((os.rmdir, path)) + + +def remove_tree(directory, verbose=True): + """Recursively remove an entire directory tree. + + Any errors are ignored (apart from being reported to stdout if 'verbose' + is true). + """ + if verbose >= 1: + log.info("removing '%s' (and everything under it)", directory) + cmdtuples = [] + _build_cmdtuple(directory, cmdtuples) + for cmd in cmdtuples: + try: + cmd[0](cmd[1]) + # Clear the cache + SkipRepeatAbsolutePaths.clear() + except OSError as exc: + log.warning("error removing %s: %s", directory, exc) + + +def ensure_relative(path): + """Take the full path 'path', and make it a relative path. + + This is useful to make 'path' the second argument to os.path.join(). + """ + drive, path = os.path.splitdrive(path) + if path[0:1] == os.sep: + path = drive + path[1:] + return path diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dist.py new file mode 100644 index 0000000000000000000000000000000000000000..e04e487b58bd75b5b50ccb005c2c3de4cf5038af --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/dist.py @@ -0,0 +1,1384 @@ +"""distutils.dist + +Provides the Distribution class, which represents the module distribution +being built/installed/distributed. +""" + +from __future__ import annotations + +import contextlib +import logging +import os +import pathlib +import re +import sys +import warnings +from collections.abc import Iterable, MutableMapping +from email import message_from_file +from typing import ( + IO, + TYPE_CHECKING, + Any, + ClassVar, + Literal, + TypeVar, + Union, + overload, +) + +from packaging.utils import canonicalize_name, canonicalize_version + +from ._log import log +from .debug import DEBUG +from .errors import ( + DistutilsArgError, + DistutilsClassError, + DistutilsModuleError, + DistutilsOptionError, +) +from .fancy_getopt import FancyGetopt, translate_longopt +from .util import check_environ, rfc822_escape, strtobool + +if TYPE_CHECKING: + from _typeshed import SupportsWrite + from typing_extensions import TypeAlias + + # type-only import because of mutual dependence between these modules + from .cmd import Command + +_CommandT = TypeVar("_CommandT", bound="Command") +_OptionsList: TypeAlias = list[ + Union[tuple[str, Union[str, None], str, int], tuple[str, Union[str, None], str]] +] + + +# Regex to define acceptable Distutils command names. This is not *quite* +# the same as a Python NAME -- I don't allow leading underscores. The fact +# that they're very similar is no coincidence; the default naming scheme is +# to look for a Python module named after the command. +command_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$') + + +def _ensure_list(value: str | Iterable[str], fieldname) -> str | list[str]: + if isinstance(value, str): + # a string containing comma separated values is okay. It will + # be converted to a list by Distribution.finalize_options(). + pass + elif not isinstance(value, list): + # passing a tuple or an iterator perhaps, warn and convert + typename = type(value).__name__ + msg = "Warning: '{fieldname}' should be a list, got type '{typename}'" + msg = msg.format(**locals()) + log.warning(msg) + value = list(value) + return value + + +class Distribution: + """The core of the Distutils. Most of the work hiding behind 'setup' + is really done within a Distribution instance, which farms the work out + to the Distutils commands specified on the command line. + + Setup scripts will almost never instantiate Distribution directly, + unless the 'setup()' function is totally inadequate to their needs. + However, it is conceivable that a setup script might wish to subclass + Distribution for some specialized purpose, and then pass the subclass + to 'setup()' as the 'distclass' keyword argument. If so, it is + necessary to respect the expectations that 'setup' has of Distribution. + See the code for 'setup()', in core.py, for details. + """ + + # 'global_options' describes the command-line options that may be + # supplied to the setup script prior to any actual commands. + # Eg. "./setup.py -n" or "./setup.py --quiet" both take advantage of + # these global options. This list should be kept to a bare minimum, + # since every global option is also valid as a command option -- and we + # don't want to pollute the commands with too many options that they + # have minimal control over. + # The fourth entry for verbose means that it can be repeated. + global_options: ClassVar[_OptionsList] = [ + ('verbose', 'v', "run verbosely (default)", 1), + ('quiet', 'q', "run quietly (turns verbosity off)"), + ('help', 'h', "show detailed help message"), + ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'), + ] + + # 'common_usage' is a short (2-3 line) string describing the common + # usage of the setup script. + common_usage: ClassVar[str] = """\ +Common commands: (see '--help-commands' for more) + + setup.py build will build the package underneath 'build/' + setup.py install will install the package +""" + + # options that are not propagated to the commands + display_options: ClassVar[_OptionsList] = [ + ('help-commands', None, "list all available commands"), + ('name', None, "print package name"), + ('version', 'V', "print package version"), + ('fullname', None, "print -"), + ('author', None, "print the author's name"), + ('author-email', None, "print the author's email address"), + ('maintainer', None, "print the maintainer's name"), + ('maintainer-email', None, "print the maintainer's email address"), + ('contact', None, "print the maintainer's name if known, else the author's"), + ( + 'contact-email', + None, + "print the maintainer's email address if known, else the author's", + ), + ('url', None, "print the URL for this package"), + ('license', None, "print the license of the package"), + ('licence', None, "alias for --license"), + ('description', None, "print the package description"), + ('long-description', None, "print the long package description"), + ('platforms', None, "print the list of platforms"), + ('classifiers', None, "print the list of classifiers"), + ('keywords', None, "print the list of keywords"), + ('provides', None, "print the list of packages/modules provided"), + ('requires', None, "print the list of packages/modules required"), + ('obsoletes', None, "print the list of packages/modules made obsolete"), + ] + display_option_names: ClassVar[list[str]] = [ + translate_longopt(x[0]) for x in display_options + ] + + # negative options are options that exclude other options + negative_opt: ClassVar[dict[str, str]] = {'quiet': 'verbose'} + + # -- Creation/initialization methods ------------------------------- + + # Can't Unpack a TypedDict with optional properties, so using Any instead + def __init__(self, attrs: MutableMapping[str, Any] | None = None) -> None: # noqa: C901 + """Construct a new Distribution instance: initialize all the + attributes of a Distribution, and then use 'attrs' (a dictionary + mapping attribute names to values) to assign some of those + attributes their "real" values. (Any attributes not mentioned in + 'attrs' will be assigned to some null value: 0, None, an empty list + or dictionary, etc.) Most importantly, initialize the + 'command_obj' attribute to the empty dictionary; this will be + filled in with real command objects by 'parse_command_line()'. + """ + + # Default values for our command-line options + self.verbose = True + self.help = False + for attr in self.display_option_names: + setattr(self, attr, False) + + # Store the distribution meta-data (name, version, author, and so + # forth) in a separate object -- we're getting to have enough + # information here (and enough command-line options) that it's + # worth it. Also delegate 'get_XXX()' methods to the 'metadata' + # object in a sneaky and underhanded (but efficient!) way. + self.metadata = DistributionMetadata() + for basename in self.metadata._METHOD_BASENAMES: + method_name = "get_" + basename + setattr(self, method_name, getattr(self.metadata, method_name)) + + # 'cmdclass' maps command names to class objects, so we + # can 1) quickly figure out which class to instantiate when + # we need to create a new command object, and 2) have a way + # for the setup script to override command classes + self.cmdclass: dict[str, type[Command]] = {} + + # 'command_packages' is a list of packages in which commands + # are searched for. The factory for command 'foo' is expected + # to be named 'foo' in the module 'foo' in one of the packages + # named here. This list is searched from the left; an error + # is raised if no named package provides the command being + # searched for. (Always access using get_command_packages().) + self.command_packages: str | list[str] | None = None + + # 'script_name' and 'script_args' are usually set to sys.argv[0] + # and sys.argv[1:], but they can be overridden when the caller is + # not necessarily a setup script run from the command-line. + self.script_name: str | os.PathLike[str] | None = None + self.script_args: list[str] | None = None + + # 'command_options' is where we store command options between + # parsing them (from config files, the command-line, etc.) and when + # they are actually needed -- ie. when the command in question is + # instantiated. It is a dictionary of dictionaries of 2-tuples: + # command_options = { command_name : { option : (source, value) } } + self.command_options: dict[str, dict[str, tuple[str, str]]] = {} + + # 'dist_files' is the list of (command, pyversion, file) that + # have been created by any dist commands run so far. This is + # filled regardless of whether the run is dry or not. pyversion + # gives sysconfig.get_python_version() if the dist file is + # specific to a Python version, 'any' if it is good for all + # Python versions on the target platform, and '' for a source + # file. pyversion should not be used to specify minimum or + # maximum required Python versions; use the metainfo for that + # instead. + self.dist_files: list[tuple[str, str, str]] = [] + + # These options are really the business of various commands, rather + # than of the Distribution itself. We provide aliases for them in + # Distribution as a convenience to the developer. + self.packages = None + self.package_data: dict[str, list[str]] = {} + self.package_dir = None + self.py_modules = None + self.libraries = None + self.headers = None + self.ext_modules = None + self.ext_package = None + self.include_dirs = None + self.extra_path = None + self.scripts = None + self.data_files = None + self.password = '' + + # And now initialize bookkeeping stuff that can't be supplied by + # the caller at all. 'command_obj' maps command names to + # Command instances -- that's how we enforce that every command + # class is a singleton. + self.command_obj: dict[str, Command] = {} + + # 'have_run' maps command names to boolean values; it keeps track + # of whether we have actually run a particular command, to make it + # cheap to "run" a command whenever we think we might need to -- if + # it's already been done, no need for expensive filesystem + # operations, we just check the 'have_run' dictionary and carry on. + # It's only safe to query 'have_run' for a command class that has + # been instantiated -- a false value will be inserted when the + # command object is created, and replaced with a true value when + # the command is successfully run. Thus it's probably best to use + # '.get()' rather than a straight lookup. + self.have_run: dict[str, bool] = {} + + # Now we'll use the attrs dictionary (ultimately, keyword args from + # the setup script) to possibly override any or all of these + # distribution options. + + if attrs: + # Pull out the set of command options and work on them + # specifically. Note that this order guarantees that aliased + # command options will override any supplied redundantly + # through the general options dictionary. + options = attrs.get('options') + if options is not None: + del attrs['options'] + for command, cmd_options in options.items(): + opt_dict = self.get_option_dict(command) + for opt, val in cmd_options.items(): + opt_dict[opt] = ("setup script", val) + + if 'licence' in attrs: + attrs['license'] = attrs['licence'] + del attrs['licence'] + msg = "'licence' distribution option is deprecated; use 'license'" + warnings.warn(msg) + + # Now work on the rest of the attributes. Any attribute that's + # not already defined is invalid! + for key, val in attrs.items(): + if hasattr(self.metadata, "set_" + key): + getattr(self.metadata, "set_" + key)(val) + elif hasattr(self.metadata, key): + setattr(self.metadata, key, val) + elif hasattr(self, key): + setattr(self, key, val) + else: + msg = f"Unknown distribution option: {key!r}" + warnings.warn(msg) + + # no-user-cfg is handled before other command line args + # because other args override the config files, and this + # one is needed before we can load the config files. + # If attrs['script_args'] wasn't passed, assume false. + # + # This also make sure we just look at the global options + self.want_user_cfg = True + + if self.script_args is not None: + # Coerce any possible iterable from attrs into a list + self.script_args = list(self.script_args) + for arg in self.script_args: + if not arg.startswith('-'): + break + if arg == '--no-user-cfg': + self.want_user_cfg = False + break + + self.finalize_options() + + def get_option_dict(self, command): + """Get the option dictionary for a given command. If that + command's option dictionary hasn't been created yet, then create it + and return the new dictionary; otherwise, return the existing + option dictionary. + """ + dict = self.command_options.get(command) + if dict is None: + dict = self.command_options[command] = {} + return dict + + def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None: + from pprint import pformat + + if commands is None: # dump all command option dicts + commands = sorted(self.command_options.keys()) + + if header is not None: + self.announce(indent + header) + indent = indent + " " + + if not commands: + self.announce(indent + "no commands known yet") + return + + for cmd_name in commands: + opt_dict = self.command_options.get(cmd_name) + if opt_dict is None: + self.announce(indent + f"no option dict for '{cmd_name}' command") + else: + self.announce(indent + f"option dict for '{cmd_name}' command:") + out = pformat(opt_dict) + for line in out.split('\n'): + self.announce(indent + " " + line) + + # -- Config file finding/parsing methods --------------------------- + + def find_config_files(self): + """Find as many configuration files as should be processed for this + platform, and return a list of filenames in the order in which they + should be parsed. The filenames returned are guaranteed to exist + (modulo nasty race conditions). + + There are multiple possible config files: + - distutils.cfg in the Distutils installation directory (i.e. + where the top-level Distutils __inst__.py file lives) + - a file in the user's home directory named .pydistutils.cfg + on Unix and pydistutils.cfg on Windows/Mac; may be disabled + with the ``--no-user-cfg`` option + - setup.cfg in the current directory + - a file named by an environment variable + """ + check_environ() + files = [str(path) for path in self._gen_paths() if os.path.isfile(path)] + + if DEBUG: + self.announce("using config files: {}".format(', '.join(files))) + + return files + + def _gen_paths(self): + # The system-wide Distutils config file + sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent + yield sys_dir / "distutils.cfg" + + # The per-user config file + prefix = '.' * (os.name == 'posix') + filename = prefix + 'pydistutils.cfg' + if self.want_user_cfg: + with contextlib.suppress(RuntimeError): + yield pathlib.Path('~').expanduser() / filename + + # All platforms support local setup.cfg + yield pathlib.Path('setup.cfg') + + # Additional config indicated in the environment + with contextlib.suppress(TypeError): + yield pathlib.Path(os.getenv("DIST_EXTRA_CONFIG")) + + def parse_config_files(self, filenames=None): # noqa: C901 + from configparser import ConfigParser + + # Ignore install directory options if we have a venv + if sys.prefix != sys.base_prefix: + ignore_options = [ + 'install-base', + 'install-platbase', + 'install-lib', + 'install-platlib', + 'install-purelib', + 'install-headers', + 'install-scripts', + 'install-data', + 'prefix', + 'exec-prefix', + 'home', + 'user', + 'root', + ] + else: + ignore_options = [] + + ignore_options = frozenset(ignore_options) + + if filenames is None: + filenames = self.find_config_files() + + if DEBUG: + self.announce("Distribution.parse_config_files():") + + parser = ConfigParser() + for filename in filenames: + if DEBUG: + self.announce(f" reading {filename}") + parser.read(filename, encoding='utf-8') + for section in parser.sections(): + options = parser.options(section) + opt_dict = self.get_option_dict(section) + + for opt in options: + if opt != '__name__' and opt not in ignore_options: + val = parser.get(section, opt) + opt = opt.replace('-', '_') + opt_dict[opt] = (filename, val) + + # Make the ConfigParser forget everything (so we retain + # the original filenames that options come from) + parser.__init__() + + # If there was a "global" section in the config file, use it + # to set Distribution options. + + if 'global' in self.command_options: + for opt, (_src, val) in self.command_options['global'].items(): + alias = self.negative_opt.get(opt) + try: + if alias: + setattr(self, alias, not strtobool(val)) + elif opt in ('verbose',): # ugh! + setattr(self, opt, strtobool(val)) + else: + setattr(self, opt, val) + except ValueError as msg: + raise DistutilsOptionError(msg) + + # -- Command-line parsing methods ---------------------------------- + + def parse_command_line(self): + """Parse the setup script's command line, taken from the + 'script_args' instance attribute (which defaults to 'sys.argv[1:]' + -- see 'setup()' in core.py). This list is first processed for + "global options" -- options that set attributes of the Distribution + instance. Then, it is alternately scanned for Distutils commands + and options for that command. Each new command terminates the + options for the previous command. The allowed options for a + command are determined by the 'user_options' attribute of the + command class -- thus, we have to be able to load command classes + in order to parse the command line. Any error in that 'options' + attribute raises DistutilsGetoptError; any error on the + command-line raises DistutilsArgError. If no Distutils commands + were found on the command line, raises DistutilsArgError. Return + true if command-line was successfully parsed and we should carry + on with executing commands; false if no errors but we shouldn't + execute commands (currently, this only happens if user asks for + help). + """ + # + # We now have enough information to show the Macintosh dialog + # that allows the user to interactively specify the "command line". + # + toplevel_options = self._get_toplevel_options() + + # We have to parse the command line a bit at a time -- global + # options, then the first command, then its options, and so on -- + # because each command will be handled by a different class, and + # the options that are valid for a particular class aren't known + # until we have loaded the command class, which doesn't happen + # until we know what the command is. + + self.commands = [] + parser = FancyGetopt(toplevel_options + self.display_options) + parser.set_negative_aliases(self.negative_opt) + parser.set_aliases({'licence': 'license'}) + args = parser.getopt(args=self.script_args, object=self) + option_order = parser.get_option_order() + logging.getLogger().setLevel(logging.WARN - 10 * self.verbose) + + # for display options we return immediately + if self.handle_display_options(option_order): + return + while args: + args = self._parse_command_opts(parser, args) + if args is None: # user asked for help (and got it) + return + + # Handle the cases of --help as a "global" option, ie. + # "setup.py --help" and "setup.py --help command ...". For the + # former, we show global options (--verbose, --dry-run, etc.) + # and display-only options (--name, --version, etc.); for the + # latter, we omit the display-only options and show help for + # each command listed on the command line. + if self.help: + self._show_help( + parser, display_options=len(self.commands) == 0, commands=self.commands + ) + return + + # Oops, no commands found -- an end-user error + if not self.commands: + raise DistutilsArgError("no commands supplied") + + # All is well: return true + return True + + def _get_toplevel_options(self): + """Return the non-display options recognized at the top level. + + This includes options that are recognized *only* at the top + level as well as options recognized for commands. + """ + return self.global_options + [ + ( + "command-packages=", + None, + "list of packages that provide distutils commands", + ), + ] + + def _parse_command_opts(self, parser, args): # noqa: C901 + """Parse the command-line options for a single command. + 'parser' must be a FancyGetopt instance; 'args' must be the list + of arguments, starting with the current command (whose options + we are about to parse). Returns a new version of 'args' with + the next command at the front of the list; will be the empty + list if there are no more commands on the command line. Returns + None if the user asked for help on this command. + """ + # late import because of mutual dependence between these modules + from distutils.cmd import Command + + # Pull the current command from the head of the command line + command = args[0] + if not command_re.match(command): + raise SystemExit(f"invalid command name '{command}'") + self.commands.append(command) + + # Dig up the command class that implements this command, so we + # 1) know that it's a valid command, and 2) know which options + # it takes. + try: + cmd_class = self.get_command_class(command) + except DistutilsModuleError as msg: + raise DistutilsArgError(msg) + + # Require that the command class be derived from Command -- want + # to be sure that the basic "command" interface is implemented. + if not issubclass(cmd_class, Command): + raise DistutilsClassError( + f"command class {cmd_class} must subclass Command" + ) + + # Also make sure that the command object provides a list of its + # known options. + if not ( + hasattr(cmd_class, 'user_options') + and isinstance(cmd_class.user_options, list) + ): + msg = ( + "command class %s must provide " + "'user_options' attribute (a list of tuples)" + ) + raise DistutilsClassError(msg % cmd_class) + + # If the command class has a list of negative alias options, + # merge it in with the global negative aliases. + negative_opt = self.negative_opt + if hasattr(cmd_class, 'negative_opt'): + negative_opt = negative_opt.copy() + negative_opt.update(cmd_class.negative_opt) + + # Check for help_options in command class. They have a different + # format (tuple of four) so we need to preprocess them here. + if hasattr(cmd_class, 'help_options') and isinstance( + cmd_class.help_options, list + ): + help_options = fix_help_options(cmd_class.help_options) + else: + help_options = [] + + # All commands support the global options too, just by adding + # in 'global_options'. + parser.set_option_table( + self.global_options + cmd_class.user_options + help_options + ) + parser.set_negative_aliases(negative_opt) + (args, opts) = parser.getopt(args[1:]) + if hasattr(opts, 'help') and opts.help: + self._show_help(parser, display_options=False, commands=[cmd_class]) + return + + if hasattr(cmd_class, 'help_options') and isinstance( + cmd_class.help_options, list + ): + help_option_found = 0 + for help_option, _short, _desc, func in cmd_class.help_options: + if hasattr(opts, parser.get_attr_name(help_option)): + help_option_found = 1 + if callable(func): + func() + else: + raise DistutilsClassError( + f"invalid help function {func!r} for help option '{help_option}': " + "must be a callable object (function, etc.)" + ) + + if help_option_found: + return + + # Put the options from the command-line into their official + # holding pen, the 'command_options' dictionary. + opt_dict = self.get_option_dict(command) + for name, value in vars(opts).items(): + opt_dict[name] = ("command line", value) + + return args + + def finalize_options(self) -> None: + """Set final values for all the options on the Distribution + instance, analogous to the .finalize_options() method of Command + objects. + """ + for attr in ('keywords', 'platforms'): + value = getattr(self.metadata, attr) + if value is None: + continue + if isinstance(value, str): + value = [elm.strip() for elm in value.split(',')] + setattr(self.metadata, attr, value) + + def _show_help( + self, parser, global_options=True, display_options=True, commands: Iterable = () + ): + """Show help for the setup script command-line in the form of + several lists of command-line options. 'parser' should be a + FancyGetopt instance; do not expect it to be returned in the + same state, as its option table will be reset to make it + generate the correct help text. + + If 'global_options' is true, lists the global options: + --verbose, --dry-run, etc. If 'display_options' is true, lists + the "display-only" options: --name, --version, etc. Finally, + lists per-command help for every command name or command class + in 'commands'. + """ + # late import because of mutual dependence between these modules + from distutils.cmd import Command + from distutils.core import gen_usage + + if global_options: + if display_options: + options = self._get_toplevel_options() + else: + options = self.global_options + parser.set_option_table(options) + parser.print_help(self.common_usage + "\nGlobal options:") + print() + + if display_options: + parser.set_option_table(self.display_options) + parser.print_help( + "Information display options (just display information, ignore any commands)" + ) + print() + + for command in commands: + if isinstance(command, type) and issubclass(command, Command): + klass = command + else: + klass = self.get_command_class(command) + if hasattr(klass, 'help_options') and isinstance(klass.help_options, list): + parser.set_option_table( + klass.user_options + fix_help_options(klass.help_options) + ) + else: + parser.set_option_table(klass.user_options) + parser.print_help(f"Options for '{klass.__name__}' command:") + print() + + print(gen_usage(self.script_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. + """ + from distutils.core import gen_usage + + # User just wants a list of commands -- we'll print it out and stop + # processing now (ie. if they ran "setup --help-commands foo bar", + # we ignore "foo bar"). + if self.help_commands: + self.print_commands() + print() + print(gen_usage(self.script_name)) + return 1 + + # If user supplied any of the "display metadata" options, then + # display that metadata in the order in which the user supplied the + # metadata options. + any_display_options = 0 + is_display_option = set() + for option in self.display_options: + is_display_option.add(option[0]) + + for opt, val in option_order: + if val and opt in is_display_option: + opt = translate_longopt(opt) + value = getattr(self.metadata, "get_" + opt)() + if opt in ('keywords', 'platforms'): + print(','.join(value)) + elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'): + print('\n'.join(value)) + else: + print(value) + any_display_options = 1 + + return any_display_options + + def print_command_list(self, commands, header, max_length) -> None: + """Print a subset of the list of all commands -- used by + 'print_commands()'. + """ + print(header + ":") + + for cmd in commands: + klass = self.cmdclass.get(cmd) + if not klass: + klass = self.get_command_class(cmd) + try: + description = klass.description + except AttributeError: + description = "(no description available)" + + print(f" {cmd:<{max_length}} {description}") + + def print_commands(self) -> None: + """Print out a help message listing all available commands with a + description of each. The list is divided into "standard commands" + (listed in distutils.command.__all__) and "extra commands" + (mentioned in self.cmdclass, but not a standard command). The + descriptions come from the command class attribute + 'description'. + """ + import distutils.command + + std_commands = distutils.command.__all__ + is_std = set(std_commands) + + extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std] + + max_length = 0 + for cmd in std_commands + extra_commands: + if len(cmd) > max_length: + max_length = len(cmd) + + self.print_command_list(std_commands, "Standard commands", max_length) + if extra_commands: + print() + self.print_command_list(extra_commands, "Extra commands", max_length) + + def get_command_list(self): + """Get a list of (command, description) tuples. + The list is divided into "standard commands" (listed in + distutils.command.__all__) and "extra commands" (mentioned in + self.cmdclass, but not a standard command). The descriptions come + from the command class attribute 'description'. + """ + # Currently this is only used on Mac OS, for the Mac-only GUI + # Distutils interface (by Jack Jansen) + import distutils.command + + std_commands = distutils.command.__all__ + is_std = set(std_commands) + + extra_commands = [cmd for cmd in self.cmdclass.keys() if cmd not in is_std] + + rv = [] + for cmd in std_commands + extra_commands: + klass = self.cmdclass.get(cmd) + if not klass: + klass = self.get_command_class(cmd) + try: + description = klass.description + except AttributeError: + description = "(no description available)" + rv.append((cmd, description)) + return rv + + # -- Command class/object methods ---------------------------------- + + def get_command_packages(self): + """Return a list of packages from which commands are loaded.""" + pkgs = self.command_packages + if not isinstance(pkgs, list): + if pkgs is None: + pkgs = '' + pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != ''] + if "distutils.command" not in pkgs: + pkgs.insert(0, "distutils.command") + self.command_packages = pkgs + return pkgs + + def get_command_class(self, command: str) -> type[Command]: + """Return the class that implements the Distutils command named by + 'command'. First we check the 'cmdclass' dictionary; if the + command is mentioned there, we fetch the class object from the + dictionary and return it. Otherwise we load the command module + ("distutils.command." + command) and fetch the command class from + the module. The loaded class is also stored in 'cmdclass' + to speed future calls to 'get_command_class()'. + + Raises DistutilsModuleError if the expected module could not be + found, or if that module does not define the expected class. + """ + klass = self.cmdclass.get(command) + if klass: + return klass + + for pkgname in self.get_command_packages(): + module_name = f"{pkgname}.{command}" + klass_name = command + + try: + __import__(module_name) + module = sys.modules[module_name] + except ImportError: + continue + + try: + klass = getattr(module, klass_name) + except AttributeError: + raise DistutilsModuleError( + f"invalid command '{command}' (no class '{klass_name}' in module '{module_name}')" + ) + + self.cmdclass[command] = klass + return klass + + raise DistutilsModuleError(f"invalid command '{command}'") + + @overload + def get_command_obj( + self, command: str, create: Literal[True] = True + ) -> Command: ... + @overload + def get_command_obj( + self, command: str, create: Literal[False] + ) -> Command | None: ... + def get_command_obj(self, command: str, create: bool = True) -> Command | None: + """Return the command object for 'command'. Normally this object + is cached on a previous call to 'get_command_obj()'; if no command + object for 'command' is in the cache, then we either create and + return it (if 'create' is true) or return None. + """ + cmd_obj = self.command_obj.get(command) + if not cmd_obj and create: + if DEBUG: + self.announce( + "Distribution.get_command_obj(): " + f"creating '{command}' command object" + ) + + klass = self.get_command_class(command) + cmd_obj = self.command_obj[command] = klass(self) + self.have_run[command] = False + + # Set any options that were supplied in config files + # or on the command line. (NB. support for error + # reporting is lame here: any errors aren't reported + # until 'finalize_options()' is called, which means + # we won't report the source of the error.) + options = self.command_options.get(command) + if options: + self._set_command_options(cmd_obj, options) + + return cmd_obj + + 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'). + """ + 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 msg: + raise DistutilsOptionError(msg) + + @overload + def reinitialize_command( + self, command: str, reinit_subcommands: bool = False + ) -> Command: ... + @overload + def reinitialize_command( + self, command: _CommandT, reinit_subcommands: bool = False + ) -> _CommandT: ... + def reinitialize_command( + self, command: str | Command, reinit_subcommands=False + ) -> Command: + """Reinitializes a command to the state it was in when first + returned by 'get_command_obj()': ie., initialized but not yet + finalized. This provides the opportunity to sneak option + values in programmatically, overriding or supplementing + user-supplied values from the config files and command line. + You'll have to re-finalize the command object (by calling + 'finalize_options()' or 'ensure_finalized()') before using it for + real. + + 'command' should be a command name (string) or command object. If + 'reinit_subcommands' is true, also reinitializes the command's + sub-commands, as declared by the 'sub_commands' class attribute (if + it has one). See the "install" command for an example. Only + reinitializes the sub-commands that actually matter, ie. those + whose test predicates return true. + + Returns the reinitialized command object. + """ + from distutils.cmd import Command + + if not isinstance(command, Command): + command_name = command + command = self.get_command_obj(command_name) + else: + command_name = command.get_command_name() + + if not command.finalized: + return command + command.initialize_options() + command.finalized = False + self.have_run[command_name] = False + self._set_command_options(command) + + if reinit_subcommands: + for sub in command.get_sub_commands(): + self.reinitialize_command(sub, reinit_subcommands) + + return command + + # -- Methods that operate on the Distribution ---------------------- + + def announce(self, msg, level: int = logging.INFO) -> None: + log.log(level, msg) + + def run_commands(self) -> None: + """Run each command that was seen on the setup script command line. + Uses the list of commands found and cache of command objects + created by 'get_command_obj()'. + """ + for cmd in self.commands: + self.run_command(cmd) + + # -- Methods that operate on its Commands -------------------------- + + def run_command(self, command: str) -> None: + """Do whatever it takes to run a command (including nothing at all, + if the command has already been run). Specifically: if we have + already created and run the command named by 'command', return + silently without doing anything. If the command named by 'command' + doesn't even have a command object yet, create one. Then invoke + 'run()' on that command object (or an existing one). + """ + # Already been here, done that? then return silently. + if self.have_run.get(command): + return + + log.info("running %s", command) + cmd_obj = self.get_command_obj(command) + cmd_obj.ensure_finalized() + cmd_obj.run() + self.have_run[command] = True + + # -- Distribution query methods ------------------------------------ + + def has_pure_modules(self) -> bool: + return len(self.packages or self.py_modules or []) > 0 + + def has_ext_modules(self) -> bool: + return self.ext_modules and len(self.ext_modules) > 0 + + def has_c_libraries(self) -> bool: + return self.libraries and len(self.libraries) > 0 + + def has_modules(self) -> bool: + return self.has_pure_modules() or self.has_ext_modules() + + def has_headers(self) -> bool: + return self.headers and len(self.headers) > 0 + + def has_scripts(self) -> bool: + return self.scripts and len(self.scripts) > 0 + + def has_data_files(self) -> bool: + return self.data_files and len(self.data_files) > 0 + + def is_pure(self) -> bool: + return ( + self.has_pure_modules() + and not self.has_ext_modules() + and not self.has_c_libraries() + ) + + # -- Metadata query methods ---------------------------------------- + + # If you're looking for 'get_name()', 'get_version()', and so forth, + # they are defined in a sneaky way: the constructor binds self.get_XXX + # to self.metadata.get_XXX. The actual code is in the + # DistributionMetadata class, below. + if TYPE_CHECKING: + # Unfortunately this means we need to specify them manually or not expose statically + def _(self) -> None: + self.get_name = self.metadata.get_name + self.get_version = self.metadata.get_version + self.get_fullname = self.metadata.get_fullname + self.get_author = self.metadata.get_author + self.get_author_email = self.metadata.get_author_email + self.get_maintainer = self.metadata.get_maintainer + self.get_maintainer_email = self.metadata.get_maintainer_email + self.get_contact = self.metadata.get_contact + self.get_contact_email = self.metadata.get_contact_email + self.get_url = self.metadata.get_url + self.get_license = self.metadata.get_license + self.get_licence = self.metadata.get_licence + self.get_description = self.metadata.get_description + self.get_long_description = self.metadata.get_long_description + self.get_keywords = self.metadata.get_keywords + self.get_platforms = self.metadata.get_platforms + self.get_classifiers = self.metadata.get_classifiers + self.get_download_url = self.metadata.get_download_url + self.get_requires = self.metadata.get_requires + self.get_provides = self.metadata.get_provides + self.get_obsoletes = self.metadata.get_obsoletes + + # Default attributes generated in __init__ from self.display_option_names + help_commands: bool + name: str | Literal[False] + version: str | Literal[False] + fullname: str | Literal[False] + author: str | Literal[False] + author_email: str | Literal[False] + maintainer: str | Literal[False] + maintainer_email: str | Literal[False] + contact: str | Literal[False] + contact_email: str | Literal[False] + url: str | Literal[False] + license: str | Literal[False] + licence: str | Literal[False] + description: str | Literal[False] + long_description: str | Literal[False] + platforms: str | list[str] | Literal[False] + classifiers: str | list[str] | Literal[False] + keywords: str | list[str] | Literal[False] + provides: list[str] | Literal[False] + requires: list[str] | Literal[False] + obsoletes: list[str] | Literal[False] + + +class DistributionMetadata: + """Dummy class to hold the distribution meta-data: name, version, + author, and so forth. + """ + + _METHOD_BASENAMES = ( + "name", + "version", + "author", + "author_email", + "maintainer", + "maintainer_email", + "url", + "license", + "description", + "long_description", + "keywords", + "platforms", + "fullname", + "contact", + "contact_email", + "classifiers", + "download_url", + # PEP 314 + "provides", + "requires", + "obsoletes", + ) + + def __init__( + self, path: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None + ) -> None: + if path is not None: + self.read_pkg_file(open(path)) + else: + self.name: str | None = None + self.version: str | None = None + self.author: str | None = None + self.author_email: str | None = None + self.maintainer: str | None = None + self.maintainer_email: str | None = None + self.url: str | None = None + self.license: str | None = None + self.description: str | None = None + self.long_description: str | None = None + self.keywords: str | list[str] | None = None + self.platforms: str | list[str] | None = None + self.classifiers: str | list[str] | None = None + self.download_url: str | None = None + # PEP 314 + self.provides: str | list[str] | None = None + self.requires: str | list[str] | None = None + self.obsoletes: str | list[str] | None = None + + def read_pkg_file(self, file: IO[str]) -> None: + """Reads the metadata values from a file object.""" + msg = message_from_file(file) + + def _read_field(name: str) -> str | None: + value = msg[name] + if value and value != "UNKNOWN": + return value + return None + + def _read_list(name): + values = msg.get_all(name, None) + if values == []: + return None + return values + + metadata_version = msg['metadata-version'] + self.name = _read_field('name') + self.version = _read_field('version') + self.description = _read_field('summary') + # we are filling author only. + self.author = _read_field('author') + self.maintainer = None + self.author_email = _read_field('author-email') + self.maintainer_email = None + self.url = _read_field('home-page') + self.license = _read_field('license') + + if 'download-url' in msg: + self.download_url = _read_field('download-url') + else: + self.download_url = None + + self.long_description = _read_field('description') + self.description = _read_field('summary') + + if 'keywords' in msg: + self.keywords = _read_field('keywords').split(',') + + self.platforms = _read_list('platform') + self.classifiers = _read_list('classifier') + + # PEP 314 - these fields only exist in 1.1 + if metadata_version == '1.1': + self.requires = _read_list('requires') + self.provides = _read_list('provides') + self.obsoletes = _read_list('obsoletes') + else: + self.requires = None + self.provides = None + self.obsoletes = None + + def write_pkg_info(self, base_dir: str | os.PathLike[str]) -> None: + """Write the PKG-INFO file into the release tree.""" + with open( + os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8' + ) as pkg_info: + self.write_pkg_file(pkg_info) + + def write_pkg_file(self, file: SupportsWrite[str]) -> None: + """Write the PKG-INFO format data to a file object.""" + version = '1.0' + if ( + self.provides + or self.requires + or self.obsoletes + or self.classifiers + or self.download_url + ): + version = '1.1' + + # required fields + file.write(f'Metadata-Version: {version}\n') + file.write(f'Name: {self.get_name()}\n') + file.write(f'Version: {self.get_version()}\n') + + def maybe_write(header, val): + if val: + file.write(f"{header}: {val}\n") + + # optional fields + maybe_write("Summary", self.get_description()) + maybe_write("Home-page", self.get_url()) + maybe_write("Author", self.get_contact()) + maybe_write("Author-email", self.get_contact_email()) + maybe_write("License", self.get_license()) + maybe_write("Download-URL", self.download_url) + maybe_write("Description", rfc822_escape(self.get_long_description() or "")) + maybe_write("Keywords", ",".join(self.get_keywords())) + + self._write_list(file, 'Platform', self.get_platforms()) + self._write_list(file, 'Classifier', self.get_classifiers()) + + # PEP 314 + self._write_list(file, 'Requires', self.get_requires()) + self._write_list(file, 'Provides', self.get_provides()) + self._write_list(file, 'Obsoletes', self.get_obsoletes()) + + def _write_list(self, file, name, values): + values = values or [] + for value in values: + file.write(f'{name}: {value}\n') + + # -- Metadata query methods ---------------------------------------- + + def get_name(self) -> str: + return self.name or "UNKNOWN" + + def get_version(self) -> str: + return self.version or "0.0.0" + + def get_fullname(self) -> str: + return self._fullname(self.get_name(), self.get_version()) + + @staticmethod + def _fullname(name: str, version: str) -> str: + """ + >>> DistributionMetadata._fullname('setup.tools', '1.0-2') + 'setup_tools-1.0.post2' + >>> DistributionMetadata._fullname('setup-tools', '1.2post2') + 'setup_tools-1.2.post2' + >>> DistributionMetadata._fullname('setup-tools', '1.0-r2') + 'setup_tools-1.0.post2' + >>> DistributionMetadata._fullname('setup.tools', '1.0.post') + 'setup_tools-1.0.post0' + >>> DistributionMetadata._fullname('setup.tools', '1.0+ubuntu-1') + 'setup_tools-1.0+ubuntu.1' + """ + return "{}-{}".format( + canonicalize_name(name).replace('-', '_'), + canonicalize_version(version, strip_trailing_zero=False), + ) + + def get_author(self) -> str | None: + return self.author + + def get_author_email(self) -> str | None: + return self.author_email + + def get_maintainer(self) -> str | None: + return self.maintainer + + def get_maintainer_email(self) -> str | None: + return self.maintainer_email + + def get_contact(self) -> str | None: + return self.maintainer or self.author + + def get_contact_email(self) -> str | None: + return self.maintainer_email or self.author_email + + def get_url(self) -> str | None: + return self.url + + def get_license(self) -> str | None: + return self.license + + get_licence = get_license + + def get_description(self) -> str | None: + return self.description + + def get_long_description(self) -> str | None: + return self.long_description + + def get_keywords(self) -> str | list[str]: + return self.keywords or [] + + def set_keywords(self, value: str | Iterable[str]) -> None: + self.keywords = _ensure_list(value, 'keywords') + + def get_platforms(self) -> str | list[str] | None: + return self.platforms + + def set_platforms(self, value: str | Iterable[str]) -> None: + self.platforms = _ensure_list(value, 'platforms') + + def get_classifiers(self) -> str | list[str]: + return self.classifiers or [] + + def set_classifiers(self, value: str | Iterable[str]) -> None: + self.classifiers = _ensure_list(value, 'classifiers') + + def get_download_url(self) -> str | None: + return self.download_url + + # PEP 314 + def get_requires(self) -> str | list[str]: + return self.requires or [] + + def set_requires(self, value: Iterable[str]) -> None: + import distutils.versionpredicate + + for v in value: + distutils.versionpredicate.VersionPredicate(v) + self.requires = list(value) + + def get_provides(self) -> str | list[str]: + return self.provides or [] + + def set_provides(self, value: Iterable[str]) -> None: + value = [v.strip() for v in value] + for v in value: + import distutils.versionpredicate + + distutils.versionpredicate.split_provision(v) + self.provides = value + + def get_obsoletes(self) -> str | list[str]: + return self.obsoletes or [] + + def set_obsoletes(self, value: Iterable[str]) -> None: + import distutils.versionpredicate + + for v in value: + distutils.versionpredicate.VersionPredicate(v) + self.obsoletes = list(value) + + +def fix_help_options(options): + """Convert a 4-tuple 'help_options' list as found in various command + classes to the 3-tuple form required by FancyGetopt. + """ + return [opt[0:3] for opt in options] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/errors.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..409d21faa2caeb8a53fed10e4266f7cccc764d23 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/errors.py @@ -0,0 +1,108 @@ +""" +Exceptions used by the Distutils modules. + +Distutils modules may raise these or standard exceptions, +including :exc:`SystemExit`. +""" + +# compiler exceptions aliased for compatibility +from .compilers.C.errors import CompileError as CompileError +from .compilers.C.errors import Error as _Error +from .compilers.C.errors import LibError as LibError +from .compilers.C.errors import LinkError as LinkError +from .compilers.C.errors import PreprocessError as PreprocessError +from .compilers.C.errors import UnknownFileType as _UnknownFileType + +CCompilerError = _Error +UnknownFileError = _UnknownFileType + + +class DistutilsError(Exception): + """The root of all Distutils evil.""" + + pass + + +class DistutilsModuleError(DistutilsError): + """Unable to load an expected module, or to find an expected class + within some module (in particular, command modules and classes).""" + + pass + + +class DistutilsClassError(DistutilsError): + """Some command class (or possibly distribution class, if anyone + feels a need to subclass Distribution) is found not to be holding + up its end of the bargain, ie. implementing some part of the + "command "interface.""" + + pass + + +class DistutilsGetoptError(DistutilsError): + """The option table provided to 'fancy_getopt()' is bogus.""" + + pass + + +class DistutilsArgError(DistutilsError): + """Raised by fancy_getopt in response to getopt.error -- ie. an + error in the command line usage.""" + + pass + + +class DistutilsFileError(DistutilsError): + """Any problems in the filesystem: expected file not found, etc. + Typically this is for problems that we detect before OSError + could be raised.""" + + pass + + +class DistutilsOptionError(DistutilsError): + """Syntactic/semantic errors in command options, such as use of + mutually conflicting options, or inconsistent options, + badly-spelled values, etc. No distinction is made between option + values originating in the setup script, the command line, config + files, or what-have-you -- but if we *know* something originated in + the setup script, we'll raise DistutilsSetupError instead.""" + + pass + + +class DistutilsSetupError(DistutilsError): + """For errors that can be definitely blamed on the setup script, + such as invalid keyword arguments to 'setup()'.""" + + pass + + +class DistutilsPlatformError(DistutilsError): + """We don't know how to do something on the current platform (but + we do know how to do it on some platform) -- eg. trying to compile + C files on a platform not supported by a CCompiler subclass.""" + + pass + + +class DistutilsExecError(DistutilsError): + """Any problems executing an external program (such as the C + compiler, when compiling C files).""" + + pass + + +class DistutilsInternalError(DistutilsError): + """Internal inconsistencies or impossibilities (obviously, this + should never be seen if the code is working!).""" + + pass + + +class DistutilsTemplateError(DistutilsError): + """Syntax error in a file list template.""" + + +class DistutilsByteCompileError(DistutilsError): + """Byte compile error.""" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/extension.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/extension.py new file mode 100644 index 0000000000000000000000000000000000000000..f51411266e4047275280d883b75e7103af21faef --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/extension.py @@ -0,0 +1,258 @@ +"""distutils.extension + +Provides the Extension class, used to describe C/C++ extension +modules in setup scripts.""" + +from __future__ import annotations + +import os +import warnings +from collections.abc import Iterable + +# This class is really only used by the "build_ext" command, so it might +# make sense to put it in distutils.command.build_ext. However, that +# module is already big enough, and I want to make this class a bit more +# complex to simplify some common cases ("foo" module in "foo.c") and do +# better error-checking ("foo.c" actually exists). +# +# Also, putting this in build_ext.py means every setup script would have to +# import that large-ish module (indirectly, through distutils.core) in +# order to do anything. + + +class Extension: + """Just a collection of attributes that describes an extension + module and everything needed to build it (hopefully in a portable + way, but there are hooks that let you be as unportable as you need). + + Instance attributes: + name : string + the full name of the extension, including any packages -- ie. + *not* a filename or pathname, but Python dotted name + sources : Iterable[string | os.PathLike] + iterable of source filenames (except strings, which could be misinterpreted + as a single filename), relative to the distribution root (where the setup + script lives), in Unix form (slash-separated) for portability. Can be any + non-string iterable (list, tuple, set, etc.) containing strings or + PathLike objects. 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. + include_dirs : [string] + list of directories to search for C/C++ header files (in Unix + form for portability) + define_macros : [(name : string, value : string|None)] + list of macros to define; each macro is defined using a 2-tuple, + where 'value' is either the string to define it to or None to + define it without a particular value (equivalent of "#define + FOO" in source or -DFOO on Unix C compiler command line) + undef_macros : [string] + list of macros to undefine explicitly + library_dirs : [string] + list of directories to search for C/C++ libraries at link time + libraries : [string] + list of library names (not filenames or paths) to link against + runtime_library_dirs : [string] + list of directories to search for C/C++ libraries at run time + (for shared extensions, this is when the extension is loaded) + extra_objects : [string] + 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.) + extra_compile_args : [string] + 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. + extra_link_args : [string] + 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'. + export_symbols : [string] + 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. + swig_opts : [string] + any extra options to pass to SWIG if a source file has the .i + extension. + depends : [string] + list of files that the extension depends on + language : string + extension language (i.e. "c", "c++", "objc"). Will be detected + from the source extensions if not provided. + optional : boolean + specifies that a build failure in the extension should not abort the + build process, but simply not install the failing extension. + """ + + # When adding arguments to this constructor, be sure to update + # setup_keywords in core.py. + def __init__( + self, + name: str, + sources: Iterable[str | os.PathLike[str]], + include_dirs: list[str] | None = None, + define_macros: list[tuple[str, str | None]] | None = None, + undef_macros: list[str] | None = None, + library_dirs: list[str] | None = None, + libraries: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + extra_objects: list[str] | None = None, + extra_compile_args: list[str] | None = None, + extra_link_args: list[str] | None = None, + export_symbols: list[str] | None = None, + swig_opts: list[str] | None = None, + depends: list[str] | None = None, + language: str | None = None, + optional: bool | None = None, + **kw, # To catch unknown keywords + ): + if not isinstance(name, str): + raise TypeError("'name' must be a string") + + # handle the string case first; since strings are iterable, disallow them + if isinstance(sources, str): + raise TypeError( + "'sources' must be an iterable of strings or PathLike objects, not a string" + ) + + # now we check if it's iterable and contains valid types + try: + self.sources = list(map(os.fspath, sources)) + except TypeError: + raise TypeError( + "'sources' must be an iterable of strings or PathLike objects" + ) + + self.name = name + self.include_dirs = include_dirs or [] + self.define_macros = define_macros or [] + self.undef_macros = undef_macros or [] + self.library_dirs = library_dirs or [] + self.libraries = libraries or [] + self.runtime_library_dirs = runtime_library_dirs or [] + self.extra_objects = extra_objects or [] + self.extra_compile_args = extra_compile_args or [] + self.extra_link_args = extra_link_args or [] + self.export_symbols = export_symbols or [] + self.swig_opts = swig_opts or [] + self.depends = depends or [] + self.language = language + self.optional = optional + + # If there are unknown keyword options, warn about them + if len(kw) > 0: + options = [repr(option) for option in kw] + options = ', '.join(sorted(options)) + msg = f"Unknown Extension options: {options}" + warnings.warn(msg) + + def __repr__(self): + return f'<{self.__class__.__module__}.{self.__class__.__qualname__}({self.name!r}) at {id(self):#x}>' + + +def read_setup_file(filename): # noqa: C901 + """Reads a Setup file and returns Extension instances.""" + from distutils.sysconfig import _variable_rx, expand_makefile_vars, parse_makefile + from distutils.text_file import TextFile + from distutils.util import split_quoted + + # First pass over the file to gather "VAR = VALUE" assignments. + vars = parse_makefile(filename) + + # Second pass to gobble up the real content: lines of the form + # ... [ ...] [ ...] [ ...] + file = TextFile( + filename, + strip_comments=True, + skip_blanks=True, + join_lines=True, + lstrip_ws=True, + rstrip_ws=True, + ) + try: + extensions = [] + + while True: + line = file.readline() + if line is None: # eof + break + if _variable_rx.match(line): # VAR=VALUE, handled in first pass + continue + + if line[0] == line[-1] == "*": + file.warn(f"'{line}' lines not handled yet") + continue + + line = expand_makefile_vars(line, vars) + words = split_quoted(line) + + # NB. this parses a slightly different syntax than the old + # makesetup script: here, there must be exactly one extension per + # line, and it must be the first word of the line. I have no idea + # why the old syntax supported multiple extensions per line, as + # they all wind up being the same. + + module = words[0] + ext = Extension(module, []) + append_next_word = None + + for word in words[1:]: + if append_next_word is not None: + append_next_word.append(word) + append_next_word = None + continue + + suffix = os.path.splitext(word)[1] + switch = word[0:2] + value = word[2:] + + if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"): + # hmm, should we do something about C vs. C++ sources? + # or leave it up to the CCompiler implementation to + # worry about? + ext.sources.append(word) + elif switch == "-I": + ext.include_dirs.append(value) + elif switch == "-D": + equals = value.find("=") + if equals == -1: # bare "-DFOO" -- no value + ext.define_macros.append((value, None)) + else: # "-DFOO=blah" + ext.define_macros.append((value[0:equals], value[equals + 2 :])) + elif switch == "-U": + ext.undef_macros.append(value) + elif switch == "-C": # only here 'cause makesetup has it! + ext.extra_compile_args.append(word) + elif switch == "-l": + ext.libraries.append(value) + elif switch == "-L": + ext.library_dirs.append(value) + elif switch == "-R": + ext.runtime_library_dirs.append(value) + elif word == "-rpath": + append_next_word = ext.runtime_library_dirs + elif word == "-Xlinker": + append_next_word = ext.extra_link_args + elif word == "-Xcompiler": + append_next_word = ext.extra_compile_args + elif switch == "-u": + ext.extra_link_args.append(word) + if not value: + append_next_word = ext.extra_link_args + elif suffix in (".a", ".so", ".sl", ".o", ".dylib"): + # NB. a really faithful emulation of makesetup would + # append a .o file to extra_objects only if it + # had a slash in it; otherwise, it would s/.o/.c/ + # and append it to sources. Hmmmm. + ext.extra_objects.append(word) + else: + file.warn(f"unrecognized argument '{word}'") + + extensions.append(ext) + finally: + file.close() + + return extensions diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/fancy_getopt.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/fancy_getopt.py new file mode 100644 index 0000000000000000000000000000000000000000..1a1d3a05da544b98ff84d03ecbee1185b2eb45f7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/fancy_getopt.py @@ -0,0 +1,471 @@ +"""distutils.fancy_getopt + +Wrapper around the standard getopt module that provides the following +additional features: + * short and long options are tied together + * options have help strings, so fancy_getopt could potentially + create a complete usage summary + * options set attributes of a passed-in object +""" + +from __future__ import annotations + +import getopt +import re +import string +import sys +from collections.abc import Sequence +from typing import Any + +from .errors import DistutilsArgError, DistutilsGetoptError + +# Much like command_re in distutils.core, this is close to but not quite +# the same as a Python NAME -- except, in the spirit of most GNU +# utilities, we use '-' in place of '_'. (The spirit of LISP lives on!) +# The similarities to NAME are again not a coincidence... +longopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)' +longopt_re = re.compile(rf'^{longopt_pat}$') + +# For recognizing "negative alias" options, eg. "quiet=!verbose" +neg_alias_re = re.compile(f"^({longopt_pat})=!({longopt_pat})$") + +# This is used to translate long options to legitimate Python identifiers +# (for use as attributes of some object). +longopt_xlate = str.maketrans('-', '_') + + +class FancyGetopt: + """Wrapper around the standard 'getopt()' module that provides some + handy extra functionality: + * short and long options are tied together + * options have help strings, and help text can be assembled + from them + * options set attributes of a passed-in object + * boolean options can have "negative aliases" -- eg. if + --quiet is the "negative alias" of --verbose, then "--quiet" + on the command line sets 'verbose' to false + """ + + def __init__(self, option_table=None): + # The option table is (currently) a list of tuples. The + # tuples may have 3 or four values: + # (long_option, short_option, help_string [, repeatable]) + # if an option takes an argument, its long_option should have '=' + # appended; short_option should just be a single character, no ':' + # in any case. If a long_option doesn't have a corresponding + # short_option, short_option should be None. All option tuples + # must have long options. + self.option_table = option_table + + # 'option_index' maps long option names to entries in the option + # table (ie. those 3-tuples). + self.option_index = {} + if self.option_table: + self._build_index() + + # 'alias' records (duh) alias options; {'foo': 'bar'} means + # --foo is an alias for --bar + self.alias = {} + + # 'negative_alias' keeps track of options that are the boolean + # opposite of some other option + self.negative_alias = {} + + # These keep track of the information in the option table. We + # don't actually populate these structures until we're ready to + # parse the command-line, since the 'option_table' passed in here + # isn't necessarily the final word. + self.short_opts = [] + self.long_opts = [] + self.short2long = {} + self.attr_name = {} + self.takes_arg = {} + + # And 'option_order' is filled up in 'getopt()'; it records the + # original order of options (and their values) on the command-line, + # but expands short options, converts aliases, etc. + self.option_order = [] + + def _build_index(self): + self.option_index.clear() + for option in self.option_table: + self.option_index[option[0]] = option + + def set_option_table(self, option_table): + self.option_table = option_table + self._build_index() + + def add_option(self, long_option, short_option=None, help_string=None): + if long_option in self.option_index: + raise DistutilsGetoptError( + f"option conflict: already an option '{long_option}'" + ) + else: + option = (long_option, short_option, help_string) + self.option_table.append(option) + self.option_index[long_option] = option + + def has_option(self, long_option): + """Return true if the option table for this parser has an + option with long name 'long_option'.""" + return long_option in self.option_index + + def get_attr_name(self, long_option): + """Translate long option name 'long_option' to the form it + has as an attribute of some object: ie., translate hyphens + to underscores.""" + return long_option.translate(longopt_xlate) + + def _check_alias_dict(self, aliases, what): + assert isinstance(aliases, dict) + for alias, opt in aliases.items(): + if alias not in self.option_index: + raise DistutilsGetoptError( + f"invalid {what} '{alias}': option '{alias}' not defined" + ) + if opt not in self.option_index: + raise DistutilsGetoptError( + f"invalid {what} '{alias}': aliased option '{opt}' not defined" + ) + + def set_aliases(self, alias): + """Set the aliases for this option parser.""" + self._check_alias_dict(alias, "alias") + self.alias = alias + + def set_negative_aliases(self, negative_alias): + """Set the negative aliases for this option parser. + 'negative_alias' should be a dictionary mapping option names to + option names, both the key and value must already be defined + in the option table.""" + self._check_alias_dict(negative_alias, "negative alias") + self.negative_alias = negative_alias + + def _grok_option_table(self): # noqa: C901 + """Populate the various data structures that keep tabs on the + option table. Called by 'getopt()' before it can do anything + worthwhile. + """ + self.long_opts = [] + self.short_opts = [] + self.short2long.clear() + self.repeat = {} + + for option in self.option_table: + if len(option) == 3: + long, short, help = option + repeat = 0 + elif len(option) == 4: + long, short, help, repeat = option + else: + # the option table is part of the code, so simply + # assert that it is correct + raise ValueError(f"invalid option tuple: {option!r}") + + # Type- and value-check the option names + if not isinstance(long, str) or len(long) < 2: + raise DistutilsGetoptError( + f"invalid long option '{long}': must be a string of length >= 2" + ) + + if not ((short is None) or (isinstance(short, str) and len(short) == 1)): + raise DistutilsGetoptError( + f"invalid short option '{short}': must a single character or None" + ) + + self.repeat[long] = repeat + self.long_opts.append(long) + + if long[-1] == '=': # option takes an argument? + if short: + short = short + ':' + long = long[0:-1] + self.takes_arg[long] = True + else: + # Is option is a "negative alias" for some other option (eg. + # "quiet" == "!verbose")? + alias_to = self.negative_alias.get(long) + if alias_to is not None: + if self.takes_arg[alias_to]: + raise DistutilsGetoptError( + f"invalid negative alias '{long}': " + f"aliased option '{alias_to}' takes a value" + ) + + self.long_opts[-1] = long # XXX redundant?! + self.takes_arg[long] = False + + # If this is an alias option, make sure its "takes arg" flag is + # the same as the option it's aliased to. + alias_to = self.alias.get(long) + if alias_to is not None: + if self.takes_arg[long] != self.takes_arg[alias_to]: + raise DistutilsGetoptError( + f"invalid alias '{long}': inconsistent with " + f"aliased option '{alias_to}' (one of them takes a value, " + "the other doesn't" + ) + + # Now enforce some bondage on the long option name, so we can + # later translate it to an attribute name on some object. Have + # to do this a bit late to make sure we've removed any trailing + # '='. + if not longopt_re.match(long): + raise DistutilsGetoptError( + f"invalid long option name '{long}' " + "(must be letters, numbers, hyphens only" + ) + + self.attr_name[long] = self.get_attr_name(long) + if short: + self.short_opts.append(short) + self.short2long[short[0]] = long + + def getopt(self, args: Sequence[str] | None = None, object=None): # noqa: C901 + """Parse command-line options in args. Store as attributes on object. + + If 'args' is None or not supplied, uses 'sys.argv[1:]'. If + 'object' is None or not supplied, creates a new OptionDummy + object, stores option values there, and returns a tuple (args, + object). If 'object' is supplied, it is modified in place and + 'getopt()' just returns 'args'; in both cases, the returned + 'args' is a modified copy of the passed-in 'args' list, which + is left untouched. + """ + if args is None: + args = sys.argv[1:] + if object is None: + object = OptionDummy() + created_object = True + else: + created_object = False + + self._grok_option_table() + + short_opts = ' '.join(self.short_opts) + try: + opts, args = getopt.getopt(args, short_opts, self.long_opts) + except getopt.error as msg: + raise DistutilsArgError(msg) + + for opt, val in opts: + if len(opt) == 2 and opt[0] == '-': # it's a short option + opt = self.short2long[opt[1]] + else: + assert len(opt) > 2 and opt[:2] == '--' + opt = opt[2:] + + alias = self.alias.get(opt) + if alias: + opt = alias + + if not self.takes_arg[opt]: # boolean option? + assert val == '', "boolean option can't have value" + alias = self.negative_alias.get(opt) + if alias: + opt = alias + val = 0 + else: + val = 1 + + attr = self.attr_name[opt] + # The only repeating option at the moment is 'verbose'. + # It has a negative option -q quiet, which should set verbose = False. + if val and self.repeat.get(attr) is not None: + val = getattr(object, attr, 0) + 1 + setattr(object, attr, val) + self.option_order.append((opt, val)) + + # for opts + if created_object: + return args, object + else: + return args + + def get_option_order(self): + """Returns the list of (option, value) tuples processed by the + previous run of 'getopt()'. Raises RuntimeError if + 'getopt()' hasn't been called yet. + """ + if self.option_order is None: + raise RuntimeError("'getopt()' hasn't been called yet") + else: + return self.option_order + + def generate_help(self, header=None): # noqa: C901 + """Generate help text (a list of strings, one per suggested line of + output) from the option table for this FancyGetopt object. + """ + # Blithely assume the option table is good: probably wouldn't call + # 'generate_help()' unless you've already called 'getopt()'. + + # First pass: determine maximum length of long option names + max_opt = 0 + for option in self.option_table: + long = option[0] + short = option[1] + ell = len(long) + if long[-1] == '=': + ell = ell - 1 + if short is not None: + ell = ell + 5 # " (-x)" where short == 'x' + if ell > max_opt: + max_opt = ell + + opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter + + # Typical help block looks like this: + # --foo controls foonabulation + # Help block for longest option looks like this: + # --flimflam set the flim-flam level + # and with wrapped text: + # --flimflam set the flim-flam level (must be between + # 0 and 100, except on Tuesdays) + # Options with short names will have the short name shown (but + # it doesn't contribute to max_opt): + # --foo (-f) controls foonabulation + # If adding the short option would make the left column too wide, + # we push the explanation off to the next line + # --flimflam (-l) + # set the flim-flam level + # Important parameters: + # - 2 spaces before option block start lines + # - 2 dashes for each long option name + # - min. 2 spaces between option and explanation (gutter) + # - 5 characters (incl. space) for short option name + + # Now generate lines of help text. (If 80 columns were good enough + # for Jesus, then 78 columns are good enough for me!) + line_width = 78 + text_width = line_width - opt_width + big_indent = ' ' * opt_width + if header: + lines = [header] + else: + lines = ['Option summary:'] + + for option in self.option_table: + long, short, help = option[:3] + text = wrap_text(help, text_width) + if long[-1] == '=': + long = long[0:-1] + + # Case 1: no short option at all (makes life easy) + if short is None: + if text: + lines.append(f" --{long:<{max_opt}} {text[0]}") + else: + lines.append(f" --{long:<{max_opt}}") + + # Case 2: we have a short option, so we have to include it + # just after the long option + else: + opt_names = f"{long} (-{short})" + if text: + lines.append(f" --{opt_names:<{max_opt}} {text[0]}") + else: + lines.append(f" --{opt_names:<{max_opt}}") + + for ell in text[1:]: + lines.append(big_indent + ell) + return lines + + def print_help(self, header=None, file=None): + if file is None: + file = sys.stdout + for line in self.generate_help(header): + file.write(line + "\n") + + +def fancy_getopt(options, negative_opt, object, args: Sequence[str] | None): + parser = FancyGetopt(options) + parser.set_negative_aliases(negative_opt) + return parser.getopt(args, object) + + +WS_TRANS = {ord(_wschar): ' ' for _wschar in string.whitespace} + + +def wrap_text(text, width): + """wrap_text(text : string, width : int) -> [string] + + Split 'text' into multiple lines of no more than 'width' characters + each, and return the list of strings that results. + """ + if text is None: + return [] + if len(text) <= width: + return [text] + + text = text.expandtabs() + text = text.translate(WS_TRANS) + chunks = re.split(r'( +|-+)', text) + chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings + lines = [] + + while chunks: + cur_line = [] # list of chunks (to-be-joined) + cur_len = 0 # length of current line + + while chunks: + ell = len(chunks[0]) + if cur_len + ell <= width: # can squeeze (at least) this chunk in + cur_line.append(chunks[0]) + del chunks[0] + cur_len = cur_len + ell + else: # this line is full + # drop last chunk if all space + if cur_line and cur_line[-1][0] == ' ': + del cur_line[-1] + break + + if chunks: # any chunks left to process? + # if the current line is still empty, then we had a single + # chunk that's too big too fit on a line -- so we break + # down and break it up at the line width + if cur_len == 0: + cur_line.append(chunks[0][0:width]) + chunks[0] = chunks[0][width:] + + # all-whitespace chunks at the end of a line can be discarded + # (and we know from the re.split above that if a chunk has + # *any* whitespace, it is *all* whitespace) + if chunks[0][0] == ' ': + del chunks[0] + + # and store this line in the list-of-all-lines -- as a single + # string, of course! + lines.append(''.join(cur_line)) + + return lines + + +def translate_longopt(opt): + """Convert a long option name to a valid Python identifier by + changing "-" to "_". + """ + return opt.translate(longopt_xlate) + + +class OptionDummy: + """Dummy class just used as a place to hold command-line option + values as instance attributes.""" + + def __init__(self, options: Sequence[Any] = []): + """Create a new OptionDummy instance. The attributes listed in + 'options' will be initialized to None.""" + for opt in options: + setattr(self, opt, None) + + +if __name__ == "__main__": + text = """\ +Tra-la-la, supercalifragilisticexpialidocious. +How *do* you spell that odd word, anyways? +(Someone ask Mary -- she'll know [or she'll +say, "How should I know?"].)""" + + for w in (10, 20, 30, 40): + print(f"width: {w}") + print("\n".join(wrap_text(text, w))) + print() diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/file_util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/file_util.py new file mode 100644 index 0000000000000000000000000000000000000000..a9724b1779703543aaacc7b4a5872b68911d2144 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/file_util.py @@ -0,0 +1,228 @@ +"""distutils.file_util + +Utility functions for operating on single files. +""" + +import os + +from ._log import log +from .errors import DistutilsFileError + +# for generating verbose output in 'copy_file()' +_copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'} + + +def _copy_file_contents(src, dst, buffer_size=16 * 1024): # noqa: C901 + """Copy the file 'src' to 'dst'; both must be filenames. Any error + opening either file, reading from 'src', or writing to 'dst', raises + DistutilsFileError. Data is read/written in chunks of 'buffer_size' + bytes (default 16k). No attempt is made to handle anything apart from + regular files. + """ + # Stolen from shutil module in the standard library, but with + # custom error-handling added. + fsrc = None + fdst = None + try: + try: + fsrc = open(src, 'rb') + except OSError as e: + raise DistutilsFileError(f"could not open '{src}': {e.strerror}") + + if os.path.exists(dst): + try: + os.unlink(dst) + except OSError as e: + raise DistutilsFileError(f"could not delete '{dst}': {e.strerror}") + + try: + fdst = open(dst, 'wb') + except OSError as e: + raise DistutilsFileError(f"could not create '{dst}': {e.strerror}") + + while True: + try: + buf = fsrc.read(buffer_size) + except OSError as e: + raise DistutilsFileError(f"could not read from '{src}': {e.strerror}") + + if not buf: + break + + try: + fdst.write(buf) + except OSError as e: + raise DistutilsFileError(f"could not write to '{dst}': {e.strerror}") + finally: + if fdst: + fdst.close() + if fsrc: + fsrc.close() + + +def copy_file( # noqa: C901 + src, + dst, + preserve_mode=True, + preserve_times=True, + update=False, + link=None, + verbose=True, +): + """Copy a file 'src' to 'dst'. If 'dst' is a directory, then 'src' is + copied there with the same name; otherwise, it must be a filename. (If + the file exists, it will be ruthlessly clobbered.) If 'preserve_mode' + is true (the default), the file's mode (type and permission bits, or + whatever is analogous on the current platform) is copied. If + 'preserve_times' is true (the default), the last-modified and + last-access times are copied as well. If 'update' is true, 'src' will + only be copied if 'dst' does not exist, or if 'dst' does exist but is + older than 'src'. + + 'link' allows you to make hard links (os.link) or symbolic links + (os.symlink) instead of copying: set it to "hard" or "sym"; if it is + None (the default), files are copied. Don't set 'link' on systems that + don't support it: 'copy_file()' doesn't check if hard or symbolic + linking is available. If hardlink fails, falls back to + _copy_file_contents(). + + Under Mac OS, uses the native file copy function in macostools; on + other systems, uses '_copy_file_contents()' to copy file contents. + + Return a tuple (dest_name, copied): 'dest_name' is the actual name of + the output file, and 'copied' is true if the file was copied. + """ + # XXX if the destination file already exists, we clobber it if + # copying, but blow up if linking. Hmmm. And I don't know what + # macostools.copyfile() does. Should definitely be consistent, and + # should probably blow up if destination exists and we would be + # changing it (ie. it's not already a hard/soft link to src OR + # (not update) and (src newer than dst). + + from distutils._modified import newer + from stat import S_IMODE, ST_ATIME, ST_MODE, ST_MTIME + + if not os.path.isfile(src): + raise DistutilsFileError( + f"can't copy '{src}': doesn't exist or not a regular file" + ) + + if os.path.isdir(dst): + dir = dst + dst = os.path.join(dst, os.path.basename(src)) + else: + dir = os.path.dirname(dst) + + if update and not newer(src, dst): + if verbose >= 1: + log.debug("not copying %s (output up-to-date)", src) + return (dst, False) + + try: + action = _copy_action[link] + except KeyError: + raise ValueError(f"invalid value '{link}' for 'link' argument") + + if verbose >= 1: + if os.path.basename(dst) == os.path.basename(src): + log.info("%s %s -> %s", action, src, dir) + else: + log.info("%s %s -> %s", action, src, dst) + + # If linking (hard or symbolic), use the appropriate system call + # (Unix only, of course, but that's the caller's responsibility) + if link == 'hard': + if not (os.path.exists(dst) and os.path.samefile(src, dst)): + try: + os.link(src, dst) + except OSError: + # If hard linking fails, fall back on copying file + # (some special filesystems don't support hard linking + # even under Unix, see issue #8876). + pass + else: + return (dst, True) + elif link == 'sym': + if not (os.path.exists(dst) and os.path.samefile(src, dst)): + os.symlink(src, dst) + return (dst, True) + + # Otherwise (non-Mac, not linking), copy the file contents and + # (optionally) copy the times and mode. + _copy_file_contents(src, dst) + if preserve_mode or preserve_times: + st = os.stat(src) + + # According to David Ascher , utime() should be done + # before chmod() (at least under NT). + if preserve_times: + os.utime(dst, (st[ST_ATIME], st[ST_MTIME])) + if preserve_mode: + os.chmod(dst, S_IMODE(st[ST_MODE])) + + return (dst, True) + + +# XXX I suspect this is Unix-specific -- need porting help! +def move_file(src, dst, verbose=True): # noqa: C901 + """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will + be moved into it with the same name; otherwise, 'src' is just renamed + to 'dst'. Return the new full name of the file. + + Handles cross-device moves on Unix using 'copy_file()'. What about + other systems??? + """ + import errno + from os.path import basename, dirname, exists, isdir, isfile + + if verbose >= 1: + log.info("moving %s -> %s", src, dst) + + if not isfile(src): + raise DistutilsFileError(f"can't move '{src}': not a regular file") + + if isdir(dst): + dst = os.path.join(dst, basename(src)) + elif exists(dst): + raise DistutilsFileError( + f"can't move '{src}': destination '{dst}' already exists" + ) + + if not isdir(dirname(dst)): + raise DistutilsFileError( + f"can't move '{src}': destination '{dst}' not a valid path" + ) + + copy_it = False + try: + os.rename(src, dst) + except OSError as e: + (num, msg) = e.args + if num == errno.EXDEV: + copy_it = True + else: + raise DistutilsFileError(f"couldn't move '{src}' to '{dst}': {msg}") + + if copy_it: + copy_file(src, dst, verbose=verbose) + try: + os.unlink(src) + except OSError as e: + (num, msg) = e.args + try: + os.unlink(dst) + except OSError: + pass + raise DistutilsFileError( + f"couldn't move '{src}' to '{dst}' by copy/delete: " + f"delete '{src}' failed: {msg}" + ) + return dst + + +def write_file(filename, contents): + """Create a file with the specified name and write 'contents' (a + sequence of strings without line terminators) to it. + """ + with open(filename, 'w', encoding='utf-8') as f: + f.writelines(line + '\n' for line in contents) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/filelist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/filelist.py new file mode 100644 index 0000000000000000000000000000000000000000..70dc0fdebc3f4200245aa1c6280ab39861dcf8b0 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/filelist.py @@ -0,0 +1,431 @@ +"""distutils.filelist + +Provides the FileList class, used for poking about the filesystem +and building lists of files. +""" + +from __future__ import annotations + +import fnmatch +import functools +import os +import re +from collections.abc import Iterable +from typing import Literal, overload + +from ._log import log +from .errors import DistutilsInternalError, DistutilsTemplateError +from .util import convert_path + + +class FileList: + """A list of files built by on exploring the filesystem and filtered by + applying various patterns to what we find there. + + Instance attributes: + dir + directory from which files will be taken -- only used if + 'allfiles' not supplied to constructor + files + list of filenames currently being built/filtered/manipulated + allfiles + complete list of files under consideration (ie. without any + filtering applied) + """ + + def __init__(self, warn: object = None, debug_print: object = None) -> None: + # ignore argument to FileList, but keep them for backwards + # compatibility + self.allfiles: Iterable[str] | None = None + self.files: list[str] = [] + + def set_allfiles(self, allfiles: Iterable[str]) -> None: + self.allfiles = allfiles + + def findall(self, dir: str | os.PathLike[str] = os.curdir) -> None: + self.allfiles = findall(dir) + + def debug_print(self, msg: object) -> None: + """Print 'msg' to stdout if the global DEBUG (taken from the + DISTUTILS_DEBUG environment variable) flag is true. + """ + from distutils.debug import DEBUG + + if DEBUG: + print(msg) + + # Collection methods + + def append(self, item: str) -> None: + self.files.append(item) + + def extend(self, items: Iterable[str]) -> None: + self.files.extend(items) + + def sort(self) -> None: + # Not a strict lexical sort! + sortable_files = sorted(map(os.path.split, self.files)) + self.files = [] + for sort_tuple in sortable_files: + self.files.append(os.path.join(*sort_tuple)) + + # Other miscellaneous utility methods + + def remove_duplicates(self) -> None: + # Assumes list has been sorted! + for i in range(len(self.files) - 1, 0, -1): + if self.files[i] == self.files[i - 1]: + del self.files[i] + + # "File template" methods + + def _parse_template_line(self, line): + words = line.split() + action = words[0] + + patterns = dir = dir_pattern = None + + if action in ('include', 'exclude', 'global-include', 'global-exclude'): + if len(words) < 2: + raise DistutilsTemplateError( + f"'{action}' expects ..." + ) + patterns = [convert_path(w) for w in words[1:]] + elif action in ('recursive-include', 'recursive-exclude'): + if len(words) < 3: + raise DistutilsTemplateError( + f"'{action}' expects ..." + ) + dir = convert_path(words[1]) + patterns = [convert_path(w) for w in words[2:]] + elif action in ('graft', 'prune'): + if len(words) != 2: + raise DistutilsTemplateError( + f"'{action}' expects a single " + ) + dir_pattern = convert_path(words[1]) + else: + raise DistutilsTemplateError(f"unknown action '{action}'") + + return (action, patterns, dir, dir_pattern) + + def process_template_line(self, line: str) -> None: # noqa: C901 + # 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) + + # 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. + if action == 'include': + self.debug_print("include " + ' '.join(patterns)) + for pattern in patterns: + if not self.include_pattern(pattern, anchor=True): + log.warning("warning: no files found matching '%s'", pattern) + + elif action == 'exclude': + self.debug_print("exclude " + ' '.join(patterns)) + for pattern in patterns: + if not self.exclude_pattern(pattern, anchor=True): + log.warning( + "warning: no previously-included files found matching '%s'", + pattern, + ) + + elif action == 'global-include': + self.debug_print("global-include " + ' '.join(patterns)) + for pattern in patterns: + if not self.include_pattern(pattern, anchor=False): + log.warning( + ( + "warning: no files found matching '%s' " + "anywhere in distribution" + ), + pattern, + ) + + elif action == 'global-exclude': + self.debug_print("global-exclude " + ' '.join(patterns)) + for pattern in patterns: + if not self.exclude_pattern(pattern, anchor=False): + log.warning( + ( + "warning: no previously-included files matching " + "'%s' found anywhere in distribution" + ), + pattern, + ) + + elif action == 'recursive-include': + self.debug_print("recursive-include {} {}".format(dir, ' '.join(patterns))) + for pattern in patterns: + if not self.include_pattern(pattern, prefix=dir): + msg = "warning: no files found matching '%s' under directory '%s'" + log.warning(msg, pattern, dir) + + elif action == 'recursive-exclude': + self.debug_print("recursive-exclude {} {}".format(dir, ' '.join(patterns))) + for pattern in patterns: + if not self.exclude_pattern(pattern, prefix=dir): + log.warning( + ( + "warning: no previously-included files matching " + "'%s' found under directory '%s'" + ), + pattern, + dir, + ) + + elif action == 'graft': + self.debug_print("graft " + dir_pattern) + if not self.include_pattern(None, prefix=dir_pattern): + log.warning("warning: no directories found matching '%s'", dir_pattern) + + elif action == 'prune': + self.debug_print("prune " + dir_pattern) + if not self.exclude_pattern(None, prefix=dir_pattern): + log.warning( + ("no previously-included directories found matching '%s'"), + dir_pattern, + ) + else: + raise DistutilsInternalError( + f"this cannot happen: invalid action '{action}'" + ) + + # Filtering/selection methods + @overload + def include_pattern( + self, + pattern: str, + anchor: bool = True, + prefix: str | None = None, + is_regex: Literal[False] = False, + ) -> bool: ... + @overload + def include_pattern( + self, + pattern: str | re.Pattern[str], + anchor: bool = True, + prefix: str | None = None, + *, + is_regex: Literal[True], + ) -> bool: ... + @overload + def include_pattern( + self, + pattern: str | re.Pattern[str], + anchor: bool, + prefix: str | None, + is_regex: Literal[True], + ) -> bool: ... + def include_pattern( + self, + pattern: str | re.Pattern, + anchor: bool = True, + prefix: str | None = None, + is_regex: bool = False, + ) -> bool: + """Select strings (presumably filenames) from 'self.files' that + match 'pattern', a Unix-style wildcard (glob) pattern. Patterns + are not quite the same as implemented by the 'fnmatch' module: '*' + and '?' match non-special characters, where "special" is platform- + dependent: slash on Unix; colon, slash, and backslash on + DOS/Windows; and colon on Mac OS. + + If 'anchor' is true (the default), then the pattern match is more + stringent: "*.py" will match "foo.py" but not "foo/bar.py". If + 'anchor' is false, both of these will match. + + If 'prefix' is supplied, then only filenames starting with 'prefix' + (itself a pattern) and ending with 'pattern', with anything in between + them, will match. 'anchor' is ignored in this case. + + If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and + 'pattern' is assumed to be either a string containing a regex or a + regex object -- no translation is done, the regex is just compiled + and used as-is. + + Selected strings will be added to self.files. + + Return True if files are found, False otherwise. + """ + # XXX docstring lying about what the special chars are? + files_found = False + pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) + self.debug_print(f"include_pattern: applying regex r'{pattern_re.pattern}'") + + # delayed loading of allfiles list + if self.allfiles is None: + self.findall() + + for name in self.allfiles: + if pattern_re.search(name): + self.debug_print(" adding " + name) + self.files.append(name) + files_found = True + return files_found + + @overload + def exclude_pattern( + self, + pattern: str, + anchor: bool = True, + prefix: str | None = None, + is_regex: Literal[False] = False, + ) -> bool: ... + @overload + def exclude_pattern( + self, + pattern: str | re.Pattern[str], + anchor: bool = True, + prefix: str | None = None, + *, + is_regex: Literal[True], + ) -> bool: ... + @overload + def exclude_pattern( + self, + pattern: str | re.Pattern[str], + anchor: bool, + prefix: str | None, + is_regex: Literal[True], + ) -> bool: ... + def exclude_pattern( + self, + pattern: str | re.Pattern, + anchor: bool = True, + prefix: str | None = None, + is_regex: bool = False, + ) -> bool: + """Remove strings (presumably filenames) from 'files' that match + 'pattern'. Other parameters are the same as for + 'include_pattern()', above. + The list 'self.files' is modified in place. + Return True if files are found, False otherwise. + """ + files_found = False + pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) + self.debug_print(f"exclude_pattern: applying regex r'{pattern_re.pattern}'") + for i in range(len(self.files) - 1, -1, -1): + if pattern_re.search(self.files[i]): + self.debug_print(" removing " + self.files[i]) + del self.files[i] + files_found = True + return files_found + + +# Utility functions + + +def _find_all_simple(path): + """ + Find all files under 'path' + """ + all_unique = _UniqueDirs.filter(os.walk(path, followlinks=True)) + results = ( + os.path.join(base, file) for base, dirs, files in all_unique for file in files + ) + return filter(os.path.isfile, results) + + +class _UniqueDirs(set): + """ + Exclude previously-seen dirs from walk results, + avoiding infinite recursion. + Ref https://bugs.python.org/issue44497. + """ + + def __call__(self, walk_item): + """ + Given an item from an os.walk result, determine + if the item represents a unique dir for this instance + and if not, prevent further traversal. + """ + base, dirs, files = walk_item + stat = os.stat(base) + candidate = stat.st_dev, stat.st_ino + found = candidate in self + if found: + del dirs[:] + self.add(candidate) + return not found + + @classmethod + def filter(cls, items): + return filter(cls(), items) + + +def findall(dir: str | os.PathLike[str] = os.curdir): + """ + Find all files under 'dir' and return the list of full filenames. + Unless dir is '.', return full filenames with dir prepended. + """ + files = _find_all_simple(dir) + if dir == os.curdir: + make_rel = functools.partial(os.path.relpath, start=dir) + files = map(make_rel, files) + return list(files) + + +def glob_to_re(pattern): + """Translate a shell-like glob pattern to a regular expression; return + a string containing the regex. Differs from 'fnmatch.translate()' in + that '*' does not match "special characters" (which are + platform-specific). + """ + pattern_re = fnmatch.translate(pattern) + + # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which + # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix, + # and by extension they shouldn't match such "special characters" under + # any OS. So change all non-escaped dots in the RE to match any + # character except the special characters (currently: just os.sep). + sep = os.sep + if os.sep == '\\': + # we're using a regex to manipulate a regex, so we need + # to escape the backslash twice + sep = r'\\\\' + escaped = rf'\1[^{sep}]' + pattern_re = re.sub(r'((?= 2: + set_threshold(logging.DEBUG) + + +class Log(logging.Logger): + """distutils.log.Log is deprecated, please use an alternative from `logging`.""" + + def __init__(self, threshold=WARN): + warnings.warn(Log.__doc__) # avoid DeprecationWarning to ensure warn is shown + super().__init__(__name__, level=threshold) + + @property + def threshold(self): + return self.level + + @threshold.setter + def threshold(self, level): + self.setLevel(level) + + warn = logging.Logger.warning diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/spawn.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/spawn.py new file mode 100644 index 0000000000000000000000000000000000000000..e47f1d19272cdd5fb8daa67eff3e52c8c435cfde --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/spawn.py @@ -0,0 +1,130 @@ +"""distutils.spawn + +Provides the 'spawn()' function, a front-end to various platform- +specific functions for launching another program in a sub-process. +""" + +from __future__ import annotations + +import os +import platform +import shutil +import subprocess +import sys +import warnings +from collections.abc import Mapping, MutableSequence +from typing import TYPE_CHECKING, TypeVar, overload + +from ._log import log +from .debug import DEBUG +from .errors import DistutilsExecError + +if TYPE_CHECKING: + from subprocess import _ENV + + +_MappingT = TypeVar("_MappingT", bound=Mapping) + + +def _debug(cmd): + """ + Render a subprocess command differently depending on DEBUG. + """ + return cmd if DEBUG else cmd[0] + + +def _inject_macos_ver(env: _MappingT | None) -> _MappingT | dict[str, str | int] | None: + if platform.system() != 'Darwin': + return env + + from .util import MACOSX_VERSION_VAR, get_macosx_target_ver + + target_ver = get_macosx_target_ver() + update = {MACOSX_VERSION_VAR: target_ver} if target_ver else {} + return {**_resolve(env), **update} + + +@overload +def _resolve(env: None) -> os._Environ[str]: ... +@overload +def _resolve(env: _MappingT) -> _MappingT: ... +def _resolve(env: _MappingT | None) -> _MappingT | os._Environ[str]: + return os.environ if env is None else env + + +def spawn( + cmd: MutableSequence[bytes | str | os.PathLike[str]], + search_path: bool = True, + verbose: bool = False, + env: _ENV | None = None, +) -> None: + """Run another program, specified as a command list 'cmd', in a new process. + + 'cmd' is just the argument list for the new process, ie. + cmd[0] is the program to run and cmd[1:] are the rest of its arguments. + There is no way to run a program with a name different from that of its + executable. + + If 'search_path' is true (the default), the system's executable + search path will be used to find the program; otherwise, cmd[0] + must be the exact path to the executable. + + Raise DistutilsExecError if running the program fails in any way; just + return on success. + """ + log.info(subprocess.list2cmdline(cmd)) + + if search_path: + executable = shutil.which(cmd[0]) + if executable is not None: + cmd[0] = executable + + try: + subprocess.check_call(cmd, env=_inject_macos_ver(env)) + except OSError as exc: + raise DistutilsExecError( + f"command {_debug(cmd)!r} failed: {exc.args[-1]}" + ) from exc + except subprocess.CalledProcessError as err: + raise DistutilsExecError( + f"command {_debug(cmd)!r} failed with exit code {err.returncode}" + ) from err + + +def find_executable(executable: str, path: str | None = None) -> str | None: + """Tries to find 'executable' in the directories listed in 'path'. + + A string listing directories separated by 'os.pathsep'; defaults to + os.environ['PATH']. Returns the complete filename or None if not found. + """ + warnings.warn( + 'Use shutil.which instead of find_executable', DeprecationWarning, stacklevel=2 + ) + _, ext = os.path.splitext(executable) + if (sys.platform == 'win32') and (ext != '.exe'): + executable = executable + '.exe' + + if os.path.isfile(executable): + return executable + + if path is None: + path = os.environ.get('PATH', None) + # bpo-35755: Don't fall through if PATH is the empty string + if path is None: + try: + path = os.confstr("CS_PATH") + except (AttributeError, ValueError): + # os.confstr() or CS_PATH is not available + path = os.defpath + + # PATH='' doesn't match, whereas PATH=':' looks in the current directory + if not path: + return None + + paths = path.split(os.pathsep) + for p in paths: + f = os.path.join(p, executable) + if os.path.isfile(f): + # the file exists, we have a shot at spawn working + return f + return None diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/sysconfig.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/sysconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..7ddc869ab5603d691a8863988da89ec84689de84 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/sysconfig.py @@ -0,0 +1,598 @@ +"""Provide access to Python's configuration information. The specific +configuration variables available depend heavily on the platform and +configuration. The values may be retrieved using +get_config_var(name), and the list of variables is available via +get_config_vars().keys(). Additional convenience functions are also +available. + +Written by: Fred L. Drake, Jr. +Email: +""" + +from __future__ import annotations + +import functools +import os +import pathlib +import re +import sys +import sysconfig +from typing import TYPE_CHECKING, Literal, overload + +from jaraco.functools import pass_none + +from .ccompiler import CCompiler +from .compat import py39 +from .errors import DistutilsPlatformError +from .util import is_mingw + +if TYPE_CHECKING: + from typing_extensions import deprecated +else: + + def deprecated(message): + return lambda fn: fn + + +IS_PYPY = '__pypy__' in sys.builtin_module_names + +# These are needed in a couple of spots, so just compute them once. +PREFIX = os.path.normpath(sys.prefix) +EXEC_PREFIX = os.path.normpath(sys.exec_prefix) +BASE_PREFIX = os.path.normpath(sys.base_prefix) +BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix) + +# Path to the base directory of the project. On Windows the binary may +# live in project/PCbuild/win32 or project/PCbuild/amd64. +# set for cross builds +if "_PYTHON_PROJECT_BASE" in os.environ: + project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"]) +else: + if sys.executable: + project_base = os.path.dirname(os.path.abspath(sys.executable)) + else: + # sys.executable can be empty if argv[0] has been changed and Python is + # unable to retrieve the real program name + project_base = os.getcwd() + + +def _is_python_source_dir(d): + """ + Return True if the target directory appears to point to an + un-installed Python. + """ + modules = pathlib.Path(d).joinpath('Modules') + return any(modules.joinpath(fn).is_file() for fn in ('Setup', 'Setup.local')) + + +_sys_home = getattr(sys, '_home', None) + + +def _is_parent(dir_a, dir_b): + """ + Return True if a is a parent of b. + """ + return os.path.normcase(dir_a).startswith(os.path.normcase(dir_b)) + + +if os.name == 'nt': + + @pass_none + def _fix_pcbuild(d): + # In a venv, sys._home will be inside BASE_PREFIX rather than PREFIX. + prefixes = PREFIX, BASE_PREFIX + matched = ( + prefix + for prefix in prefixes + if _is_parent(d, os.path.join(prefix, "PCbuild")) + ) + return next(matched, d) + + project_base = _fix_pcbuild(project_base) + _sys_home = _fix_pcbuild(_sys_home) + + +def _python_build(): + if _sys_home: + return _is_python_source_dir(_sys_home) + return _is_python_source_dir(project_base) + + +python_build = _python_build() + + +# Calculate the build qualifier flags if they are defined. Adding the flags +# to the include and lib directories only makes sense for an installation, not +# an in-source build. +build_flags = '' +try: + if not python_build: + build_flags = sys.abiflags +except AttributeError: + # It's not a configure-based build, so the sys module doesn't have + # this attribute, which is fine. + pass + + +def get_python_version(): + """Return a string containing the major and minor Python version, + leaving off the patchlevel. Sample return values could be '1.5' + or '2.2'. + """ + return f'{sys.version_info.major}.{sys.version_info.minor}' + + +def get_python_inc(plat_specific: bool = False, prefix: str | None = None) -> str: + """Return the directory containing installed Python header files. + + If 'plat_specific' is false (the default), this is the path to the + non-platform-specific header files, i.e. Python.h and so on; + otherwise, this is the path to platform-specific header files + (namely pyconfig.h). + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + """ + default_prefix = BASE_EXEC_PREFIX if plat_specific else BASE_PREFIX + resolved_prefix = prefix if prefix is not None else default_prefix + # MinGW imitates posix like layout, but os.name != posix + os_name = "posix" if is_mingw() else os.name + try: + getter = globals()[f'_get_python_inc_{os_name}'] + except KeyError: + raise DistutilsPlatformError( + "I don't know where Python installs its C header files " + f"on platform '{os.name}'" + ) + return getter(resolved_prefix, prefix, plat_specific) + + +@pass_none +def _extant(path): + """ + Replace path with None if it doesn't exist. + """ + return path if os.path.exists(path) else None + + +def _get_python_inc_posix(prefix, spec_prefix, plat_specific): + return ( + _get_python_inc_posix_python(plat_specific) + or _extant(_get_python_inc_from_config(plat_specific, spec_prefix)) + or _get_python_inc_posix_prefix(prefix) + ) + + +def _get_python_inc_posix_python(plat_specific): + """ + Assume the executable is in the build directory. The + pyconfig.h file should be in the same directory. Since + the build directory may not be the source directory, + use "srcdir" from the makefile to find the "Include" + directory. + """ + if not python_build: + return + if plat_specific: + return _sys_home or project_base + incdir = os.path.join(get_config_var('srcdir'), 'Include') + return os.path.normpath(incdir) + + +def _get_python_inc_from_config(plat_specific, spec_prefix): + """ + If no prefix was explicitly specified, provide the include + directory from the config vars. Useful when + cross-compiling, since the config vars may come from + the host + platform Python installation, while the current Python + executable is from the build platform installation. + + >>> monkeypatch = getfixture('monkeypatch') + >>> gpifc = _get_python_inc_from_config + >>> monkeypatch.setitem(gpifc.__globals__, 'get_config_var', str.lower) + >>> gpifc(False, '/usr/bin/') + >>> gpifc(False, '') + >>> gpifc(False, None) + 'includepy' + >>> gpifc(True, None) + 'confincludepy' + """ + if spec_prefix is None: + return get_config_var('CONF' * plat_specific + 'INCLUDEPY') + + +def _get_python_inc_posix_prefix(prefix): + implementation = 'pypy' if IS_PYPY else 'python' + python_dir = implementation + get_python_version() + build_flags + return os.path.join(prefix, "include", python_dir) + + +def _get_python_inc_nt(prefix, spec_prefix, plat_specific): + if python_build: + # Include both include dirs to ensure we can find pyconfig.h + return ( + os.path.join(prefix, "include") + + os.path.pathsep + + os.path.dirname(sysconfig.get_config_h_filename()) + ) + return os.path.join(prefix, "include") + + +# allow this behavior to be monkey-patched. Ref pypa/distutils#2. +def _posix_lib(standard_lib, libpython, early_prefix, prefix): + if standard_lib: + return libpython + else: + return os.path.join(libpython, "site-packages") + + +def get_python_lib( + plat_specific: bool = False, standard_lib: bool = False, prefix: str | None = None +) -> str: + """Return the directory containing the Python library (standard or + site additions). + + If 'plat_specific' is true, return the directory containing + platform-specific modules, i.e. any module from a non-pure-Python + module distribution; otherwise, return the platform-shared library + directory. If 'standard_lib' is true, return the directory + containing standard Python library modules; otherwise, return the + directory for site-specific modules. + + If 'prefix' is supplied, use it instead of sys.base_prefix or + sys.base_exec_prefix -- i.e., ignore 'plat_specific'. + """ + + early_prefix = prefix + + if prefix is None: + if standard_lib: + prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX + else: + prefix = plat_specific and EXEC_PREFIX or PREFIX + + if os.name == "posix" or is_mingw(): + if plat_specific or standard_lib: + # Platform-specific modules (any module from a non-pure-Python + # module distribution) or standard Python library modules. + libdir = getattr(sys, "platlibdir", "lib") + else: + # Pure Python + libdir = "lib" + implementation = 'pypy' if IS_PYPY else 'python' + libpython = os.path.join(prefix, libdir, implementation + get_python_version()) + return _posix_lib(standard_lib, libpython, early_prefix, prefix) + elif os.name == "nt": + if standard_lib: + return os.path.join(prefix, "Lib") + else: + return os.path.join(prefix, "Lib", "site-packages") + else: + raise DistutilsPlatformError( + f"I don't know where Python installs its library on platform '{os.name}'" + ) + + +@functools.lru_cache +def _customize_macos(): + """ + Perform first-time customization of compiler-related + config vars on macOS. Use after a compiler is known + to be needed. This customization exists primarily to support Pythons + from binary installers. The kind and paths to build tools on + the user system may vary significantly from the system + that Python itself was built on. Also the user OS + version and build tools may not support the same set + of CPU architectures for universal builds. + """ + + sys.platform == "darwin" and __import__('_osx_support').customize_compiler( + get_config_vars() + ) + + +def customize_compiler(compiler: CCompiler) -> None: + """Do any platform-specific customization of a CCompiler instance. + + Mainly needed on Unix, so we can plug in the information that + varies across Unices and is stored in Python's Makefile. + """ + if compiler.compiler_type in ["unix", "cygwin"] or ( + compiler.compiler_type == "mingw32" and is_mingw() + ): + _customize_macos() + + ( + cc, + cxx, + cflags, + ccshared, + ldshared, + ldcxxshared, + shlib_suffix, + ar, + ar_flags, + ) = get_config_vars( + 'CC', + 'CXX', + 'CFLAGS', + 'CCSHARED', + 'LDSHARED', + 'LDCXXSHARED', + 'SHLIB_SUFFIX', + 'AR', + 'ARFLAGS', + ) + + cxxflags = cflags + + if 'CC' in os.environ: + newcc = os.environ['CC'] + if 'LDSHARED' not in os.environ and ldshared.startswith(cc): + # If CC is overridden, use that as the default + # command for LDSHARED as well + ldshared = newcc + ldshared[len(cc) :] + cc = newcc + cxx = os.environ.get('CXX', cxx) + ldshared = os.environ.get('LDSHARED', ldshared) + ldcxxshared = os.environ.get('LDCXXSHARED', ldcxxshared) + cpp = os.environ.get( + 'CPP', + cc + " -E", # not always + ) + + ldshared = _add_flags(ldshared, 'LD') + ldcxxshared = _add_flags(ldcxxshared, 'LD') + cflags = os.environ.get('CFLAGS', cflags) + ldshared = _add_flags(ldshared, 'C') + cxxflags = os.environ.get('CXXFLAGS', cxxflags) + ldcxxshared = _add_flags(ldcxxshared, 'CXX') + cpp = _add_flags(cpp, 'CPP') + cflags = _add_flags(cflags, 'CPP') + cxxflags = _add_flags(cxxflags, 'CPP') + ldshared = _add_flags(ldshared, 'CPP') + ldcxxshared = _add_flags(ldcxxshared, 'CPP') + + ar = os.environ.get('AR', ar) + + archiver = ar + ' ' + os.environ.get('ARFLAGS', ar_flags) + cc_cmd = cc + ' ' + cflags + cxx_cmd = cxx + ' ' + cxxflags + + compiler.set_executables( + preprocessor=cpp, + compiler=cc_cmd, + compiler_so=cc_cmd + ' ' + ccshared, + compiler_cxx=cxx_cmd, + compiler_so_cxx=cxx_cmd + ' ' + ccshared, + linker_so=ldshared, + linker_so_cxx=ldcxxshared, + linker_exe=cc, + linker_exe_cxx=cxx, + archiver=archiver, + ) + + if 'RANLIB' in os.environ and compiler.executables.get('ranlib', None): + compiler.set_executables(ranlib=os.environ['RANLIB']) + + compiler.shared_lib_extension = shlib_suffix + + +def get_config_h_filename() -> str: + """Return full pathname of installed pyconfig.h file.""" + return sysconfig.get_config_h_filename() + + +def get_makefile_filename() -> str: + """Return full pathname of installed Makefile from the Python build.""" + return sysconfig.get_makefile_filename() + + +def parse_config_h(fp, g=None): + """Parse a config.h-style file. + + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + """ + return sysconfig.parse_config_h(fp, vars=g) + + +# Regexes needed for parsing Makefile (and similar syntaxes, +# like old-style Setup files). +_variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)") +_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") +_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") + + +def parse_makefile(fn, g=None): # noqa: C901 + """Parse a Makefile-style file. + + A dictionary containing name/value pairs is returned. If an + optional dictionary is passed in as the second argument, it is + used instead of a new dictionary. + """ + from distutils.text_file import TextFile + + fp = TextFile( + fn, + strip_comments=True, + skip_blanks=True, + join_lines=True, + errors="surrogateescape", + ) + + if g is None: + g = {} + done = {} + notdone = {} + + while True: + line = fp.readline() + if line is None: # eof + break + m = _variable_rx.match(line) + if m: + n, v = m.group(1, 2) + v = v.strip() + # `$$' is a literal `$' in make + tmpv = v.replace('$$', '') + + if "$" in tmpv: + notdone[n] = v + else: + try: + v = int(v) + except ValueError: + # insert literal `$' + done[n] = v.replace('$$', '$') + else: + done[n] = v + + # Variables with a 'PY_' prefix in the makefile. These need to + # be made available without that prefix through sysconfig. + # Special care is needed to ensure that variable expansion works, even + # if the expansion uses the name without a prefix. + renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') + + # do variable interpolation here + while notdone: + for name in list(notdone): + value = notdone[name] + m = _findvar1_rx.search(value) or _findvar2_rx.search(value) + if m: + n = m.group(1) + found = True + if n in done: + item = str(done[n]) + elif n in notdone: + # get it on a subsequent round + found = False + elif n in os.environ: + # do it like make: fall back to environment + item = os.environ[n] + + elif n in renamed_variables: + if name.startswith('PY_') and name[3:] in renamed_variables: + item = "" + + elif 'PY_' + n in notdone: + found = False + + else: + item = str(done['PY_' + n]) + else: + done[n] = item = "" + if found: + after = value[m.end() :] + value = value[: m.start()] + item + after + if "$" in after: + notdone[name] = value + else: + try: + value = int(value) + except ValueError: + done[name] = value.strip() + else: + done[name] = value + del notdone[name] + + if name.startswith('PY_') and name[3:] in renamed_variables: + name = name[3:] + if name not in done: + done[name] = value + else: + # bogus variable reference; just drop it since we can't deal + del notdone[name] + + fp.close() + + # strip spurious spaces + for k, v in done.items(): + if isinstance(v, str): + done[k] = v.strip() + + # save the results in the global dictionary + g.update(done) + return g + + +def expand_makefile_vars(s, vars): + """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in + 'string' according to 'vars' (a dictionary mapping variable names to + values). Variables not present in 'vars' are silently expanded to the + empty string. The variable values in 'vars' should not contain further + variable expansions; if 'vars' is the output of 'parse_makefile()', + you're fine. Returns a variable-expanded version of 's'. + """ + + # This algorithm does multiple expansion, so if vars['foo'] contains + # "${bar}", it will expand ${foo} to ${bar}, and then expand + # ${bar}... and so forth. This is fine as long as 'vars' comes from + # 'parse_makefile()', which takes care of such expansions eagerly, + # according to make's variable expansion semantics. + + while True: + m = _findvar1_rx.search(s) or _findvar2_rx.search(s) + if m: + (beg, end) = m.span() + s = s[0:beg] + vars.get(m.group(1)) + s[end:] + else: + break + return s + + +_config_vars = None + + +@overload +def get_config_vars() -> dict[str, str | int]: ... +@overload +def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ... +def get_config_vars(*args: str) -> list[str | int] | dict[str, str | int]: + """With no arguments, return a dictionary of all configuration + variables relevant for the current platform. Generally this includes + everything needed to build extensions and install both pure modules and + extensions. On Unix, this means every variable defined in Python's + installed Makefile; on Windows it's a much smaller set. + + With arguments, return a list of values that result from looking up + each argument in the configuration variable dictionary. + """ + global _config_vars + if _config_vars is None: + _config_vars = sysconfig.get_config_vars().copy() + py39.add_ext_suffix(_config_vars) + + return [_config_vars.get(name) for name in args] if args else _config_vars + + +@overload +@deprecated( + "SO is deprecated, use EXT_SUFFIX. Support will be removed when this module is synchronized with stdlib Python 3.11" +) +def get_config_var(name: Literal["SO"]) -> int | str | None: ... +@overload +def get_config_var(name: str) -> int | str | None: ... +def get_config_var(name: str) -> int | str | None: + """Return the value of a single variable using the dictionary + returned by 'get_config_vars()'. Equivalent to + get_config_vars().get(name) + """ + if name == 'SO': + import warnings + + warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2) + return get_config_vars().get(name) + + +@pass_none +def _add_flags(value: str, type: str) -> str: + """ + Add any flags from the environment for the given type. + + type is the prefix to FLAGS in the environment key (e.g. "C" for "CFLAGS"). + """ + flags = os.environ.get(f'{type}FLAGS') + return f'{value} {flags}' if flags else value diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5a8ab061009f1cd87a53ce51eff3bc9e9a632273 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__init__.py @@ -0,0 +1,42 @@ +""" +Test suite for distutils. + +Tests for the command classes in the distutils.command package are +included in distutils.tests as well, instead of using a separate +distutils.command.tests package, since command identification is done +by import rather than matching pre-defined names. +""" + +import shutil +from collections.abc import Sequence + + +def missing_compiler_executable(cmd_names: Sequence[str] = []): # pragma: no cover + """Check if the compiler components used to build the interpreter exist. + + Check for the existence of the compiler executables whose names are listed + in 'cmd_names' or all the compiler executables when 'cmd_names' is empty + and return the first missing executable or None when none is found + missing. + + """ + from distutils import ccompiler, errors, sysconfig + + compiler = ccompiler.new_compiler() + sysconfig.customize_compiler(compiler) + if compiler.compiler_type == "msvc": + # MSVC has no executables, so check whether initialization succeeds + try: + compiler.initialize() + except errors.DistutilsPlatformError: + return "msvc" + for name in compiler.executables: + if cmd_names and name not in cmd_names: + continue + cmd = getattr(compiler, name) + if cmd_names: + assert cmd is not None, f"the '{name}' executable is not configured" + elif not cmd: + continue + if shutil.which(cmd[0]) is None: + return cmd[0] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef9307dd307765cd163160169d59183eb4a80cb4 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/support.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/support.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb20fd81567ac9aad462cb823a7ba3c778dc907f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/support.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_archive_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_archive_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..941635a6de6ce1ade40fb198bc8ea5708a5bdfdc Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_archive_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16fa9687d8885fc6716d5e45f6883c7cc8d19ea3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist_dumb.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist_dumb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..877c8386b6e09bd9a53341405c23bc86d4b1162f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist_dumb.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist_rpm.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist_rpm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..890b2c2fae3c475761e728d60f4da33d7995f47f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_bdist_rpm.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..498562cbedfb31e679012f1bc10275a3828a6518 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_clib.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_clib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..102c1bead14a54bee3355cc63a948fdca67b9e21 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_clib.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_ext.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_ext.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5bb817348ef6a86a44fe37312efd697c59e5565 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_ext.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_py.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c43ed530e2eef3a665c797f4fd1db3359c510561 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_py.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_scripts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_scripts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86f2a97562eb2c2041e521eddbc6eb6d4ad9d63b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_build_scripts.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_check.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_check.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ec0424eac88c64e0e526c3a2e4ca76a6ab522f1 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_check.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_clean.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_clean.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9a13b2c928ade4a8c7e164b8391f3eaba01c81e Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_clean.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_cmd.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_cmd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0887b7254a53dd836922e9973bb9a1388af5c384 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_cmd.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_config_cmd.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_config_cmd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4126d675f115b66dd3e85473ac80417da0be28db Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_config_cmd.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_core.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67a734ce42fced496581b90b02b7c9b03003c4eb Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_core.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_dir_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_dir_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..594439f21442a65b651e63d23d8b646c8712a41f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_dir_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_dist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_dist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c602271579b03f76a9f31c5800328aaec6db9e4 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_dist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_extension.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_extension.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..783efc8d9c5d18d4b58d442b46d8ca41f450a23a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_extension.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_file_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_file_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c89d587651421e27e77f3e408d7c7ee16255227 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_file_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_filelist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_filelist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91297e2e152b7f77c64898a7f994feabf9ea8ea6 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_filelist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b3d168b967273e366b2f276653fe6a925e23aac Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_data.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_data.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abf444e7c939b451a6769af407024189f74f314b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_data.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_headers.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_headers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06762af34360137b9796dd96969ffef2146b561a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_headers.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_lib.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_lib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fa14aa90000c218019f21aa056106af2861846d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_lib.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_scripts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_scripts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0709332232acc48ffe098af3884fdc92ce920e2 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_install_scripts.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_log.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_log.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80ecbd47533390a0dc7235bf888e58fcbbfef520 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_log.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_modified.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_modified.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fef3513e9d836b19a295752137e17d71f2baa9d2 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_modified.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_sdist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_sdist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79ab79ba5fdf038981d5a42dc3552e67b96f5fd4 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_sdist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_spawn.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_spawn.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64275fae62d5fc97e97db6cdb2c8535cebc8c332 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_spawn.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_sysconfig.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_sysconfig.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da4042c97a21ede24868770d1b1cb4d29d94b259 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_sysconfig.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_text_file.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_text_file.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10de08daf1ecd96bed70e85c2b40a6ecc9cbe041 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_text_file.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fce01c468600652076f73a49cc7a14eed6e238aa Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_util.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_version.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf40f6cc9eefa51d2314e9df0be7253a301fd00e Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_version.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_versionpredicate.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_versionpredicate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1318804cc090fc6b64422f3c28fdba8ee33f7532 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/test_versionpredicate.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/unix_compat.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/unix_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6128d74be6e25f5a36ba4d3a748a5e2ea2a94bfa Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/__pycache__/unix_compat.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6b4a2745e091e2a442f30dec14f43bdad50feb8 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/__pycache__/py39.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/__pycache__/py39.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a190a8c403b6952675ebd2c5fa26d39f248ee156 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/__pycache__/py39.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/py39.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/py39.py new file mode 100644 index 0000000000000000000000000000000000000000..aca3939a0cea90dd0a90d7f36fcf83a5167cbfc4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/compat/py39.py @@ -0,0 +1,40 @@ +import sys + +if sys.version_info >= (3, 10): + from test.support.import_helper import ( + CleanImport as CleanImport, + ) + from test.support.import_helper import ( + DirsOnSysPath as DirsOnSysPath, + ) + from test.support.os_helper import ( + EnvironmentVarGuard as EnvironmentVarGuard, + ) + from test.support.os_helper import ( + rmtree as rmtree, + ) + from test.support.os_helper import ( + skip_unless_symlink as skip_unless_symlink, + ) + from test.support.os_helper import ( + unlink as unlink, + ) +else: + from test.support import ( + CleanImport as CleanImport, + ) + from test.support import ( + DirsOnSysPath as DirsOnSysPath, + ) + from test.support import ( + EnvironmentVarGuard as EnvironmentVarGuard, + ) + from test.support import ( + rmtree as rmtree, + ) + from test.support import ( + skip_unless_symlink as skip_unless_symlink, + ) + from test.support import ( + unlink as unlink, + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/support.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/support.py new file mode 100644 index 0000000000000000000000000000000000000000..9cd2b8a9eedbb9f11a3ed793af57b3290c5febef --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/support.py @@ -0,0 +1,134 @@ +"""Support code for distutils test cases.""" + +import itertools +import os +import pathlib +import shutil +import sys +import sysconfig +import tempfile +from distutils.core import Distribution + +import pytest +from more_itertools import always_iterable + + +@pytest.mark.usefixtures('distutils_managed_tempdir') +class TempdirManager: + """ + Mix-in class that handles temporary directories for test cases. + """ + + def mkdtemp(self): + """Create a temporary directory that will be cleaned up. + + Returns the path of the directory. + """ + d = tempfile.mkdtemp() + self.tempdirs.append(d) + return d + + def write_file(self, path, content='xxx'): + """Writes a file in the given path. + + path can be a string or a sequence. + """ + pathlib.Path(*always_iterable(path)).write_text(content, encoding='utf-8') + + def create_dist(self, pkg_name='foo', **kw): + """Will generate a test environment. + + This function creates: + - a Distribution instance using keywords + - a temporary directory with a package structure + + It returns the package directory and the distribution + instance. + """ + tmp_dir = self.mkdtemp() + pkg_dir = os.path.join(tmp_dir, pkg_name) + os.mkdir(pkg_dir) + dist = Distribution(attrs=kw) + + return pkg_dir, dist + + +class DummyCommand: + """Class to store options for retrieval via set_undefined_options().""" + + def __init__(self, **kwargs): + vars(self).update(kwargs) + + def ensure_finalized(self): + pass + + +def copy_xxmodule_c(directory): + """Helper for tests that need the xxmodule.c source file. + + Example use: + + def test_compile(self): + copy_xxmodule_c(self.tmpdir) + self.assertIn('xxmodule.c', os.listdir(self.tmpdir)) + + If the source file can be found, it will be copied to *directory*. If not, + the test will be skipped. Errors during copy are not caught. + """ + shutil.copy(_get_xxmodule_path(), os.path.join(directory, 'xxmodule.c')) + + +def _get_xxmodule_path(): + source_name = 'xxmodule.c' if sys.version_info > (3, 9) else 'xxmodule-3.8.c' + return os.path.join(os.path.dirname(__file__), source_name) + + +def fixup_build_ext(cmd): + """Function needed to make build_ext tests pass. + + When Python was built with --enable-shared on Unix, -L. is not enough to + find libpython.so, because regrtest runs in a tempdir, not in the + source directory where the .so lives. + + When Python was built with in debug mode on Windows, build_ext commands + need their debug attribute set, and it is not done automatically for + some reason. + + This function handles both of these things. Example use: + + cmd = build_ext(dist) + support.fixup_build_ext(cmd) + cmd.ensure_finalized() + + Unlike most other Unix platforms, Mac OS X embeds absolute paths + to shared libraries into executables, so the fixup is not needed there. + """ + if os.name == 'nt': + cmd.debug = sys.executable.endswith('_d.exe') + elif sysconfig.get_config_var('Py_ENABLE_SHARED'): + # To further add to the shared builds fun on Unix, we can't just add + # library_dirs to the Extension() instance because that doesn't get + # plumbed through to the final compiler command. + runshared = sysconfig.get_config_var('RUNSHARED') + if runshared is None: + cmd.library_dirs = ['.'] + else: + if sys.platform == 'darwin': + cmd.library_dirs = [] + else: + name, equals, value = runshared.partition('=') + cmd.library_dirs = [d for d in value.split(os.pathsep) if d] + + +def combine_markers(cls): + """ + pytest will honor markers as found on the class, but when + markers are on multiple subclasses, only one appears. Use + this decorator to combine those markers. + """ + cls.pytestmark = [ + mark + for base in itertools.chain([cls], cls.__bases__) + for mark in getattr(base, 'pytestmark', []) + ] + return cls diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_archive_util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_archive_util.py new file mode 100644 index 0000000000000000000000000000000000000000..a9cc5eb00968ed9d5d77cac60ef543827c669539 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_archive_util.py @@ -0,0 +1,342 @@ +"""Tests for distutils.archive_util.""" + +import functools +import operator +import os +import pathlib +import sys +import tarfile +from distutils import archive_util +from distutils.archive_util import ( + ARCHIVE_FORMATS, + check_archive_formats, + make_archive, + make_tarball, + make_zipfile, +) +from distutils.spawn import spawn +from distutils.tests import support +from os.path import splitdrive + +import path +import pytest +from test.support import patch + +from .unix_compat import UID_0_SUPPORT, grp, pwd, require_uid_0, require_unix_id + + +def can_fs_encode(filename): + """ + Return True if the filename can be saved in the file system. + """ + if os.path.supports_unicode_filenames: + return True + try: + filename.encode(sys.getfilesystemencoding()) + except UnicodeEncodeError: + return False + return True + + +def all_equal(values): + return functools.reduce(operator.eq, values) + + +def same_drive(*paths): + return all_equal(pathlib.Path(path).drive for path in paths) + + +class ArchiveUtilTestCase(support.TempdirManager): + @pytest.mark.usefixtures('needs_zlib') + def test_make_tarball(self, name='archive'): + # creating something to tar + tmpdir = self._create_files() + self._make_tarball(tmpdir, name, '.tar.gz') + # trying an uncompressed one + self._make_tarball(tmpdir, name, '.tar', compress=None) + + @pytest.mark.usefixtures('needs_zlib') + def test_make_tarball_gzip(self): + tmpdir = self._create_files() + self._make_tarball(tmpdir, 'archive', '.tar.gz', compress='gzip') + + def test_make_tarball_bzip2(self): + pytest.importorskip('bz2') + tmpdir = self._create_files() + self._make_tarball(tmpdir, 'archive', '.tar.bz2', compress='bzip2') + + def test_make_tarball_xz(self): + pytest.importorskip('lzma') + tmpdir = self._create_files() + self._make_tarball(tmpdir, 'archive', '.tar.xz', compress='xz') + + @pytest.mark.skipif("not can_fs_encode('årchiv')") + def test_make_tarball_latin1(self): + """ + Mirror test_make_tarball, except filename contains latin characters. + """ + self.test_make_tarball('årchiv') # note this isn't a real word + + @pytest.mark.skipif("not can_fs_encode('のアーカイブ')") + def test_make_tarball_extended(self): + """ + Mirror test_make_tarball, except filename contains extended + characters outside the latin charset. + """ + self.test_make_tarball('のアーカイブ') # japanese for archive + + def _make_tarball(self, tmpdir, target_name, suffix, **kwargs): + tmpdir2 = self.mkdtemp() + if same_drive(tmpdir, tmpdir2): + pytest.skip("source and target should be on same drive") + + base_name = os.path.join(tmpdir2, target_name) + + # working with relative paths to avoid tar warnings + with path.Path(tmpdir): + make_tarball(splitdrive(base_name)[1], 'dist', **kwargs) + + # check if the compressed tarball was created + tarball = base_name + suffix + assert os.path.exists(tarball) + assert self._tarinfo(tarball) == self._created_files + + def _tarinfo(self, path): + tar = tarfile.open(path) + try: + names = tar.getnames() + names.sort() + return names + finally: + tar.close() + + _zip_created_files = [ + 'dist/', + 'dist/file1', + 'dist/file2', + 'dist/sub/', + 'dist/sub/file3', + 'dist/sub2/', + ] + _created_files = [p.rstrip('/') for p in _zip_created_files] + + def _create_files(self): + # creating something to tar + tmpdir = self.mkdtemp() + dist = os.path.join(tmpdir, 'dist') + os.mkdir(dist) + self.write_file([dist, 'file1'], 'xxx') + self.write_file([dist, 'file2'], 'xxx') + os.mkdir(os.path.join(dist, 'sub')) + self.write_file([dist, 'sub', 'file3'], 'xxx') + os.mkdir(os.path.join(dist, 'sub2')) + return tmpdir + + @pytest.mark.usefixtures('needs_zlib') + @pytest.mark.skipif("not (shutil.which('tar') and shutil.which('gzip'))") + def test_tarfile_vs_tar(self): + tmpdir = self._create_files() + tmpdir2 = self.mkdtemp() + base_name = os.path.join(tmpdir2, 'archive') + old_dir = os.getcwd() + os.chdir(tmpdir) + try: + make_tarball(base_name, 'dist') + finally: + os.chdir(old_dir) + + # check if the compressed tarball was created + tarball = base_name + '.tar.gz' + assert os.path.exists(tarball) + + # now create another tarball using `tar` + tarball2 = os.path.join(tmpdir, 'archive2.tar.gz') + tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist'] + gzip_cmd = ['gzip', '-f', '-9', 'archive2.tar'] + old_dir = os.getcwd() + os.chdir(tmpdir) + try: + spawn(tar_cmd) + spawn(gzip_cmd) + finally: + os.chdir(old_dir) + + assert os.path.exists(tarball2) + # let's compare both tarballs + assert self._tarinfo(tarball) == self._created_files + assert self._tarinfo(tarball2) == self._created_files + + # trying an uncompressed one + base_name = os.path.join(tmpdir2, 'archive') + old_dir = os.getcwd() + os.chdir(tmpdir) + try: + make_tarball(base_name, 'dist', compress=None) + finally: + os.chdir(old_dir) + tarball = base_name + '.tar' + assert os.path.exists(tarball) + + @pytest.mark.usefixtures('needs_zlib') + def test_make_zipfile(self): + zipfile = pytest.importorskip('zipfile') + # creating something to tar + tmpdir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + with path.Path(tmpdir): + make_zipfile(base_name, 'dist') + + # check if the compressed tarball was created + tarball = base_name + '.zip' + assert os.path.exists(tarball) + with zipfile.ZipFile(tarball) as zf: + assert sorted(zf.namelist()) == self._zip_created_files + + def test_make_zipfile_no_zlib(self): + zipfile = pytest.importorskip('zipfile') + patch(self, archive_util.zipfile, 'zlib', None) # force zlib ImportError + + called = [] + zipfile_class = zipfile.ZipFile + + def fake_zipfile(*a, **kw): + if kw.get('compression', None) == zipfile.ZIP_STORED: + called.append((a, kw)) + return zipfile_class(*a, **kw) + + patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile) + + # create something to tar and compress + tmpdir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + with path.Path(tmpdir): + make_zipfile(base_name, 'dist') + + tarball = base_name + '.zip' + assert called == [((tarball, "w"), {'compression': zipfile.ZIP_STORED})] + assert os.path.exists(tarball) + with zipfile.ZipFile(tarball) as zf: + assert sorted(zf.namelist()) == self._zip_created_files + + def test_check_archive_formats(self): + assert check_archive_formats(['gztar', 'xxx', 'zip']) == 'xxx' + assert ( + check_archive_formats(['gztar', 'bztar', 'xztar', 'ztar', 'tar', 'zip']) + is None + ) + + def test_make_archive(self): + tmpdir = self.mkdtemp() + base_name = os.path.join(tmpdir, 'archive') + with pytest.raises(ValueError): + make_archive(base_name, 'xxx') + + def test_make_archive_cwd(self): + current_dir = os.getcwd() + + def _breaks(*args, **kw): + raise RuntimeError() + + ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file') + try: + try: + make_archive('xxx', 'xxx', root_dir=self.mkdtemp()) + except Exception: + pass + assert os.getcwd() == current_dir + finally: + ARCHIVE_FORMATS.pop('xxx') + + def test_make_archive_tar(self): + base_dir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive(base_name, 'tar', base_dir, 'dist') + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar' + assert self._tarinfo(res) == self._created_files + + @pytest.mark.usefixtures('needs_zlib') + def test_make_archive_gztar(self): + base_dir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive(base_name, 'gztar', base_dir, 'dist') + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.gz' + assert self._tarinfo(res) == self._created_files + + def test_make_archive_bztar(self): + pytest.importorskip('bz2') + base_dir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive(base_name, 'bztar', base_dir, 'dist') + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.bz2' + assert self._tarinfo(res) == self._created_files + + def test_make_archive_xztar(self): + pytest.importorskip('lzma') + base_dir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive(base_name, 'xztar', base_dir, 'dist') + assert os.path.exists(res) + assert os.path.basename(res) == 'archive.tar.xz' + assert self._tarinfo(res) == self._created_files + + def test_make_archive_owner_group(self): + # testing make_archive with owner and group, with various combinations + # this works even if there's not gid/uid support + if UID_0_SUPPORT: + group = grp.getgrgid(0)[0] + owner = pwd.getpwuid(0)[0] + else: + group = owner = 'root' + + base_dir = self._create_files() + root_dir = self.mkdtemp() + base_name = os.path.join(self.mkdtemp(), 'archive') + res = make_archive( + base_name, 'zip', root_dir, base_dir, owner=owner, group=group + ) + assert os.path.exists(res) + + res = make_archive(base_name, 'zip', root_dir, base_dir) + assert os.path.exists(res) + + res = make_archive( + base_name, 'tar', root_dir, base_dir, owner=owner, group=group + ) + assert os.path.exists(res) + + res = make_archive( + base_name, 'tar', root_dir, base_dir, owner='kjhkjhkjg', group='oihohoh' + ) + assert os.path.exists(res) + + @pytest.mark.usefixtures('needs_zlib') + @require_unix_id + @require_uid_0 + def test_tarfile_root_owner(self): + tmpdir = self._create_files() + base_name = os.path.join(self.mkdtemp(), 'archive') + old_dir = os.getcwd() + os.chdir(tmpdir) + group = grp.getgrgid(0)[0] + owner = pwd.getpwuid(0)[0] + try: + archive_name = make_tarball( + base_name, 'dist', compress=None, owner=owner, group=group + ) + finally: + os.chdir(old_dir) + + # check if the compressed tarball was created + assert os.path.exists(archive_name) + + # now checks the rights + archive = tarfile.open(archive_name) + try: + for member in archive.getmembers(): + assert member.uid == 0 + assert member.gid == 0 + finally: + archive.close() diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_bdist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_bdist.py new file mode 100644 index 0000000000000000000000000000000000000000..d5696fc3dcd8081335606dc92badd73a69ceac69 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_bdist.py @@ -0,0 +1,47 @@ +"""Tests for distutils.command.bdist.""" + +from distutils.command.bdist import bdist +from distutils.tests import support + + +class TestBuild(support.TempdirManager): + def test_formats(self): + # let's create a command and make sure + # we can set the format + dist = self.create_dist()[1] + cmd = bdist(dist) + cmd.formats = ['gztar'] + cmd.ensure_finalized() + assert cmd.formats == ['gztar'] + + # what formats does bdist offer? + formats = [ + 'bztar', + 'gztar', + 'rpm', + 'tar', + 'xztar', + 'zip', + 'ztar', + ] + found = sorted(cmd.format_commands) + assert found == formats + + def test_skip_build(self): + # bug #10946: bdist --skip-build should trickle down to subcommands + dist = self.create_dist()[1] + cmd = bdist(dist) + cmd.skip_build = True + cmd.ensure_finalized() + dist.command_obj['bdist'] = cmd + + names = [ + 'bdist_dumb', + ] # bdist_rpm does not support --skip-build + + for name in names: + subcmd = cmd.get_finalized_command(name) + if getattr(subcmd, '_unsupported', False): + # command is not supported on this build + continue + assert subcmd.skip_build, f'{name} should take --skip-build from bdist' diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_bdist_dumb.py new file mode 100644 index 0000000000000000000000000000000000000000..1fc51d244a78058329c56a618b092e466715e565 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_bdist_rpm.py new file mode 100644 index 0000000000000000000000000000000000000000..75051430e224c8908e22601133a40f5f82ee455a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build.py new file mode 100644 index 0000000000000000000000000000000000000000..f7fe69acd1ad39cf40d277afd6409648b18df146 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build_clib.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build_clib.py new file mode 100644 index 0000000000000000000000000000000000000000..f76f26bcea04ebeaeba20d3c65881198f841c9b5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build_ext.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..dab0507f3d3ec104fb4acfe5b15f92661ff33a37 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build_py.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build_py.py new file mode 100644 index 0000000000000000000000000000000000000000..b316ed43a11836210caeb7177bd8890a1f61d1bb --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build_scripts.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_build_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..3582f691ef578a419555c6ffbba6a619310517a6 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_check.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_check.py new file mode 100644 index 0000000000000000000000000000000000000000..b672b1f972b46f399eb5b2ef263da2548d52ef89 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_clean.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_clean.py new file mode 100644 index 0000000000000000000000000000000000000000..cc78f30f34b323845b977b9147c2153390774bd3 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_cmd.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..76e8f5989b3b102a32239436ff3b65f26e09e029 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_config_cmd.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_config_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..ebee2ef93f0bc9d422984e2e4872665b1be3a1de --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_core.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_core.py new file mode 100644 index 0000000000000000000000000000000000000000..bad3fb7e8318d3ee73ecabe20ed98c279f606a77 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_dir_util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_dir_util.py new file mode 100644 index 0000000000000000000000000000000000000000..326cb346145ec7e3a1dd0384c33d4125131feaae --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_dist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..2c5beebe64eb9d747088cf117082a546330b29f3 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_extension.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8e768223ea40d7a629111db181a946cf8ca5b0 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_file_util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_file_util.py new file mode 100644 index 0000000000000000000000000000000000000000..a75d4a0317dc717c24f67127370aa87089eeba1a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_filelist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_filelist.py new file mode 100644 index 0000000000000000000000000000000000000000..130e6fb53b0bd9670bdcfe6d4bc7fcf8fd90416e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install.py new file mode 100644 index 0000000000000000000000000000000000000000..b3ffb2e668ac5a042c5a2889d7b51b5755b73157 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install_data.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c800f86c645d86fcb11aa3bef1513325ef163132 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install_headers.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..2c74f06b976f3c3ea977667a5c16c0e7f201a558 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install_lib.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..f685a579560ea70bceea221de0e54485975ce180 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install_scripts.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_install_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..868b1c22521f23a5dd398e4636c94330d4c238ac --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_log.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_log.py new file mode 100644 index 0000000000000000000000000000000000000000..d67779fc9fa0f58a010929d5a456890c6dde3376 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_modified.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_modified.py new file mode 100644 index 0000000000000000000000000000000000000000..e35cec2d6f1a8d27619e33c253f0a83f0f72a75d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_sdist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..6b1a376b262162aa7c8d3d989709c05b38563d6c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_spawn.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_spawn.py new file mode 100644 index 0000000000000000000000000000000000000000..3b9fc926f6ffc41673630fbf5775e6f4ad638b18 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_sysconfig.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_sysconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..43d77c23fad426be237b9f91a6d98d7c36233d84 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_text_file.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_text_file.py new file mode 100644 index 0000000000000000000000000000000000000000..f51115656135cd3f348a45d4a14f97eeee47fb98 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..00c9743ed0a2664039060ef149d30f165bf2f465 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_version.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_version.py new file mode 100644 index 0000000000000000000000000000000000000000..b68f0977249aa23aafbf31cf74a0e4127f777d05 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_versionpredicate.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/test_versionpredicate.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/unix_compat.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/tests/unix_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..a5d9ee45ccc639794d29ba0a5fd24f781ee5ecf5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/text_file.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/text_file.py new file mode 100644 index 0000000000000000000000000000000000000000..89d9048d5902950516c3541ad212bff7b6cb2045 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/unixccompiler.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/unixccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..20b8ce6b9bba21bd709b77249bdcae5b4119e9ca --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/util.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/util.py new file mode 100644 index 0000000000000000000000000000000000000000..47bb5af5e4b9c78c8b7e3657594562115750db8a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/util.py @@ -0,0 +1,506 @@ +"""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, +) -> None: + """ + Perform some action that affects the outside world (e.g. by + writing to the filesystem). Was previously used to deal with + "dry run" operations, but now runs unconditionally. + """ + if msg is None: + msg = f"{func.__name__}{args!r}" + if msg[-2:] == ',)': # correct for singleton tuple + msg = msg[0:-2] + ')' + + log.info(msg) + 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, + 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. + + 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) + 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}, + direct=True) +""" + ) + + cmd = [sys.executable] + cmd.extend(subprocess._optim_args_from_interpreter_flags()) + cmd.append(script_name) + spawn(cmd) + execute(os.remove, (script_name,), f"removing {script_name}") + + # "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) + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/version.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/version.py new file mode 100644 index 0000000000000000000000000000000000000000..2223ee9c8cab2495034a57d4585625feb81a8330 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/versionpredicate.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/versionpredicate.py new file mode 100644 index 0000000000000000000000000000000000000000..fe31b0ed8ef843080ea64df9f58a398d317434ad --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/zosccompiler.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/zosccompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e49630ac6ed8cad62c4d2ff8361758519e6dc83b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_distutils/zosccompiler.py @@ -0,0 +1,3 @@ +from .compilers.C import zos + +zOSCCompiler = zos.Compiler diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/.lock b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/.lock new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b49c3af060ce6326b8d91b9b73e76456ea0d9d2b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..32214fb4400035788bfe5c0de42dad106a4f54f1 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..8cd7450980bb1cf4d7646611ae6d64b6a9853b35 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/RECORD @@ -0,0 +1,13 @@ +autocommand-2.2.2.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +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/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +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/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..57e3d840d59a650ac5bccbad5baeec47d155f0ad --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..dda5158ff6d263927861b19ef5a5d183d2aa77ed --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand-2.2.2.dist-info/top_level.txt @@ -0,0 +1 @@ +autocommand diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..73fbfca6b36927c6371839df3dfe733bebb2066f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a6984e8a6272ae82c6465415395a241434326a5 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..142895c0829beb9b3f04dbb8bf9a8941bb0b91f1 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autoasync.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c1dbdd9059d70b4820e73ea6662e81c1802485e Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autocommand.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/automain.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/automain.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..581fd48a29e7091ec4c20691cf03e203c0f695be Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/automain.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a9f89f6a48a27f8fc4b761d261e3d95bcb6018f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/autoparse.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/errors.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bfc4cd40704881221502b011bf574c5d606058f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/__pycache__/errors.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/autoasync.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/autoasync.py new file mode 100644 index 0000000000000000000000000000000000000000..688f7e05544bb5b4914d290c9bfe73bb99f4e06a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/autocommand.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/autocommand.py new file mode 100644 index 0000000000000000000000000000000000000000..097e86de0720126a1390d728f7e50a4f89cac77f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/automain.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/automain.py new file mode 100644 index 0000000000000000000000000000000000000000..6cc45db66a1c1dbf1bedb993683b0700d0510643 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/autoparse.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/autoparse.py new file mode 100644 index 0000000000000000000000000000000000000000..0276a3fae10eb367af326543bcd69e62432b2f7b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/errors.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/autocommand/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..2570607399a3ae13cb92db65a9171d955d3248c6 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..db0a2dcdbe5f55f5815b2eaa243c507d0bdad002 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c7d2c25bc103c6b3b1f60b23337276d81f24b5c4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/RECORD @@ -0,0 +1,12 @@ +backports.tarfile-1.2.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +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/tarfile/__init__.py,sha256=Pwf2qUIfB0SolJPCKcx3vz3UEu_aids4g4sAfxy94qg,108491 +backports/tarfile/__main__.py,sha256=Yw2oGT1afrz2eBskzdPYL8ReB_3liApmhFkN2EbDmc4,59 +backports/tarfile/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +backports/tarfile/compat/py38.py,sha256=iYkyt_gvWjLzGUTJD9TuTfMMjOk-ersXZmRlvQYN2qE,568 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..99d2be5b64d7dc414f8ab9c002de06456b4bada2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports.tarfile-1.2.0.dist-info/top_level.txt @@ -0,0 +1 @@ +backports diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d1f7edf5dc6343538563a8caa7de6829752c4f9 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d169575be1aabb25f3ad5195b56d7e108131a883 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c16881cb3ae1ea6e729b62bb2e5d625faa3f5fe --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/__main__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..daf55090862ae43283b6552073549ac3ab2ad50a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/__main__.py @@ -0,0 +1,5 @@ +from . import main + + +if __name__ == '__main__': + main() diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d3c9671a6a1d7e86375fdd779c15f64ad23a9ea Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__main__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3f4b8af41dce58b3177c2c7fe31f7ca69410f49 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa387c887a17d06e04d41e7fe9bac9b39edd1fd4 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/__pycache__/py38.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/py38.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/backports/tarfile/compat/py38.py new file mode 100644 index 0000000000000000000000000000000000000000..20fbbfc1c095baf9f8c72902b24296b50ad3ab9d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9d894b433dc0e27e53d3be160edb861358db99fd --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/METADATA @@ -0,0 +1,133 @@ +Metadata-Version: 2.4 +Name: importlib_metadata +Version: 8.7.1 +Summary: Read metadata from Python packages +Author-email: "Jason R. Coombs" +License-Expression: Apache-2.0 +Project-URL: Source, https://github.com/python/importlib_metadata +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: zipp>=3.20 +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; 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" +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: 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: enabler +Requires-Dist: pytest-enabler>=3.4; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy>=1.0.1; extra == "type" +Requires-Dist: mypy<1.19; platform_python_implementation == "PyPy" and extra == "type" +Dynamic: license-file + +.. 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/astral-sh/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-2025-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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..78aa761cab1c52d856213f18e2785001bdb02904 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/RECORD @@ -0,0 +1,21 @@ +importlib_metadata-8.7.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +importlib_metadata-8.7.1.dist-info/METADATA,sha256=o-OLnuQyYonUhkcE8w4pnudp4jCc6fSnXw3hpQrQo1Y,4670 +importlib_metadata-8.7.1.dist-info/RECORD,, +importlib_metadata-8.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_metadata-8.7.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +importlib_metadata-8.7.1.dist-info/licenses/LICENSE,sha256=RYUC4S2Xu_ZEOGBqIARKqF6wX7CoqAe7NdvsJT_R_AQ,10278 +importlib_metadata-8.7.1.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19 +importlib_metadata/__init__.py,sha256=u7Ew4-UkpzNY-ka6k-WRkDhQZS1akkLMfWs2eEnUmGo,37734 +importlib_metadata/_adapters.py,sha256=r5i8XLrKT6xmrpoREZhZrfczOYDmrVZeJBW5u0HzIGU,3797 +importlib_metadata/_collections.py,sha256=CxAhzlF3g1rwu_fMiB53JtRQiUFh0RgiMpoOvmK_ocg,760 +importlib_metadata/_compat.py,sha256=VC5ZDLlT-BcshauCShdFJvMNLntJJfZzNK1meGa-enw,1313 +importlib_metadata/_functools.py,sha256=0pA2OoiVK6wnsGq8HvVIzgdkvLiZ0nfnfw7IsndjoHk,3510 +importlib_metadata/_itertools.py,sha256=nMvp9SfHAQ_JYwK4L2i64lr3GRXGlYlikGTVzWbys_E,5351 +importlib_metadata/_meta.py,sha256=EtHyiJ5kGzWFDfKyQ2XQp6Vu113CeadKW1Vf6aGc1B4,1765 +importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166 +importlib_metadata/_typing.py,sha256=EQKhhsEgz_Sa-FnePI-faC72rNOOQwopjA1i5pG8FDU,367 +importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608 +importlib_metadata/compat/py39.py,sha256=J3W7PUVRPNYMmcvT12RF8ndBU9e8_T0Ac4U87Bsrq70,1187 +importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379 +importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5c1d8bbc02a6624cf8e957c40e6f761c1575d180 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/licenses/LICENSE @@ -0,0 +1,73 @@ +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 2025 [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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbb07547a19c30031d13c45cf01cba61dc434e47 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata-8.7.1.dist-info/top_level.txt @@ -0,0 +1 @@ +importlib_metadata diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..508b02e4fce3fa9463b7466138cca7414db0e9b9 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__init__.py @@ -0,0 +1,1191 @@ +""" +APIs exposing metadata from third-party Python packages. + +This codebase is shared between importlib.metadata in the stdlib +and importlib_metadata in PyPI. See +https://github.com/python/importlib_metadata/wiki/Development-Methodology +for more detail. +""" + +from __future__ import annotations + +import abc +import collections +import email +import functools +import itertools +import operator +import os +import pathlib +import posixpath +import re +import sys +import textwrap +import types +from collections.abc import Iterable, Mapping +from contextlib import suppress +from importlib import import_module +from importlib.abc import MetaPathFinder +from itertools import starmap +from typing import Any + +from . import _meta +from ._collections import FreezableDefaultDict, Pair +from ._compat import ( + NullFinder, + install, +) +from ._functools import method_cache, noop, pass_none, passthrough +from ._itertools import always_iterable, bucket, unique_everseen +from ._meta import PackageMetadata, SimplePath +from ._typing import md_none +from .compat import py39, py311 + +__all__ = [ + 'Distribution', + 'DistributionFinder', + 'PackageMetadata', + 'PackageNotFoundError', + 'SimplePath', + '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] # make readonly + (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 _EntryPointMatch(types.SimpleNamespace): + module: str + attr: str + extras: str + + +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'] + + If the value package or module are not valid identifiers, a + ValueError is raised on access. + + >>> EntryPoint(name=None, group=None, value='invalid-name').module + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + >>> EntryPoint(name=None, group=None, value='invalid-name').attr + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + >>> EntryPoint(name=None, group=None, value='invalid-name').extras + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + + The same thing happens on construction. + + >>> EntryPoint(name=None, group=None, value='invalid-name') + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + + """ + + 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: Distribution | None = None + + def __init__(self, name: str, value: str, group: str) -> None: + vars(self).update(name=name, value=value, group=group) + self.module + + 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. + """ + module = import_module(self.module) + attrs = filter(None, (self.attr or '').split('.')) + return functools.reduce(getattr, attrs, module) + + @property + def module(self) -> str: + return self._match.module + + @property + def attr(self) -> str: + return self._match.attr + + @property + def extras(self) -> list[str]: + return re.findall(r'\w+', self._match.extras or '') + + @functools.cached_property + def _match(self) -> _EntryPointMatch: + match = self.pattern.match(self.value) + if not match: + raise ValueError( + 'Invalid object reference. ' + 'See https://packaging.python.org' + '/en/latest/specifications/entry-points/#data-model', + self.value, + ) + return _EntryPointMatch(**match.groupdict()) + + 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 + """ + self._disallow_dist(params) + attrs = (getattr(self, param) for param in params) + return all(map(operator.eq, params.values(), attrs)) + + @staticmethod + def _disallow_dist(params): + """ + Querying by dist is not allowed (dist objects are not comparable). + >>> EntryPoint(name='fan', value='fav', group='fag').matches(dist='foo') + Traceback (most recent call last): + ... + ValueError: "dist" is not suitable for matching... + """ + if "dist" in params: + raise ValueError( + '"dist" is not suitable for matching. ' + "Instead, use Distribution.entry_points.select() on a " + "located distribution." + ) + + 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] # Work with str instead of int + """ + 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: FileHash | None + size: int + dist: Distribution + + def read_text(self, encoding: str = 'utf-8') -> str: + 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) -> str | None: + """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. + + This method is used by callers of ``Distribution.files()`` to + locate files within the distribution. If it's possible for a + Distribution to represent files in the distribution as + ``SimplePath`` objects, it should implement this method + to resolve such objects. + + Some Distribution providers may elect not to resolve SimplePath + objects within the distribution by raising a + NotImplementedError, but consumers of such a Distribution would + be unable to invoke ``Distribution.files()``. + """ + + @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._prefer_valid(cls.discover(name=name)))) + except StopIteration: + raise PackageNotFoundError(name) + + @classmethod + def discover( + cls, *, context: DistributionFinder.Context | None = 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 _prefer_valid(dists: Iterable[Distribution]) -> Iterable[Distribution]: + """ + Prefer (move to the front) distributions that have metadata. + + Ref python/importlib_resources#489. + """ + buckets = bucket(dists, lambda dist: bool(dist.metadata)) + return itertools.chain(buckets[True], buckets[False]) + + @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 | None: + """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. + """ + + 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('') + ) + return self._assemble_message(text) + + @staticmethod + @pass_none + def _assemble_message(text: str) -> _meta.PackageMetadata: + # deferred for performance (python/cpython#109829) + from . import _adapters + + return _adapters.Message(email.message_from_string(text)) + + @property + def name(self) -> str: + """Return the 'Name' metadata for the distribution package.""" + return md_none(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 md_none(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) -> list[PackagePath] | None: + """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) -> list[str] | None: + """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): + # Deferred for performance (python/importlib_metadata#503) + import json + + 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. + """ + + +@passthrough +def _clear_after_fork(cached): + """Ensure ``func`` clears cached state after ``fork`` when supported. + + ``FastPath`` caches zip-backed ``pathlib.Path`` objects that retain a + reference to the parent's open ``ZipFile`` handle. Re-using a cached + instance in a forked child can therefore resurrect invalid file pointers + and trigger ``BadZipFile``/``OSError`` failures (python/importlib_metadata#520). + Registering ``cache_clear`` with ``os.register_at_fork`` keeps each process + on its own cache. + """ + getattr(os, 'register_at_fork', noop)(after_in_child=cached.cache_clear) + + +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 + """ + + @_clear_after_fork # type: ignore[misc] + @functools.lru_cache() + 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): + # deferred for performance (python/importlib_metadata#502) + from zipp.compat.overlay import zipfile + + zip_path = zipfile.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: str | None): + 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]) -> str | None: + 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 | None: + """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) -> list[PackagePath] | None: + """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) -> list[str] | None: + """ + 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(md_none(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) -> str | None: + """ + 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' + """ + # Defer import of inspect for performance (python/cpython#118761) + import inspect + + return _topmost(name) or inspect.getmodulename(name) 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dc66e0f7d275061a4f262c6c0151827ae42dd1e Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d622a6cabc2b6804558351a5b546709896bca4f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_adapters.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9100273f5538c9e2f450a4ad4598c7d665866734 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_collections.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..036277822cdcb7004ca9c34ba009b75e93c26d64 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_compat.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc85738e9dea6c438e0bcc6f257f4cc8d65390d9 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_functools.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96081991ec51858c777675f4cfe664bd02e877b3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_itertools.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..670aea270fc48c2397acce0d0c7d0249f013f3bb Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_meta.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57d1cb7632ad5a40dbd5afb697a7f57e4553cdbd Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_text.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_typing.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_typing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f87ae4cbe75fcd9cdc81c815e8b01cd2f6b28822 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/_typing.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2706d3c6c6d4e5fe1ed245222ea1a265efa196ef Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/__pycache__/diagnose.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..dede395d79a38bab322d56a66d916703af84f77b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py @@ -0,0 +1,136 @@ +import email.message +import email.policy +import re +import textwrap + +from ._text import FoldedCase + + +class RawPolicy(email.policy.EmailPolicy): + def fold(self, name, value): + folded = self.linesep.join( + textwrap + .indent(value, prefix=' ' * 8, predicate=lambda line: True) + .lstrip() + .splitlines() + ) + return f'{name}: {folded}{self.linesep}' + + +class Message(email.message.Message): + r""" + Specialized Message subclass to handle metadata naturally. + + Reads values that may have newlines in them and converts the + payload to the Description. + + >>> msg_text = textwrap.dedent(''' + ... Name: Foo + ... Version: 3.0 + ... License: blah + ... de-blah + ... + ... First line of description. + ... Second line of description. + ... + ... Fourth line! + ... ''').lstrip().replace('', '') + >>> msg = Message(email.message_from_string(msg_text)) + >>> msg['Description'] + 'First line of description.\nSecond line of description.\n\nFourth line!\n' + + Message should render even if values contain newlines. + + >>> print(msg) + Name: Foo + Version: 3.0 + License: blah + de-blah + Description: First line of description. + Second line of description. + + Fourth line! + + + """ + + 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" + indent = ' ' * 8 + if not value or '\n' + indent not in value: + return value + return textwrap.dedent(indent + value) + + headers = [(key, redent(value)) for key, value in vars(self)['_headers']] + if self._payload: + headers.append(('Description', self.get_payload())) + self.set_payload('') + return headers + + def as_string(self): + return super().as_string(policy=RawPolicy()) + + @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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_collections.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5045d36be57251000393b32baba7baa9cd8c4f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_collections.py @@ -0,0 +1,34 @@ +import collections +import typing + + +# 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(typing.NamedTuple): + name: str + value: str + + @classmethod + def parse(cls, text): + return cls(*map(str.strip, text.split("=", 1))) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_compat.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..01356d69b97c95a6d41818e5c2c50a299146bef4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_compat.py @@ -0,0 +1,56 @@ +import platform +import sys + +__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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_functools.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..b1fd04a84ab4c129b19f71a13f7489c37d1a9e9e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_functools.py @@ -0,0 +1,135 @@ +import functools +import types +from typing import Callable, TypeVar + + +# 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 + + +# From jaraco.functools 4.4 +def noop(*args, **kwargs): + """ + A no-operation function that does nothing. + + >>> noop(1, 2, three=3) + """ + + +_T = TypeVar('_T') + + +# From jaraco.functools 4.4 +def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]: + """ + Wrap the function to always return the first parameter. + + >>> passthrough(print)('3') + 3 + '3' + """ + + @functools.wraps(func) + def wrapper(first: _T, *args, **kwargs) -> _T: + func(first, *args, **kwargs) + return first + + return wrapper # type: ignore[return-value] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..79d37198ce7aff317873f6e4e84cd904a46a69de --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py @@ -0,0 +1,171 @@ +from collections import defaultdict, deque +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,)) + + +# Copied from more_itertools 10.3 +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) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_meta.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..0c20eff3da75223a5ca76a1743b7c5b8fa1dc1f6 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_meta.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import os +from collections.abc import Iterator +from typing import ( + Any, + Protocol, + TypeVar, + 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 + ) -> str | None: ... # pragma: no cover + + @overload + def get(self, name: str, failobj: _T) -> str | _T: ... # pragma: no cover + + # overload per python/importlib_metadata#435 + @overload + def get_all( + self, name: str, failobj: None = None + ) -> list[Any] | None: ... # pragma: no cover + + @overload + def get_all(self, name: str, failobj: _T) -> list[Any] | _T: + """ + Return all values associated with a possibly multi-valued key. + """ + + @property + def json(self) -> dict[str, 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: str | os.PathLike[str] + ) -> SimplePath: ... # pragma: no cover + + def __truediv__( + self, other: 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_text.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_text.py new file mode 100644 index 0000000000000000000000000000000000000000..c88cfbb2349c6401336bc5ba6623f51afd1eb59d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_typing.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..32b1d2b98ac987e8361f60362b8bdabcdc6fb1c8 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/_typing.py @@ -0,0 +1,15 @@ +import functools +import typing + +from ._meta import PackageMetadata + +md_none = functools.partial(typing.cast, PackageMetadata) +""" +Suppress type errors for optional metadata. + +Although Distribution.metadata can return None when metadata is corrupt +and thus None, allow callers to assume it's not None and crash if +that's the case. + +# python/importlib_metadata#493 +""" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8f7cac7a6e424aadee980e0e441237fa96db276 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ce14b259804207ba1b4ece106adebfd487e39e9 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py311.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06990e43585579cd472fbd6de976e6244b954788 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/__pycache__/py39.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py311.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5327436f9b1d9eae371e321c491a270634b3cf --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py new file mode 100644 index 0000000000000000000000000000000000000000..3eb9c01ecbbdcdf7b79d8840ee91c2fe7a734a1c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/compat/py39.py @@ -0,0 +1,42 @@ +""" +Compatibility layer with Python 3.8/3.9 +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: # pragma: no cover + # Prevent circular imports on runtime. + from .. import Distribution, EntryPoint +else: + Distribution = EntryPoint = Any + +from .._typing import md_none + + +def normalized_name(dist: Distribution) -> str | None: + """ + 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 md_none(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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/diagnose.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..e405471ac4d94371b1ee9b1622227ff76b337180 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/py.typed b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/importlib_metadata/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1bb5a44356f00884a71ceeefd24ded6caaba2418 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..797b9da7334a85347e0439d48c11ee0d1b101f49 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/METADATA @@ -0,0 +1,96 @@ +Metadata-Version: 2.1 +Name: jaraco.text +Version: 4.0.0 +Summary: Module for text manipulation +Author-email: "Jason R. Coombs" +Project-URL: Source, 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: 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: inflect +Requires-Dist: inflect ; extra == 'inflect' +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: pathlib2 ; (python_version < "3.10") and extra == 'test' +Requires-Dist: pytest-ruff >=0.2.1 ; (sys_platform != "cygwin") 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..af65a9daa8caed85a09198e65f37278ec0532d91 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/RECORD @@ -0,0 +1,14 @@ +jaraco.text-4.0.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +jaraco.text-4.0.0.dist-info/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +jaraco.text-4.0.0.dist-info/METADATA,sha256=XC_QkBLJVPE5sQYkl41TNaZUw0AUzQb29GbKaD28nFY,3731 +jaraco.text-4.0.0.dist-info/RECORD,, +jaraco.text-4.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco.text-4.0.0.dist-info/WHEEL,sha256=Wyh-_nZ0DJYolHNn1_hMa4lM7uDedD_RGVwbmTjyItk,91 +jaraco.text-4.0.0.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=lazNYXo8IhOR1bFigLAyGiiQao6jtO3KGWh8bZZPx3c,16762 +jaraco/text/layouts.py,sha256=HTC8aSTLZ7uXipyOXapRMC158juecjK6RVwitfmZ9_w,643 +jaraco/text/show-newlines.py,sha256=jT0vp4gLhG20hX2lTB-zKo_i3NgKzj79yRAdz4eMzIM,903 +jaraco/text/strip-prefix.py,sha256=NfVXV8JVNo6nqcuYASfMV7_y4Eo8zMQqlCOGvAnRIVw,412 +jaraco/text/to-dvorak.py,sha256=36nPPsiifwv6RfpAb--3zpgbIx8ohnnI1aR29IJTO9s,118 +jaraco/text/to-qwerty.py,sha256=IQoFY9v7vLTEybcput4KBYm_5GR35pmtgZ_xyrmdTgI,118 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ecaf39f3c3df8b0075a2951da9b1a27fcb08a173 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (71.1.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco.text-4.0.0.dist-info/top_level.txt @@ -0,0 +1 @@ +jaraco diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/context/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/context/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..41ad609edd407ac93f87731d07435a25a3d6435d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/context/__init__.py @@ -0,0 +1,367 @@ +from __future__ import annotations + +import contextlib +import errno +import functools +import operator +import os +import platform +import shutil +import stat +import subprocess +import sys +import tempfile +import urllib.request +from collections.abc 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 URL to a tarball, download, extract, yield, then clean up. + + Assumes everything in the tarball is prefixed with a common + directory. That common path is stripped and the contents + are extracted to ``target_dir``, similar to passing + ``-C {target} --strip-components 1`` to the ``tar`` command. + + Uses the streaming protocol to extract the contents from a + stream in a single pass without loading the whole file into + memory. + + >>> 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 the target is not specified, contents are extracted to a + directory relative to the current working directory named after + the name of the file as extracted from the URL. + + >>> target = getfixture('tmp_path') + >>> with pushd(target), tarball(url): + ... target.joinpath('served').is_dir() + True + """ + if target_dir is None: + target_dir = os.path.basename(url).replace('.tar.gz', '').replace('.tgz', '') + 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=_default_filter) + yield target_dir + finally: + shutil.rmtree(target_dir) + + +def _compose_tarfile_filters(*filters): + def compose_two(f1, f2): + return lambda member, path: f1(f2(member, path), path) + + return functools.reduce(compose_two, filters, lambda member, path: member) + + +def strip_first_component( + member: tarfile.TarInfo, + path, +) -> tarfile.TarInfo: + _, member.name = member.name.split('/', 1) + return member + + +_default_filter = _compose_tarfile_filters(tarfile.data_filter, strip_first_component) + + +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) +""" +A tarball context with the current working directory pointing to the contents. +""" + + +def remove_readonly(func, path, exc_info): + """ + Add support for removing read-only files on Windows. + """ + _, exc, _ = exc_info + if func in (os.rmdir, os.remove, os.unlink) and exc.errno == errno.EACCES: + # change the file to be readable,writable,executable: 0777 + os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) + # retry + func(path) + else: + raise + + +def robust_remover(): + return ( + functools.partial(shutil.rmtree, onerror=remove_readonly) + if platform.system() == 'Windows' + else shutil.rmtree + ) + + +@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) + >>> assert not os.path.exists(the_dir) + """ + temp_dir = tempfile.mkdtemp() + try: + yield temp_dir + finally: + remover(temp_dir) + + +robust_temp_dir = functools.partial(temp_dir, remover=robust_remover()) + + +@contextlib.contextmanager +def repo_context( + url, branch: str | None = None, quiet: bool = True, dest_ctx=robust_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. + + >>> getfixture('ensure_git') + >>> getfixture('needs_internet') + >>> repo = repo_context('https://github.com/jaraco/jaraco.context') + >>> with repo as dest: + ... listing = os.listdir(dest) + >>> 'README.rst' in listing + True + """ + exe = 'git' if 'git' in url else 'hg' + with dest_ctx() as repo_dir: + cmd = [exe, 'clone', url, repo_dir] + cmd.extend(['--branch', branch] * bool(branch)) + stream = subprocess.DEVNULL if quiet else None + subprocess.check_call(cmd, stdout=stream, stderr=stream) + yield repo_dir + + +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). + + Useful in conjunction with console entry point functions. + + >>> 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/context/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/context/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d333598b3a1bfd95ca82dba5ba2051f4847ad123 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/context/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/context/py.typed b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/context/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..df32e2e924bdfb14aa7dfcfc503d22081c1f0d74 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.py @@ -0,0 +1,722 @@ +from __future__ import annotations + +import collections.abc +import functools +import inspect +import itertools +import operator +import time +import types +import warnings +from typing import Callable, TypeVar + +import more_itertools + + +def compose(*funcs): + """ + Compose any number of unary functions into a single unary function. + + Comparable to + `function composition `_ + in mathematics: + + ``h = g ∘ f`` implies ``h(x) = g(f(x))``. + + In Python, ``h = compose(g, f)``. + + >>> 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 + + +_T = TypeVar('_T') + + +def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]: + """ + Wrap the function to always return the first parameter. + + >>> passthrough(print)('3') + 3 + '3' + """ + + @functools.wraps(func) + def wrapper(first: _T, *args, **kwargs) -> _T: + func(first, *args, **kwargs) + return first + + return wrapper + + +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 none_as(value, replacement=None): + """ + >>> none_as(None, 'foo') + 'foo' + >>> none_as('bar', 'foo') + 'bar' + """ + return replacement if value is None else value + + +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') # noqa: PYI024 # Internal; stubs used for typing + + @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)) + + +_T = TypeVar('_T') + + +def chainable(method: Callable[[_T, ...], None]) -> Callable[[_T, ...], _T]: + """ + Wrap an instance method to always return self. + + + >>> class Dingus: + ... @chainable + ... def set_attr(self, name, val): + ... setattr(self, name, val) + >>> d = Dingus().set_attr('a', 'eh!') + >>> d.a + 'eh!' + >>> d2 = Dingus().set_attr('a', 'eh!').set_attr('b', 'bee!') + >>> d2.a + d2.b + 'eh!bee!' + + Enforces that the return value is null. + + >>> class BorkedDingus: + ... @chainable + ... def set_attr(self, name, val): + ... setattr(self, name, val) + ... return len(name) + >>> BorkedDingus().set_attr('a', 'eh!') + Traceback (most recent call last): + ... + AssertionError + """ + + @functools.wraps(method) + def wrapper(self, *args, **kwargs): + assert method(self, *args, **kwargs) is None + return self + + return wrapper + + +def noop(*args, **kwargs): + """ + A no-operation function that does nothing. + + >>> noop(1, 2, three=3) + """ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6f834bf06d962463dd198c40931ad86546b1a359 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__init__.pyi @@ -0,0 +1,123 @@ +from collections.abc import Callable, Hashable, Iterator +from functools import partial +from operator import methodcaller +from typing import ( + Any, + Generic, + Protocol, + TypeVar, + overload, +) + +from typing_extensions import Concatenate, ParamSpec, TypeVarTuple, Unpack + +_P = ParamSpec('_P') +_R = TypeVar('_R') +_T = TypeVar('_T') +_Ts = TypeVarTuple('_Ts') +_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: float = ..., + trap: type[BaseException] | tuple[type[BaseException], ...] = ..., +) -> _R: ... +def retry( + cleanup: Callable[..., None] = ..., + retries: 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]]: ... +def splat(func: Callable[[Unpack[_Ts]], _R]) -> Callable[[tuple[Unpack[_Ts]]], _R]: ... diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1edf91069bfc86536be1b2fbb8ee95a462c1fa9c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/py.typed b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/functools/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/Lorem ipsum.txt new file mode 100644 index 0000000000000000000000000000000000000000..986f944b60b9900c22464a0c027d713854cc204e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8567200ad7fad1ea127ff5f81c5509d96d37cbd7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__init__.py @@ -0,0 +1,647 @@ +import functools +import itertools +import re +import textwrap + +from typing import Iterable + +try: + from importlib.resources import files # type: ignore +except ImportError: # pragma: nocover + from importlib_resources import files # type: ignore + +from jaraco.context import ExceptionTrap +from jaraco.functools import compose, method_cache + + +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 clean(text.splitlines()) + + +def clean(lines: Iterable[str]): + """ + Yield non-blank, non-comment elements from lines. + """ + return filter(_nonblank, map(str.strip, lines)) + + +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 + + +def lines_from(input): + """ + Generate lines from a :class:`importlib.resources.abc.Traversable` path. + + >>> lines = lines_from(files(__name__).joinpath('Lorem ipsum.txt')) + >>> next(lines) + 'Lorem ipsum...' + >>> next(lines) + 'Curabitur pretium...' + """ + with input.open(encoding='utf-8') as stream: + yield from stream diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eb73e1d24d9bfb2597501f9676601490813fac0 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..502d0ea039490c62d70e0e1d6099d945150d266b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/layouts.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eec3fe737900e0b64bdb3db4f43283a758cce458 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/show-newlines.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da822fe142bd08b9536642af78276bc00fee48dc Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/strip-prefix.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ac516a6f7c9554f6ce33d3f4aef8ba82d8a50a7 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-dvorak.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..439ac6b55901b8fcb6da17e027361c82079c5d5d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/__pycache__/to-qwerty.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/layouts.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..9636f0f7b53cb4d1ea5842e1eb62c998ddb91070 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py new file mode 100644 index 0000000000000000000000000000000000000000..ef4cc54c9e457728d63e9fb6033950fed074016c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/show-newlines.py @@ -0,0 +1,32 @@ +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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/strip-prefix.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/strip-prefix.py new file mode 100644 index 0000000000000000000000000000000000000000..761717a9b9e1f837eeacf0e888822f6fad881361 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py new file mode 100644 index 0000000000000000000000000000000000000000..14c8981e441dee59afa715853c87a84796b931fc --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/to-dvorak.py @@ -0,0 +1,5 @@ +import sys + +from . import layouts + +__name__ == '__main__' and layouts._translate_stream(sys.stdin, layouts.to_dvorak) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py new file mode 100644 index 0000000000000000000000000000000000000000..23596fda930cde864e643152ec706b6149f130f2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco/text/to-qwerty.py @@ -0,0 +1,5 @@ +import sys + +from . import layouts + +__name__ == '__main__' and layouts._translate_stream(sys.stdin, layouts.to_qwerty) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8fb5e53da3f958a6566c3c379b50f3e59c04320e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/METADATA @@ -0,0 +1,82 @@ +Metadata-Version: 2.4 +Name: jaraco.context +Version: 6.1.0 +Summary: Useful decorators and context managers +Author-email: "Jason R. Coombs" +License-Expression: MIT +Project-URL: Source, https://github.com/jaraco/jaraco.context +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: backports.tarfile; python_version < "3.12" +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: jaraco.test>=5.6.0; extra == "test" +Requires-Dist: portend; 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" +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: enabler +Requires-Dist: pytest-enabler>=3.4; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy>=1.0.1; extra == "type" +Requires-Dist: mypy<1.19; platform_python_implementation == "PyPy" and extra == "type" +Dynamic: license-file + +.. 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/astral-sh/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-2025-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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e5169f66596795d5883da25a272970be0e8acd50 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/RECORD @@ -0,0 +1,9 @@ +jaraco/context/__init__.py,sha256=br1ydYGo1Xr_Pu1anuEdd-QrjUiz_EY5L_5E4C03L4w,9809 +jaraco/context/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco_context-6.1.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +jaraco_context-6.1.0.dist-info/METADATA,sha256=BDXr_FIFXFqZdO0gwXG2RUOD6vnbsVCIFLp62XxZ1xI,4270 +jaraco_context-6.1.0.dist-info/RECORD,, +jaraco_context-6.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco_context-6.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +jaraco_context-6.1.0.dist-info/licenses/LICENSE,sha256=l1WhhRlmbl8PTK49qtPXASvK5IpgCzEjfXXp_hNOZoM,1076 +jaraco_context-6.1.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c891f411dc44c70ff121531af2ee189d3da4c871 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/licenses/LICENSE @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) 2026 + +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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/top_level.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_context-6.1.0.dist-info/top_level.txt @@ -0,0 +1 @@ +jaraco diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..f2150dd88bea2b8701c2b6199bfc53b1fdb8f9a7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/METADATA @@ -0,0 +1,69 @@ +Metadata-Version: 2.4 +Name: jaraco.functools +Version: 4.4.0 +Summary: Functools like those found in stdlib +Author-email: "Jason R. Coombs" +License-Expression: MIT +Project-URL: Source, https://github.com/jaraco/jaraco.functools +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: more_itertools +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: jaraco.classes; 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" +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: enabler +Requires-Dist: pytest-enabler>=3.4; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy>=1.0.1; extra == "type" +Requires-Dist: mypy<1.19; platform_python_implementation == "PyPy" and extra == "type" +Dynamic: license-file + +.. 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/astral-sh/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-2025-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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3516c9f0396cc14d4ee246160a425447aad03abe --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/RECORD @@ -0,0 +1,10 @@ +jaraco/functools/__init__.py,sha256=ZJx9cMs2Nvk2xGUl8OjVGkpjdOaNlSzJrN4dGglgX2g,18599 +jaraco/functools/__init__.pyi,sha256=K4DcbnYIHE5QlMxqf9-cVp-WhycrhuTao4J7O7TMq4Y,3907 +jaraco/functools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco_functools-4.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +jaraco_functools-4.4.0.dist-info/METADATA,sha256=LnnajcNGmSSr46yLIqP-tWkqeb-fR7vIa2U11hhkGEk,2960 +jaraco_functools-4.4.0.dist-info/RECORD,, +jaraco_functools-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco_functools-4.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +jaraco_functools-4.4.0.dist-info/licenses/LICENSE,sha256=WlfLTbheKi3YjCkGKJCK3VfjRRRJ4KmnH9-zh3b9dZ0,1076 +jaraco_functools-4.4.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f60bd572013c6abcb3a82ba9b50d84935de6394f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) 2025 + +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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/top_level.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/jaraco_functools-4.4.0.dist-info/top_level.txt @@ -0,0 +1 @@ +jaraco diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..bb7a3db109905db8cc7f1f2f5047e0b609aaf4ce --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/METADATA @@ -0,0 +1,283 @@ +Metadata-Version: 2.4 +Name: more-itertools +Version: 10.8.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.9 +Description-Content-Type: text/x-rst +License-Expression: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries +License-File: LICENSE +Project-URL: Documentation, https://more-itertools.readthedocs.io/en/stable/ +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 `_, | +| | `interleave_randomly `_, | +| | `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 `_, | +| | `argmin `_, | +| | `argmax `_, | +| | `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 `_, | +| | `extract `_, | +| | `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 `_, | +| | `matmul `_, | +| | `polynomial_from_roots `_, | +| | `polynomial_derivative `_, | +| | `polynomial_eval `_, | +| | `sum_of_squares `_, | +| | `running_median `_, | +| | `totient `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Integer math | `factor `_, | +| | `is_prime `_, | +| | `multinomial `_, | +| | `nth_prime `_, | +| | `sieve `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Combinatorics | `circular_shifts `_, | +| | `derangements `_, | +| | `gray_product `_, | +| | `outer_product `_, | +| | `partitions `_, | +| | `set_partitions `_, | +| | `powerset `_, | +| | `powerset_of_sets `_ | +| +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| | `distinct_combinations `_, | +| | `distinct_permutations `_ | +| +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| | `combination_index `_, | +| | `combination_with_replacement_index `_, | +| | `permutation_index `_, | +| | `product_index `_ | +| +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| | `nth_combination `_, | +| | `nth_combination_with_replacement `_, | +| | `nth_permutation `_, | +| | `nth_product `_ | +| +-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| | `random_combination `_, | +| | `random_combination_with_replacement `_, | +| | `random_permutation `_, | +| | `random_product `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Wrapping | `always_iterable `_, | +| | `always_reversible `_, | +| | `countable `_, | +| | `consumer `_, | +| | `with_iter `_, | +| | `iter_except `_ | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Others | `locate `_, | +| | `rlocate `_, | +| | `replace `_, | +| | `numeric_range `_, | +| | `side_effect `_, | +| | `iterate `_, | +| | `loops `_, | +| | `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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..61ef7d6dd02d0a26d3373299cd2efa792fb23165 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/RECORD @@ -0,0 +1,13 @@ +more_itertools-10.8.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +more_itertools-10.8.0.dist-info/METADATA,sha256=arNRUUWr5YsGfwh8hnYxz0z11lP-2BuWQu4SCGw5BLg,39413 +more_itertools-10.8.0.dist-info/RECORD,, +more_itertools-10.8.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +more_itertools-10.8.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +more_itertools-10.8.0.dist-info/licenses/LICENSE,sha256=CfHIyelBrz5YTVlkHqm4fYPAyw_QB-te85Gn4mQ8GkY,1053 +more_itertools/__init__.py,sha256=5F7E_zpoGcEBW_T_3WE0WYYt8j-gJodIuiBcOJxrOv8,149 +more_itertools/__init__.pyi,sha256=5B3eTzON1BBuOLob1vCflyEb2lSd6usXQQ-Cv-hXkeA,43 +more_itertools/more.py,sha256=mNPKKu5UI7lRL460vgm0QTCWFiGMVCMosSPxVSdibos,163690 +more_itertools/more.pyi,sha256=fpEgNX3O66wY5cnT-s5VYDKNUpAcaCyU3iP84It3OOM,27119 +more_itertools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +more_itertools/recipes.py,sha256=Ma-kuBNZDFhaQDbIJgRmnrG86WzaupbOyUV3v8je3xw,41811 +more_itertools/recipes.pyi,sha256=LNRwN-OL3nkMfQAqx-PPc1fBaetUObb_Z6mdePyzh1c,6226 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0a523bece3e50519653c4d7a38399baa487fefa1 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools-10.8.0.dist-info/licenses/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..24216c5c1feb8b6017f71d096124e5db0aac5bd2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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.8.0' diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__init__.pyi b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..96f6e36c7f4ac9ea0aebdcd9e11b8d1ff092d2ef --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__init__.pyi @@ -0,0 +1,2 @@ +from .more import * +from .recipes import * diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96fe26a694bb84e9565b1bb428ffcd88741edb91 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db5c99966c3a0ddf9d5c715fda61bf3404b78258 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/__pycache__/recipes.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/more.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/more.py new file mode 100644 index 0000000000000000000000000000000000000000..bf501956ae6c77e7597948abdaede960ca259444 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/more.py @@ -0,0 +1,5303 @@ +import math +import warnings + +from collections import Counter, defaultdict, deque, abc +from collections.abc import Sequence +from contextlib import suppress +from functools import cached_property, partial, reduce, wraps +from heapq import heapify, heapreplace +from itertools import ( + chain, + combinations, + compress, + count, + cycle, + dropwhile, + groupby, + islice, + permutations, + repeat, + starmap, + takewhile, + tee, + zip_longest, + product, +) +from math import comb, e, exp, factorial, floor, fsum, log, log1p, perm, tau +from math import ceil +from queue import Empty, Queue +from random import random, randrange, shuffle, uniform +from operator import ( + attrgetter, + is_not, + itemgetter, + lt, + mul, + neg, + sub, + gt, +) +from sys import hexversion, maxsize +from time import monotonic + +from .recipes import ( + _marker, + _zip_equal, + UnequalIterablesError, + consume, + first_true, + flatten, + is_prime, + nth, + powerset, + sieve, + take, + unique_everseen, + all_equal, + batched, +) + +__all__ = [ + 'AbortThread', + 'SequenceView', + 'UnequalIterablesError', + 'adjacent', + 'all_unique', + 'always_iterable', + 'always_reversible', + 'argmax', + 'argmin', + 'bucket', + 'callback_iter', + 'chunked', + 'chunked_even', + 'circular_shifts', + 'collapse', + 'combination_index', + 'combination_with_replacement_index', + 'consecutive_groups', + 'constrained_batches', + 'consumer', + 'count_cycle', + 'countable', + 'derangements', + 'dft', + 'difference', + 'distinct_combinations', + 'distinct_permutations', + 'distribute', + 'divide', + 'doublestarmap', + 'duplicates_everseen', + 'duplicates_justseen', + 'classify_unique', + 'exactly_n', + 'extract', + 'filter_except', + 'filter_map', + 'first', + 'gray_product', + 'groupby_transform', + 'ichunked', + 'iequals', + 'idft', + 'ilen', + 'interleave', + 'interleave_evenly', + 'interleave_longest', + 'interleave_randomly', + '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_prime', + '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+ +try: + from math import sumprod as _fsumprod + +except ImportError: # pragma: no cover + # Extended precision algorithms from T. J. Dekker, + # "A Floating-Point Technique for Extending the Available Precision" + # https://csclub.uwaterloo.ca/~pbarfuss/dekker1971.pdf + # Formulas: (5.5) (5.6) and (5.8). Code: mul12() + + def dl_split(x: float): + "Split a float into two half-precision components." + t = x * 134217729.0 # Veltkamp constant = 2.0 ** 27 + 1 + hi = t - (t - x) + lo = x - hi + return hi, lo + + def dl_mul(x, y): + "Lossless multiplication." + xx_hi, xx_lo = dl_split(x) + yy_hi, yy_lo = dl_split(y) + p = xx_hi * yy_hi + q = xx_hi * yy_lo + xx_lo * yy_hi + z = p + q + zz = p - z + q + xx_lo * yy_lo + return z, zz + + def _fsumprod(p, q): + return fsum(chain.from_iterable(map(dl_mul, p, q))) + + +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 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 + if getattr(iterable, '__reversed__', None): + return next(reversed(iterable)) + 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 value 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*. + + For example, there are 168 prime numbers below 1,000: + + >>> ilen(sieve(1000)) + 168 + + Equivalent to, but faster than:: + + def ilen(iterable): + count = 0 + for _ in iterable: + count += 1 + return count + + This fully consumes the iterable, so handle with care. + + """ + # This is the "most beautiful of the fast variants" of this function. + # If you think you can improve on it, please ensure that your version + # is both 10x faster and 10x more beautiful. + return sum(compress(repeat(1), zip(iterable))) + + +def iterate(func, start): + """Return ``start``, ``func(start)``, ``func(func(start))``, ... + + Produces an infinite iterator. To add a stopping condition, + use :func:`take`, ``takewhile``, or :func:`takewhile_inclusive`:. + + >>> take(10, iterate(lambda x: 2*x, 1)) + [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] + + >>> collatz = lambda x: 3*x + 1 if x%2==1 else x // 2 + >>> list(takewhile_inclusive(lambda x: x!=1, iterate(collatz, 10))) + [10, 5, 16, 8, 4, 2, 1] + + """ + with suppress(StopIteration): + while True: + yield start + start = func(start) + + +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 few 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. + + """ + iterator = iter(iterable) + for first in iterator: + for second in iterator: + msg = ( + f'Expected exactly one item in iterable, but got {first!r}, ' + f'{second!r}, and perhaps more.' + ) + raise too_long or ValueError(msg) + return first + raise too_short or ValueError('too few items in iterable (expected 1)') + + +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 the actual number of items. If it has more than *n* items, call function + *too_long* with the number ``n + 1``. + + >>> 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, + f'Too few items in iterable (got {item_count})', + ) + + if too_long is None: + too_long = lambda item_count: raise_( + ValueError, + f'Too many items in iterable (got at least {item_count})', + ) + + it = iter(iterable) + + sent = 0 + for item in islice(it, n): + yield item + sent += 1 + + if sent < n: + too_short(sent) + return + + for item in it: + too_long(n + 1) + return + + +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 yielding from ``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. The function :func:`multinomial` computes this directly. + + 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)] + + *iterable* need not be sortable, but note that using equal (``x == y``) + but non-identical (``id(x) != id(y)``) elements may produce surprising + behavior. For example, ``1`` and ``True`` are equal but non-identical: + + >>> list(distinct_permutations([1, True, '3'])) # doctest: +SKIP + [ + (1, True, '3'), + (1, '3', True), + ('3', 1, True) + ] + >>> list(distinct_permutations([1, 2, '3'])) # doctest: +SKIP + [ + (1, 2, '3'), + (1, '3', 2), + (2, 1, '3'), + (2, '3', 1), + ('3', 1, 2), + ('3', 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 = list(iterable) + + try: + items.sort() + sortable = True + except TypeError: + sortable = False + + indices_dict = defaultdict(list) + + for item in items: + indices_dict[items.index(item)].append(item) + + indices = [items.index(item) for item in items] + indices.sort() + + equivalent_items = {k: cycle(v) for k, v in indices_dict.items()} + + def permuted_items(permuted_indices): + return tuple( + next(equivalent_items[index]) for index in permuted_indices + ) + + size = len(items) + if r is None: + r = size + + # functools.partial(_partial, ... ) + algorithm = _full if (r == size) else partial(_partial, r=r) + + if 0 < r <= size: + if sortable: + return algorithm(items) + else: + return ( + permuted_items(permuted_indices) + for permuted_indices in algorithm(indices) + ) + + return iter(() if r else ((),)) + + +def derangements(iterable, r=None): + """Yield successive derangements of the elements in *iterable*. + + A derangement is a permutation in which no element appears at its original + index. In other words, a derangement is a permutation that has no fixed points. + + Suppose Alice, Bob, Carol, and Dave are playing Secret Santa. + The code below outputs all of the different ways to assign gift recipients + such that nobody is assigned to himself or herself: + + >>> for d in derangements(['Alice', 'Bob', 'Carol', 'Dave']): + ... print(', '.join(d)) + Bob, Alice, Dave, Carol + Bob, Carol, Dave, Alice + Bob, Dave, Alice, Carol + Carol, Alice, Dave, Bob + Carol, Dave, Alice, Bob + Carol, Dave, Bob, Alice + Dave, Alice, Bob, Carol + Dave, Carol, Alice, Bob + Dave, Carol, Bob, Alice + + If *r* is given, only the *r*-length derangements are yielded. + + >>> sorted(derangements(range(3), 2)) + [(1, 0), (1, 2), (2, 0)] + >>> sorted(derangements([0, 2, 3], 2)) + [(2, 0), (2, 3), (3, 0)] + + Elements are treated as unique based on their position, not on their value. + + Consider the Secret Santa example with two *different* people who have + the *same* name. Then there are two valid gift assignments even though + it might appear that a person is assigned to themselves: + + >>> names = ['Alice', 'Bob', 'Bob'] + >>> list(derangements(names)) + [('Bob', 'Bob', 'Alice'), ('Bob', 'Alice', 'Bob')] + + To avoid confusion, make the inputs distinct: + + >>> deduped = [f'{name}{index}' for index, name in enumerate(names)] + >>> list(derangements(deduped)) + [('Bob1', 'Bob2', 'Alice0'), ('Bob2', 'Alice0', 'Bob1')] + + The number of derangements of a set of size *n* is known as the + "subfactorial of n". For n > 0, the subfactorial is: + ``round(math.factorial(n) / math.e)``. + + References: + + * Article: https://www.numberanalytics.com/blog/ultimate-guide-to-derangements-in-combinatorics + * Sizes: https://oeis.org/A000166 + """ + xs = tuple(iterable) + ys = tuple(range(len(xs))) + return compress( + permutations(xs, r=r), + map(all, map(map, repeat(is_not), repeat(ys), permutations(ys, r=r))), + ) + + +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') + + iterator = iter(seq) + + # Generate first window + window = deque(islice(iterator, 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(iterator, 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 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) + + return iter(self._cache) + + 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] + + """ + p, q = tee(iterable) + return take(n, q), p + + +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). + + """ + for xs in zip_longest(*iterables, fillvalue=_marker): + for x in xs: + if x is not _marker: + yield x + + +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 interleave_randomly(*iterables): + """Repeatedly select one of the input *iterables* at random and yield the next + item from it. + + >>> iterables = [1, 2, 3], 'abc', (True, False, None) + >>> list(interleave_randomly(*iterables)) # doctest: +SKIP + ['a', 'b', 1, 'c', True, False, None, 2, 3] + + The relative order of the items in each input iterable will preserved. Note the + sequences of items with this property are not equally likely to be generated. + + """ + iterators = [iter(e) for e in iterables] + while iterators: + idx = randrange(len(iterators)) + try: + yield next(iterators[idx]) + except StopIteration: + # equivalent to `list.pop` but slightly faster + iterators[idx] = iterators[-1] + del iterators[-1] + + +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 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, *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, *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 the *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 + :func:`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] + + """ + iterator = iter(iterable) + iterator_with_repeat = chain(iterator, repeat(fillvalue)) + + if n is None: + return iterator_with_repeat + elif n < 1: + raise ValueError('n must be at least 1') + elif next_multiple: + + def slice_generator(): + for first in iterator: + yield (first,) + yield islice(iterator_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(iterator_with_repeat, n), iterator) + + +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, strict=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 the *strict* keyword argument is ``True``, then + ``UnequalIterablesError`` will be raised if any of the iterables have + different lengths. + + """ + 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) + ) + + zipper = zip_equal if strict else zip + return list( + zipper(*sorted(zipper(*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(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)) + + # If we have an iterable like iter([(1, 2, 3), (4, 5), (6,)]), + # the second unzipped iterable fails at the third tuple since + # it tries to access (6,)[1]. + # Same with the third unzipped iterable and the second tuple. + # To support these "improperly zipped" iterables, we suppress + # the IndexError, which just stops the unzipped iterables at + # first length mismatch. + return tuple( + iter_suppress(map(itemgetter(i), it), IndexError) + 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( + f'numeric_range expected at least 1 argument, got {argc}' + ) + else: + raise TypeError( + f'numeric_range expected at most 3 arguments, got {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 ' + f'integers or slices, not {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 f"numeric_range({self._start!r}, {self._stop!r})" + return ( + f"numeric_range({self._start!r}, {self._stop!r}, {self._step!r})" + ) + + 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(f"{value} is not in numeric range") + + 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')] + + """ + seq = tuple(iterable) + if not seq: + return iter(()) + counter = count() if n is None else range(n) + return zip(repeat_each(counter, len(seq)), cycle(seq)) + + +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) + for a in it: + first = True + for b in it: + yield first, False, a + a = b + first = False + yield first, 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 among 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*. + + >>> iterator = iter('abcdefgh') + >>> list(islice_extended(iterator, -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: + + >>> iterator = map(str, count()) + >>> it = islice_extended(iterator)[10:20:2] + >>> list(it) + ['10', '12', '14', '16', '18'] + + """ + + def __init__(self, iterable, *args): + it = iter(iterable) + if args: + self._iterator = _islice_helper(it, slice(*args)) + else: + self._iterator = it + + def __iter__(self): + return self + + def __next__(self): + return next(self._iterator) + + def __getitem__(self, key): + if isinstance(key, slice): + return islice_extended(_islice_helper(self._iterator, 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 in range(n): + if index % step == 0: + # pop and yield the item. + # We don't want to use an intermediate variable + # it would extend the lifetime of the current item + yield cache.popleft()[1] + else: + # just pop and discard the item + cache.popleft() + 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): + if index % step == 0: + # pop and yield the item. + # We don't want to use an intermediate variable + # it would extend the lifetime of the current item + yield cache.popleft() + else: + # just pop and discard the item + cache.popleft() + 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=None): + """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] + + To find runs of adjacent letters, apply :func:`ord` function + to convert letters to ordinals. + + >>> iterable = 'abcdfgilmnop' + >>> ordering = ord + >>> 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]] + + """ + if ordering is None: + key = lambda x: x[0] - x[1] + else: + key = lambda x: x[0] - ordering(x[1]) + + for k, g in groupby(enumerate(iterable), key=key): + 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 f'{self.__class__.__name__}({self._target!r})' + + +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') + + You can also seek forward: + + >>> it = seekable((str(n) for n in range(20))) + >>> it.seek(10) + >>> next(it) + '10' + >>> 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) + '0' + + Call :meth:`relative_seek` to seek relative to the source iterator's + current position. + + >>> it = seekable((str(n) for n in range(20))) + >>> next(it), next(it), next(it) + ('0', '1', '2') + >>> it.relative_seek(2) + >>> next(it) + '5' + >>> it.relative_seek(-3) # Source is at '6', we move back to '3' + >>> next(it) + '3' + >>> it.relative_seek(-3) # Source is at '4', we move back to '1' + >>> next(it) + '1' + + + 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): + if self._index is None: + self._index = len(self._cache) + + self.seek(max(self._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(starmap(repeat, 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 ilen(islice(filter(predicate, iterable), n + 1)) == n + + +def circular_shifts(iterable, steps=1): + """Yield the circular shifts of *iterable*. + + >>> list(circular_shifts(range(4))) + [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)] + + Set *steps* to the number of places to rotate to the left + (or to the right if negative). Defaults to 1. + + >>> list(circular_shifts(range(4), 2)) + [(0, 1, 2, 3), (2, 3, 0, 1)] + + >>> list(circular_shifts(range(4), -1)) + [(0, 1, 2, 3), (3, 0, 1, 2), (2, 3, 0, 1), (1, 2, 3, 0)] + + """ + buffer = deque(iterable) + if steps == 0: + raise ValueError('Steps should be a non-zero integer') + + buffer.rotate(steps) + steps = -steps + n = len(buffer) + n //= math.gcd(n, steps) + + for _ in repeat(None, n): + buffer.rotate(steps) + yield tuple(buffer) + + +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. + + """ + + ret = defaultdict(list) + + if valuefunc is None: + for item in iterable: + key = keyfunc(item) + ret[key].append(item) + + else: + 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: + + >>> iterator = iter('abcb') + >>> pred = lambda x: x == 'b' + >>> list(rlocate(iterator, 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, repeat(_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, min_size=None, max_size=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'] + + if *min_size* and/or *max_size* are given, the minimum and/or maximum size + per block in partition is set. + + >>> iterable = 'abc' + >>> for part in set_partitions(iterable, min_size=2): + ... print([''.join(p) for p in part]) + ['abc'] + >>> for part in set_partitions(iterable, max_size=2): + ... print([''.join(p) for p in part]) + ['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 + + min_size = min_size if min_size is not None else 0 + max_size = max_size if max_size is not None else n + if min_size > max_size: + 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 filter( + lambda z: all(min_size <= len(bk) <= max_size for bk in z), + set_partitions_helper(L, k), + ) + else: + yield from filter( + lambda z: all(min_size <= len(bk) <= max_size for bk in z), + 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._iterator = 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._iterator) + 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. + + """ + iterator = iter(iterable) + for first in iterator: + for second in iterator: + msg = ( + f'Expected exactly one item in iterable, but got {first!r}, ' + f'{second!r}, and perhaps more.' + ) + raise too_long or ValueError(msg) + return first + return default + + +def _ichunk(iterator, n): + cache = deque() + chunk = islice(iterator, n) + + def generator(): + with suppress(StopIteration): + while True: + if cache: + yield cache.popleft() + else: + yield next(chunk) + + 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] + + """ + iterator = iter(iterable) + while True: + # Create new chunk + chunk, materialize_next = _ichunk(iterator, 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=None): + """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'] + """ + + if func_else is None: + for item in iterable: + yield func(item) if pred(item) else item + + else: + for item in iterable: + yield func(item) if pred(item) else func_else(item) + + +def _sample_unweighted(iterator, k, strict): + # Algorithm L in the 1994 paper by Kim-Hung Li: + # "Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))". + + reservoir = list(islice(iterator, k)) + if strict and len(reservoir) < k: + raise ValueError('Sample larger than population') + W = 1.0 + + with suppress(StopIteration): + while True: + W *= random() ** (1 / k) + skip = floor(log(random()) / log1p(-W)) + element = next(islice(iterator, skip, None)) + reservoir[randrange(k)] = element + + shuffle(reservoir) + return reservoir + + +def _sample_weighted(iterator, k, weights, strict): + # 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, iterator)) + if strict and len(reservoir) < k: + raise ValueError('Sample larger than population') + + 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, iterator): + 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 + + ret = [element for weight_key, element in reservoir] + shuffle(ret) + return ret + + +def _sample_counted(population, k, counts, strict): + element = None + remaining = 0 + + def feed(i): + # Advance *i* steps ahead and consume an element + nonlocal element, remaining + + while i + 1 > remaining: + i = i - remaining + element = next(population) + remaining = next(counts) + remaining -= i + 1 + return element + + with suppress(StopIteration): + reservoir = [] + for _ in range(k): + reservoir.append(feed(0)) + + if strict and len(reservoir) < k: + raise ValueError('Sample larger than population') + + with suppress(StopIteration): + W = 1.0 + while True: + W *= random() ** (1 / k) + skip = floor(log(random()) / log1p(-W)) + element = feed(skip) + reservoir[randrange(k)] = element + + shuffle(reservoir) + return reservoir + + +def sample(iterable, k, weights=None, *, counts=None, strict=False): + """Return a *k*-length list of elements chosen (without replacement) + from the *iterable*. + + Similar to :func:`random.sample`, but works on inputs that aren't + indexable (such as sets and dictionaries) and on inputs where the + size isn't known in advance (such as generators). + + >>> iterable = range(100) + >>> sample(iterable, 5) # doctest: +SKIP + [81, 60, 96, 16, 4] + + For iterables with repeated elements, you may supply *counts* to + indicate the repeats. + + >>> iterable = ['a', 'b'] + >>> counts = [3, 4] # Equivalent to 'a', 'a', 'a', 'b', 'b', 'b', 'b' + >>> sample(iterable, k=3, counts=counts) # doctest: +SKIP + ['a', 'a', 'b'] + + An iterable with *weights* may 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] + + Weighted selections are made without replacement. + After an element is selected, it is removed from the pool and the + relative weights of the other elements increase (this + does not match the behavior of :func:`random.sample`'s *counts* + parameter). Note that *weights* may not be used with *counts*. + + If the length of *iterable* is less than *k*, + ``ValueError`` is raised if *strict* is ``True`` and + all elements are returned (in shuffled order) if *strict* is ``False``. + + By default, the `Algorithm L `__ reservoir sampling + technique is used. When *weights* are provided, + `Algorithm A-ExpJ `__ is used instead. + + Notes on reproducibility: + + * The algorithms rely on inexact floating-point functions provided + by the underlying math library (e.g. ``log``, ``log1p``, and ``pow``). + Those functions can `produce slightly different results + `_ on + different builds. Accordingly, selections can vary across builds + even for the same seed. + + * The algorithms loop over the input and make selections based on + ordinal position, so selections from unordered collections (such as + sets) won't reproduce across sessions on the same platform using the + same seed. For example, this won't reproduce:: + + >> seed(8675309) + >> sample(set('abcdefghijklmnopqrstuvwxyz'), 10) + ['c', 'p', 'e', 'w', 's', 'a', 'j', 'd', 'n', 't'] + + """ + iterator = iter(iterable) + + if k < 0: + raise ValueError('k must be non-negative') + + if k == 0: + return [] + + if weights is not None and counts is not None: + raise TypeError('weights and counts are mutually exclusive') + + elif weights is not None: + weights = iter(weights) + return _sample_weighted(iterator, k, weights, strict) + + elif counts is not None: + counts = iter(counts) + return _sample_counted(iterator, k, counts, strict) + + else: + return _sample_unweighted(iterator, k, strict) + + +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, which means it may produce results that differ from the built-in + :func:`sorted` function for objects with unusual comparison dynamics + (like ``math.nan``). If there are no out-of-order items, the iterable is + exhausted. + """ + it = iterable if (key is None) else map(key, iterable) + a, b = tee(it) + next(b, None) + if reverse: + b, a = a, b + return all(map(lt, a, b)) if strict else not any(map(lt, b, a)) + + +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 # factorial(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._iterator = iter(iterable) + self.items_seen = 0 + + def __iter__(self): + return self + + def __next__(self): + item = next(self._iterator) + 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]] + + """ + iterator = 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(iterator, min_buffer)) + + # Append items until we have a completed chunk + for _ in islice(map(buffer.append, iterator), 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 from an iterable + or from 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 makes a single pass over the input elements and takes care to + minimize the number of comparisons made during processing. + + Note that unlike the builtin ``max`` function, which always returns the first + item with the maximum value, this function may return another item when there are + ties. + + This function is based on the + `recipe `__ by + Raymond Hettinger. + """ + 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'] + >>> pair_counts = Counter(zip(xs, ys)) + >>> count_rows = lambda x, y: pair_counts[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(dict.fromkeys(map(frozenset, zip(iterable)))) + return chain.from_iterable( + starmap(set().union, combinations(sets, r)) + for r in range(len(sets) + 1) + ) + + +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`. + """ + + real = attrgetter('real') + imag = attrgetter('imag') + r1 = chain(map(real, v1), map(neg, map(imag, v1))) + r2 = chain(map(real, v2), map(imag, v2)) + i1 = chain(map(real, v1), map(imag, v1)) + i2 = chain(map(imag, v2), map(real, v2)) + return complex(_fsumprod(r1, r2), _fsumprod(i1, i2)) + + +def dft(xarr): + """Discrete Fourier Transform. *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] # time domain + >>> Xarr = [2, -2-2j, -2j, 4+4j] # frequency domain + >>> magnitudes, phases = zip(*map(cmath.polar, Xarr)) + >>> all(map(cmath.isclose, dft(xarr), Xarr)) + True + + Inputs are restricted to numeric types that can add and multiply + with a complex number. This includes int, float, complex, and + Fraction, but excludes Decimal. + + 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 Transform. *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] # time domain + >>> Xarr = [2, -2-2j, -2j, 4+4j] # frequency domain + >>> all(map(cmath.isclose, idft(Xarr), xarr)) + True + + Inputs are restricted to numeric types that can add and multiply + with a complex number. This includes int, float, complex, and + Fraction, but excludes Decimal. + + 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) + + +def _nth_prime_bounds(n): + """Bounds for the nth prime (counting from 1): lb < p_n < ub.""" + # At and above 688,383, the lb/ub spread is under 0.003 * p_n. + + if n < 1: + raise ValueError + + if n < 6: + return (n, 2.25 * n) + + # https://en.wikipedia.org/wiki/Prime-counting_function#Inequalities + upper_bound = n * log(n * log(n)) + lower_bound = upper_bound - n + if n >= 688_383: + upper_bound -= n * (1.0 - (log(log(n)) - 2.0) / log(n)) + + return lower_bound, upper_bound + + +def nth_prime(n, *, approximate=False): + """Return the nth prime (counting from 0). + + >>> nth_prime(0) + 2 + >>> nth_prime(100) + 547 + + If *approximate* is set to True, will return a prime close + to the nth prime. The estimation is much faster than computing + an exact result. + + >>> nth_prime(200_000_000, approximate=True) # Exact result is 4222234763 + 4217820427 + + """ + lb, ub = _nth_prime_bounds(n + 1) + + if not approximate or n <= 1_000_000: + return nth(sieve(ceil(ub)), n) + + # Search from the midpoint and return the first odd prime + odd = floor((lb + ub) / 2) | 1 + return first_true(count(odd, step=2), pred=is_prime) + + +def argmin(iterable, *, key=None): + """ + Index of the first occurrence of a minimum value in an iterable. + + >>> argmin('efghabcdijkl') + 4 + >>> argmin([3, 2, 1, 0, 4, 2, 1, 0]) + 3 + + For example, look up a label corresponding to the position + of a value that minimizes a cost function:: + + >>> def cost(x): + ... "Days for a wound to heal given a subject's age." + ... return x**2 - 20*x + 150 + ... + >>> labels = ['homer', 'marge', 'bart', 'lisa', 'maggie'] + >>> ages = [ 35, 30, 10, 9, 1 ] + + # Fastest healing family member + >>> labels[argmin(ages, key=cost)] + 'bart' + + # Age with fastest healing + >>> min(ages, key=cost) + 10 + + """ + if key is not None: + iterable = map(key, iterable) + return min(enumerate(iterable), key=itemgetter(1))[0] + + +def argmax(iterable, *, key=None): + """ + Index of the first occurrence of a maximum value in an iterable. + + >>> argmax('abcdefghabcd') + 7 + >>> argmax([0, 1, 2, 3, 3, 2, 1, 0]) + 3 + + For example, identify the best machine learning model:: + + >>> models = ['svm', 'random forest', 'knn', 'naïve bayes'] + >>> accuracy = [ 68, 61, 84, 72 ] + + # Most accurate model + >>> models[argmax(accuracy)] + 'knn' + + # Best accuracy + >>> max(accuracy) + 84 + + """ + if key is not None: + iterable = map(key, iterable) + return max(enumerate(iterable), key=itemgetter(1))[0] + + +def extract(iterable, indices): + """Yield values at the specified indices. + + Example: + + >>> data = 'abcdefghijklmnopqrstuvwxyz' + >>> list(extract(data, [7, 4, 11, 11, 14])) + ['h', 'e', 'l', 'l', 'o'] + + The *iterable* is consumed lazily and can be infinite. + The *indices* are consumed immediately and must be finite. + + Raises ``IndexError`` if an index lies beyond the iterable. + Raises ``ValueError`` for negative indices. + """ + + iterator = iter(iterable) + index_and_position = sorted(zip(indices, count())) + + if index_and_position and index_and_position[0][0] < 0: + raise ValueError('Indices must be non-negative') + + buffer = {} + iterator_position = -1 + next_to_emit = 0 + + for index, order in index_and_position: + advance = index - iterator_position + if advance: + try: + value = next(islice(iterator, advance - 1, None)) + except StopIteration: + raise IndexError(index) + iterator_position = index + + buffer[order] = value + + while next_to_emit in buffer: + yield buffer.pop(next_to_emit) + next_to_emit += 1 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/more.pyi b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/more.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b5e33f8b747f70ae8c842c07dca5005449241a62 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/more.pyi @@ -0,0 +1,949 @@ +"""Stubs for more_itertools.more""" + +from __future__ import annotations + +import sys +import types + +from collections.abc import ( + Container, + Hashable, + Iterable, + Iterator, + Mapping, + Reversible, + Sequence, + Sized, +) +from contextlib import AbstractContextManager +from typing import ( + Any, + Callable, + Generic, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import Protocol + +__all__ = [ + 'AbortThread', + 'SequenceView', + 'UnequalIterablesError', + 'adjacent', + 'all_unique', + 'always_iterable', + 'always_reversible', + 'argmax', + 'argmin', + 'bucket', + 'callback_iter', + 'chunked', + 'chunked_even', + 'circular_shifts', + 'collapse', + 'combination_index', + 'combination_with_replacement_index', + 'consecutive_groups', + 'constrained_batches', + 'consumer', + 'count_cycle', + 'countable', + 'derangements', + 'dft', + 'difference', + 'distinct_combinations', + 'distinct_permutations', + 'distribute', + 'divide', + 'doublestarmap', + 'duplicates_everseen', + 'duplicates_justseen', + 'classify_unique', + 'exactly_n', + 'extract', + 'filter_except', + 'filter_map', + 'first', + 'gray_product', + 'groupby_transform', + 'ichunked', + 'iequals', + 'idft', + 'ilen', + 'interleave', + 'interleave_evenly', + 'interleave_longest', + 'interleave_randomly', + '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_prime', + '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', +] + +# Type and type variable definitions +_T = TypeVar('_T') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_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] + +# The type of isinstance's second argument (from typeshed builtins) +if sys.version_info >= (3, 10): + _ClassInfo = type | types.UnionType | tuple[_ClassInfo, ...] +else: + _ClassInfo = type | tuple[_ClassInfo, ...] + +@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: AbstractContextManager[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 derangements( + iterable: Iterable[_T], r: int | None = 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 interleave_randomly(*iterables: Iterable[_T]) -> Iterable[_T]: ... +def collapse( + iterable: Iterable[Any], + base_type: _ClassInfo | 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: ... + +# zip_equal +@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[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] +) -> Iterator[tuple[_T1, _T2, _T3]]: ... +@overload +def zip_equal( + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], +) -> Iterator[tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def zip_equal( + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def zip_equal( + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], +) -> Iterator[tuple[Any, ...]]: ... + +# zip_offset +@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 = ..., + strict: 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: _ClassInfo | 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, +) -> Iterator[tuple[_T, Iterator[_V]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: None, +) -> Iterator[tuple[_U, Iterator[_V]]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None, + valuefunc: None, + reducefunc: Callable[[Iterator[_T]], _W], +) -> Iterator[tuple[_T, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: None, + reducefunc: Callable[[Iterator[_T]], _W], +) -> Iterator[tuple[_U, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: None, + valuefunc: Callable[[_T], _V], + reducefunc: Callable[[Iterator[_V]], _W], +) -> Iterator[tuple[_T, _W]]: ... +@overload +def groupby_transform( + iterable: Iterable[_T], + keyfunc: Callable[[_T], _U], + valuefunc: Callable[[_T], _V], + reducefunc: Callable[[Iterator[_V]], _W], +) -> Iterator[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: None | 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], steps: int = 1 +) -> 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 = ..., + min_size: int | None = ..., + max_size: 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_unweighted( + iterator: Iterator[_T], k: int, strict: bool +) -> list[_T]: ... +def _sample_counted( + population: Iterator[_T], k: int, counts: Iterable[int], strict: bool +) -> list[_T]: ... +def _sample_weighted( + iterator: Iterator[_T], k: int, weights: Iterator[float], strict: bool +) -> list[_T]: ... +def sample( + iterable: Iterable[_T], + k: int, + weights: Iterable[float] | None = ..., + *, + counts: Iterable[int] | None = ..., + strict: bool = False, +) -> 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: types.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[tuple[_T, ...], tuple[_T, ...], 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]]: ... +@overload +def zip_broadcast( + __obj1: _T | Iterable[_T], + *, + scalar_types: _ClassInfo | None = ..., + strict: bool = ..., +) -> Iterable[tuple[_T, ...]]: ... +@overload +def zip_broadcast( + __obj1: _T | Iterable[_T], + __obj2: _T | Iterable[_T], + *, + scalar_types: _ClassInfo | None = ..., + strict: bool = ..., +) -> Iterable[tuple[_T, ...]]: ... +@overload +def zip_broadcast( + __obj1: _T | Iterable[_T], + __obj2: _T | Iterable[_T], + __obj3: _T | Iterable[_T], + *, + scalar_types: _ClassInfo | None = ..., + strict: bool = ..., +) -> Iterable[tuple[_T, ...]]: ... +@overload +def zip_broadcast( + __obj1: _T | Iterable[_T], + __obj2: _T | Iterable[_T], + __obj3: _T | Iterable[_T], + __obj4: _T | Iterable[_T], + *, + scalar_types: _ClassInfo | None = ..., + strict: bool = ..., +) -> Iterable[tuple[_T, ...]]: ... +@overload +def zip_broadcast( + __obj1: _T | Iterable[_T], + __obj2: _T | Iterable[_T], + __obj3: _T | Iterable[_T], + __obj4: _T | Iterable[_T], + __obj5: _T | Iterable[_T], + *, + scalar_types: _ClassInfo | None = ..., + strict: bool = ..., +) -> Iterable[tuple[_T, ...]]: ... +@overload +def zip_broadcast( + __obj1: _T | Iterable[_T], + __obj2: _T | Iterable[_T], + __obj3: _T | Iterable[_T], + __obj4: _T | Iterable[_T], + __obj5: _T | Iterable[_T], + __obj6: _T | Iterable[_T], + *objects: _T | Iterable[_T], + scalar_types: _ClassInfo | 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]: ... +def _nth_prime_ub(n: int) -> float: ... +def nth_prime(n: int, *, approximate: bool = ...) -> int: ... +def argmin( + iterable: Iterable[_T], *, key: Callable[[_T], _U] | None = ... +) -> int: ... +def argmax( + iterable: Iterable[_T], *, key: Callable[[_T], _U] | None = ... +) -> int: ... +def extract( + iterable: Iterable[_T], indices: Iterable[int] +) -> Iterator[_T]: ... diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/py.typed b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/recipes.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/recipes.py new file mode 100644 index 0000000000000000000000000000000000000000..dacf61407d454907d661edde2d774bee11cec92a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/recipes.py @@ -0,0 +1,1471 @@ +"""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 random + +from bisect import bisect_left, insort +from collections import deque +from contextlib import suppress +from functools import lru_cache, partial, reduce +from heapq import heappush, heappushpop +from itertools import ( + accumulate, + chain, + combinations, + compress, + count, + cycle, + groupby, + islice, + product, + repeat, + starmap, + takewhile, + tee, + zip_longest, +) +from math import prod, comb, isqrt, gcd +from operator import mul, not_, itemgetter, getitem, index +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', + 'is_prime', + 'iter_except', + 'iter_index', + 'loops', + 'matmul', + 'multinomial', + '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', + 'running_median', + '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: # pragma: no cover + _zip_strict = zip +else: # pragma: no cover + _zip_strict = partial(zip, strict=True) + + +# math.sumprod is available for Python 3.12+ +try: + from math import sumprod as _sumprod +except ImportError: # pragma: no cover + _sumprod = lambda x, y: dotproduct(x, y) + + +# heapq max-heap functions are available for Python 3.14+ +try: + from heapq import heappush_max, heappushpop_max +except ImportError: # pragma: no cover + _max_heap_available = False +else: # pragma: no cover + _max_heap_available = True + + +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'] + + """ + try: + size = len(iterable) + except TypeError: + return iter(deque(iterable, maxlen=n)) + else: + return islice(iterable, max(0, size - n), None) + + +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 + + """ + iterator = groupby(iterable, key) + for first in iterator: + for second in iterator: + return False + return True + return True + + +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, 15, 12], [0.65, 0.80, 1.25]) + 33.5 + >>> 10 * 0.65 + 15 * 0.80 + 12 * 1.25 + 33.5 + + In Python 3.12 and later, use ``math.sumprod()`` instead. + """ + return sum(map(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: # pragma: no cover + pairwise = _pairwise +else: # pragma: no cover + + 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. + + >>> iterator = grouper('ABCDEFG', 3, incomplete='strict') + >>> list(iterator) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + UnequalIterablesError + + """ + iterators = [iter(iterable)] * n + if incomplete == 'fill': + return zip_longest(*iterators, fillvalue=fillvalue) + if incomplete == 'strict': + return _zip_equal(*iterators) + if incomplete == 'ignore': + return zip(*iterators) + else: + raise ValueError('Expected fill, strict, or ignore') + + +def roundrobin(*iterables): + """Visit input iterables in a cycle until each is exhausted. + + >>> 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(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(itemgetter(0), groupby(iterable)) + + return map(next, map(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. + """ + sequenced = sorted(iterable, key=key, reverse=reverse) + return unique_justseen(sequenced, 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))) + [] + + """ + with suppress(exception): + if first is not None: + yield first() + while True: + yield func() + + +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, repeat=repeat)``. + + """ + 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): + """Discrete linear convolution of two iterables. + Equivalent to polynomial multiplication. + + For example, multiplying ``(x² -x - 20)`` by ``(x - 3)`` + gives ``(x³ -4x² -17x + 60)``. + + >>> list(convolve([1, -1, -20], [1, -3])) + [1, -4, -17, 60] + + Examples of popular kinds of kernels: + + * The kernel ``[0.25, 0.25, 0.25, 0.25]`` computes a moving average. + For image data, this blurs the image and reduces noise. + * The kernel ``[1/2, 0, -1/2]`` estimates the first derivative of + a function evaluated at evenly spaced inputs. + * The kernel ``[1, -2, 1]`` estimates the second derivative of a + function evaluated at evenly spaced inputs. + + Convolutions are mathematically commutative; however, the inputs are + evaluated differently. The signal is consumed lazily and can be + infinite. The kernel is fully consumed before the calculations begin. + + Supports all numeric types: int, float, complex, Decimal, Fraction. + + References: + + * Article: https://betterexplained.com/articles/intuitive-convolution/ + * Video by 3Blue1Brown: https://www.youtube.com/watch?v=KuXjwB4LzSA + + """ + # This implementation comes from an older version of the itertools + # documentation. While the newer implementation is a bit clearer, + # this one was kept because the inlined window logic is faster + # and it avoids an unnecessary deque-to-tuple conversion. + 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. + """ + trues, after = tee(it) + trues = compress(takewhile(predicate, trues), zip(after)) + return trues, after + + +def triplewise(iterable): + """Return overlapping triplets from *iterable*. + + >>> list(triplewise('ABCDE')) + [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E')] + + """ + # This deviates from the itertools documentation recipe - see + # https://github.com/more-itertools/more-itertools/issues/889 + t1, t2, t3 = tee(iterable, 3) + next(t3, None) + next(t3, None) + next(t2, None) + return zip(t1, t2, t3) + + +def _sliding_window_islice(iterable, n): + # Fast path for small, non-zero values of n. + iterators = tee(iterable, n) + for i, iterator in enumerate(iterators): + next(islice(iterator, i, i), None) + return zip(*iterators) + + +def _sliding_window_deque(iterable, n): + # Normal path for other values of n. + iterator = iter(iterable) + window = deque(islice(iterator, n - 1), maxlen=n) + for x in iterator: + window.append(x) + yield tuple(window) + + +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`. + """ + if n > 20: + return _sliding_window_deque(iterable, n) + elif n > 2: + return _sliding_window_islice(iterable, n) + elif n == 2: + return pairwise(iterable) + elif n == 1: + return zip(iterable) + else: + raise ValueError(f'n should be at least one, not {n}') + + +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(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³ - 4 x² - 17 x + 60 + [1, -4, -17, 60] + + Note that polynomial coefficients are specified in descending power order. + + Supports all numeric types: int, float, complex, Decimal, Fraction. + """ + + # This recipe differs from the one in itertools docs in that it + # applies list() after each call to convolve(). This avoids + # hitting stack limits with nested generators. + + poly = [1] + for root in roots: + poly = list(convolve(poly, (1, -root))) + return poly + + +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 + iterator = islice(iterable, start, stop) + for i, element in enumerate(iterator, 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 + with suppress(ValueError): + while True: + yield (i := seq_index(value, i + 1, stop)) + + +def sieve(n): + """Yield the primes less than n. + + >>> list(sieve(30)) + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + + """ + # This implementation comes from an older version of the itertools + # documentation. The newer implementation is easier to read but is + # less lazy. + if n > 2: + yield 2 + start = 3 + data = bytearray((0, 1)) * (n // 2) + for p in iter_index(data, 1, start, stop=isqrt(n) + 1): + 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): # pragma: no cover + """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') + iterator = iter(iterable) + while batch := tuple(islice(iterator, n)): + if strict and len(batch) != n: + raise ValueError('batched(): incomplete batch') + yield batch + + +if hexversion >= 0x30D00A2: # pragma: no cover + from itertools import batched as itertools_batched + + def batched(iterable, n, *, strict=False): + return itertools_batched(iterable, n, strict=strict) + + batched.__doc__ = _batched.__doc__ +else: # pragma: no cover + batched = _batched + + +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 _is_scalar(value, stringlike=(str, bytes)): + "Scalars are bytes, strings, and non-iterables." + try: + iter(value) + except TypeError: + return True + return isinstance(value, stringlike) + + +def _flatten_tensor(tensor): + "Depth-first iterator over scalars in a tensor." + iterator = iter(tensor) + while True: + try: + value = next(iterator) + except StopIteration: + return iterator + iterator = chain((value,), iterator) + if _is_scalar(value): + return iterator + iterator = chain.from_iterable(iterator) + + +def reshape(matrix, shape): + """Change the shape of a *matrix*. + + If *shape* is an integer, the matrix must be two dimensional + and the shape is interpreted as the desired number of columns: + + >>> matrix = [(0, 1), (2, 3), (4, 5)] + >>> cols = 3 + >>> list(reshape(matrix, cols)) + [(0, 1, 2), (3, 4, 5)] + + If *shape* is a tuple (or other iterable), the input matrix can have + any number of dimensions. It will first be flattened and then rebuilt + to the desired shape which can also be multidimensional: + + >>> matrix = [(0, 1), (2, 3), (4, 5)] # Start with a 3 x 2 matrix + + >>> list(reshape(matrix, (2, 3))) # Make a 2 x 3 matrix + [(0, 1, 2), (3, 4, 5)] + + >>> list(reshape(matrix, (6,))) # Make a vector of length six + [0, 1, 2, 3, 4, 5] + + >>> list(reshape(matrix, (2, 1, 3, 1))) # Make 2 x 1 x 3 x 1 tensor + [(((0,), (1,), (2,)),), (((3,), (4,), (5,)),)] + + Each dimension is assumed to be uniform, either all arrays or all scalars. + Flattening stops when the first value in a dimension is a scalar. + Scalars are bytes, strings, and non-iterables. + The reshape iterator stops when the requested shape is complete + or when the input is exhausted, whichever comes first. + + """ + if isinstance(shape, int): + return batched(chain.from_iterable(matrix), shape) + first_dim, *dims = shape + scalar_stream = _flatten_tensor(matrix) + reshaped = reduce(batched, reversed(dims), scalar_stream) + return islice(reshaped, first_dim) + + +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. + + Supports all numeric types: int, float, complex, Decimal, Fraction. + """ + n = len(m2[0]) + return batched(starmap(_sumprod, product(m1, transpose(m2))), n) + + +def _factor_pollard(n): + # Return a factor of n using Pollard's rho algorithm. + # Efficient when n is odd and composite. + for b in range(1, n): + x = y = 2 + d = 1 + while d == 1: + x = (x * x + b) % n + y = (y * y + b) % n + y = (y * y + b) % n + d = gcd(x - y, n) + if d != n: + return d + raise ValueError('prime or under 5') # pragma: no cover + + +_primes_below_211 = tuple(sieve(211)) + + +def factor(n): + """Yield the prime factors of n. + + >>> list(factor(360)) + [2, 2, 2, 3, 3, 5] + + Finds small factors with trial division. Larger factors are + either verified as prime with ``is_prime`` or split into + smaller factors with Pollard's rho algorithm. + """ + + # Corner case reduction + if n < 2: + return + + # Trial division reduction + for prime in _primes_below_211: + while not n % prime: + yield prime + n //= prime + + # Pollard's rho reduction + primes = [] + todo = [n] if n > 1 else [] + for n in todo: + if n < 211**2 or is_prime(n): + primes.append(n) + else: + fact = _factor_pollard(n) + todo += (fact, n // fact) + yield from sorted(primes) + + +def polynomial_eval(coefficients, x): + """Evaluate a polynomial at a specific value. + + Computes with better numeric stability than Horner's method. + + Evaluate ``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 + + Note that polynomial coefficients are specified in descending power order. + + Supports all numeric types: int, float, complex, Decimal, Fraction. + """ + n = len(coefficients) + if n == 0: + return type(x)(0) + 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 + + Supports all numeric types: int, float, complex, Decimal, Fraction. + """ + return _sumprod(*tee(it)) + + +def polynomial_derivative(coefficients): + """Compute the first derivative of a polynomial. + + Evaluate the derivative of ``x³ - 4 x² - 17 x + 60``: + + >>> coefficients = [1, -4, -17, 60] + >>> derivative_coefficients = polynomial_derivative(coefficients) + >>> derivative_coefficients + [3, -8, -17] + + Note that polynomial coefficients are specified in descending power order. + + Supports all numeric types: int, float, complex, Decimal, Fraction. + """ + n = len(coefficients) + powers = reversed(range(1, n)) + return list(map(mul, coefficients, powers)) + + +def totient(n): + """Return the count of natural numbers up to *n* that are coprime with *n*. + + Euler's totient function φ(n) gives the number of totatives. + Totative are integers k in the range 1 ≤ k ≤ n such that gcd(n, k) = 1. + + >>> n = 9 + >>> totient(n) + 6 + + >>> totatives = [x for x in range(1, n) if gcd(n, x) == 1] + >>> totatives + [1, 2, 4, 5, 7, 8] + >>> len(totatives) + 6 + + Reference: https://en.wikipedia.org/wiki/Euler%27s_totient_function + + """ + for prime in set(factor(n)): + n -= n // prime + return n + + +# Miller–Rabin primality test: https://oeis.org/A014233 +_perfect_tests = [ + (2047, (2,)), + (9080191, (31, 73)), + (4759123141, (2, 7, 61)), + (1122004669633, (2, 13, 23, 1662803)), + (2152302898747, (2, 3, 5, 7, 11)), + (3474749660383, (2, 3, 5, 7, 11, 13)), + (18446744073709551616, (2, 325, 9375, 28178, 450775, 9780504, 1795265022)), + ( + 3317044064679887385961981, + (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41), + ), +] + + +@lru_cache +def _shift_to_odd(n): + 'Return s, d such that 2**s * d == n' + s = ((n - 1) ^ n).bit_length() - 1 + d = n >> s + assert (1 << s) * d == n and d & 1 and s >= 0 + return s, d + + +def _strong_probable_prime(n, base): + assert (n > 2) and (n & 1) and (2 <= base < n) + + s, d = _shift_to_odd(n - 1) + + x = pow(base, d, n) + if x == 1 or x == n - 1: + return True + + for _ in range(s - 1): + x = x * x % n + if x == n - 1: + return True + + return False + + +# Separate instance of Random() that doesn't share state +# with the default user instance of Random(). +_private_randrange = random.Random().randrange + + +def is_prime(n): + """Return ``True`` if *n* is prime and ``False`` otherwise. + + Basic examples: + + >>> is_prime(37) + True + >>> is_prime(3 * 13) + False + >>> is_prime(18_446_744_073_709_551_557) + True + + Find the next prime over one billion: + + >>> next(filter(is_prime, count(10**9))) + 1000000007 + + Generate random primes up to 200 bits and up to 60 decimal digits: + + >>> from random import seed, randrange, getrandbits + >>> seed(18675309) + + >>> next(filter(is_prime, map(getrandbits, repeat(200)))) + 893303929355758292373272075469392561129886005037663238028407 + + >>> next(filter(is_prime, map(randrange, repeat(10**60)))) + 269638077304026462407872868003560484232362454342414618963649 + + This function is exact for values of *n* below 10**24. For larger inputs, + the probabilistic Miller-Rabin primality test has a less than 1 in 2**128 + chance of a false positive. + """ + + if n < 17: + return n in {2, 3, 5, 7, 11, 13} + + if not (n & 1 and n % 3 and n % 5 and n % 7 and n % 11 and n % 13): + return False + + for limit, bases in _perfect_tests: + if n < limit: + break + else: + bases = (_private_randrange(2, n - 1) for i in range(64)) + + return all(_strong_probable_prime(n, base) for base in bases) + + +def loops(n): + """Returns an iterable with *n* elements for efficient looping. + Like ``range(n)`` but doesn't create integers. + + >>> i = 0 + >>> for _ in loops(5): + ... i += 1 + >>> i + 5 + + """ + return repeat(None, n) + + +def multinomial(*counts): + """Number of distinct arrangements of a multiset. + + The expression ``multinomial(3, 4, 2)`` has several equivalent + interpretations: + + * In the expansion of ``(a + b + c)⁹``, the coefficient of the + ``a³b⁴c²`` term is 1260. + + * There are 1260 distinct ways to arrange 9 balls consisting of 3 reds, 4 + greens, and 2 blues. + + * There are 1260 unique ways to place 9 distinct objects into three bins + with sizes 3, 4, and 2. + + The :func:`multinomial` function computes the length of + :func:`distinct_permutations`. For example, there are 83,160 distinct + anagrams of the word "abracadabra": + + >>> from more_itertools import distinct_permutations, ilen + >>> ilen(distinct_permutations('abracadabra')) + 83160 + + This can be computed directly from the letter counts, 5a 2b 2r 1c 1d: + + >>> from collections import Counter + >>> list(Counter('abracadabra').values()) + [5, 2, 2, 1, 1] + >>> multinomial(5, 2, 2, 1, 1) + 83160 + + A binomial coefficient is a special case of multinomial where there are + only two categories. For example, the number of ways to arrange 12 balls + with 5 reds and 7 blues is ``multinomial(5, 7)`` or ``math.comb(12, 5)``. + + Likewise, factorial is a special case of multinomial where + the multiplicities are all just 1 so that + ``multinomial(1, 1, 1, 1, 1, 1, 1) == math.factorial(7)``. + + Reference: https://en.wikipedia.org/wiki/Multinomial_theorem + + """ + return prod(map(comb, accumulate(counts), counts)) + + +def _running_median_minheap_and_maxheap(iterator): # pragma: no cover + "Non-windowed running_median() for Python 3.14+" + + read = iterator.__next__ + lo = [] # max-heap + hi = [] # min-heap (same size as or one smaller than lo) + + with suppress(StopIteration): + while True: + heappush_max(lo, heappushpop(hi, read())) + yield lo[0] + + heappush(hi, heappushpop_max(lo, read())) + yield (lo[0] + hi[0]) / 2 + + +def _running_median_minheap_only(iterator): # pragma: no cover + "Backport of non-windowed running_median() for Python 3.13 and prior." + + read = iterator.__next__ + lo = [] # max-heap (actually a minheap with negated values) + hi = [] # min-heap (same size as or one smaller than lo) + + with suppress(StopIteration): + while True: + heappush(lo, -heappushpop(hi, read())) + yield -lo[0] + + heappush(hi, -heappushpop(lo, -read())) + yield (hi[0] - lo[0]) / 2 + + +def _running_median_windowed(iterator, maxlen): + "Yield median of values in a sliding window." + + window = deque() + ordered = [] + + for x in iterator: + window.append(x) + insort(ordered, x) + + if len(ordered) > maxlen: + i = bisect_left(ordered, window.popleft()) + del ordered[i] + + n = len(ordered) + m = n // 2 + yield ordered[m] if n & 1 else (ordered[m - 1] + ordered[m]) / 2 + + +def running_median(iterable, *, maxlen=None): + """Cumulative median of values seen so far or values in a sliding window. + + Set *maxlen* to a positive integer to specify the maximum size + of the sliding window. The default of *None* is equivalent to + an unbounded window. + + For example: + + >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0])) + [5.0, 7.0, 5.0, 7.0, 8.0, 8.5] + >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0], maxlen=3)) + [5.0, 7.0, 5.0, 9.0, 8.0, 9.0] + + Supports numeric types such as int, float, Decimal, and Fraction, + but not complex numbers which are unorderable. + + On version Python 3.13 and prior, max-heaps are simulated with + negative values. The negation causes Decimal inputs to apply context + rounding, making the results slightly different than that obtained + by statistics.median(). + """ + + iterator = iter(iterable) + + if maxlen is not None: + maxlen = index(maxlen) + if maxlen <= 0: + raise ValueError('Window size should be positive') + return _running_median_windowed(iterator, maxlen) + + if not _max_heap_available: + return _running_median_minheap_only(iterator) # pragma: no cover + + return _running_median_minheap_and_maxheap(iterator) # pragma: no cover diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/recipes.pyi b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/recipes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..de3d0a1777a547e986cba595de72f92b8e3cedbd --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/more_itertools/recipes.pyi @@ -0,0 +1,205 @@ +"""Stubs for more_itertools.recipes""" + +from __future__ import annotations + +from collections.abc import Iterable, Iterator, Sequence +from decimal import Decimal +from fractions import Fraction +from typing import ( + Any, + Callable, + TypeVar, + overload, +) + +__all__ = [ + 'all_equal', + 'batched', + 'before_and_after', + 'consume', + 'convolve', + 'dotproduct', + 'first_true', + 'factor', + 'flatten', + 'grouper', + 'is_prime', + 'iter_except', + 'iter_index', + 'loops', + 'matmul', + 'multinomial', + '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', + 'running_median', + 'sieve', + 'sliding_window', + 'subslices', + 'sum_of_squares', + 'tabulate', + 'tail', + 'take', + 'totient', + 'transpose', + 'triplewise', + 'unique', + 'unique_everseen', + 'unique_justseen', +] + +# Type and type variable definitions +_T = TypeVar('_T') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_U = TypeVar('_U') +_NumberT = TypeVar("_NumberT", float, Decimal, Fraction) + +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, ...]]: ... + +batched = _batched + +def transpose( + it: Iterable[Iterable[_T]], +) -> Iterator[tuple[_T, ...]]: ... +@overload +def reshape( + matrix: Iterable[Iterable[_T]], shape: int +) -> Iterator[tuple[_T, ...]]: ... +@overload +def reshape(matrix: Iterable[Any], shape: Iterable[int]) -> Iterator[Any]: ... +def matmul(m1: Sequence[_T], m2: Sequence[_T]) -> Iterator[tuple[_T]]: ... +def _factor_trial(n: int) -> Iterator[int]: ... +def _factor_pollard(n: int) -> int: ... +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: ... +def _shift_to_odd(n: int) -> tuple[int, int]: ... +def _strong_probable_prime(n: int, base: int) -> bool: ... +def is_prime(n: int) -> bool: ... +def loops(n: int) -> Iterator[None]: ... +def multinomial(*counts: int) -> int: ... +def running_median( + iterable: Iterable[_NumberT], *, maxlen: int | None = ... +) -> Iterator[_NumberT]: ... diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3200e601f970271fdde3fcc74f9af4423655a79d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/METADATA @@ -0,0 +1,107 @@ +Metadata-Version: 2.4 +Name: packaging +Version: 26.0 +Summary: Core utilities for Python packages +Author-email: Donald Stufft +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-Expression: Apache-2.0 OR BSD-2-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +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 :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Typing :: Typed +License-File: LICENSE +License-File: LICENSE.APACHE +License-File: LICENSE.BSD +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, metadata, lockfiles, utilities. + +Documentation +------------- + +The `documentation`_ provides information and the API for the following: + +- Version Handling +- Specifiers +- Markers +- Requirements +- Tags +- Metadata +- Lockfiles +- 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..38cdeafd21f1eab74d3f49f069bac093d7694f84 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/RECORD @@ -0,0 +1,26 @@ +packaging-26.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +packaging-26.0.dist-info/METADATA,sha256=M2K7fWom2iliuo2qpHhc0LrKwhq6kIoRlcyPWVgKJlo,3309 +packaging-26.0.dist-info/RECORD,, +packaging-26.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging-26.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +packaging-26.0.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +packaging-26.0.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +packaging-26.0.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494 +packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211 +packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559 +packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707 +packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518 +packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514 +packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421 +packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819 +packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122 +packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771 +packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360 +packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537 +packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870 +packaging/specifiers.py,sha256=EPNPimY_zFivthv1vdjZYz5IqkKGsnKR2yKh-EVyvZw,40797 +packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856 +packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040 +packaging/version.py,sha256=7XWlL2IDYLwDYC0ht6cFEhapLwLWbmyo4rb7sEFj0x8,23272 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6f62d44e4ef733c0e713afcd2371fed7f2b3de67 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.APACHE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.APACHE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.BSD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..42ce7b75c92fb01a3f6ed17eea363f756b7da582 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging-26.0.dist-info/licenses/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21695a74b5107c96ba4bb2cbca6b7f259dacd330 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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__ = "26.0" + +__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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e78b8d99d9bbcd5cd051de8ab55fa35ada5c28c9 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_elffile.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_elffile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4d204c62f2f2eee2af3aee0de18f9bb0bf248e1 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_elffile.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..777b8c17bbca5f7bb1550e9deedb029e49aab493 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_manylinux.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6803b5046cc1e25b7a1f381004f9be71faa99d9f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_musllinux.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_parser.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dbfc64902fd293d2364747d14a7e7e608eb4442 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_parser.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_structures.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_structures.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5198a31f7dbda046e58d54a115a42b43bcfb7022 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_structures.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a66748fbefda4a9b99d6df1a40733d5ac61757c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/_tokenizer.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/markers.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/markers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adfc36d1619fb7276881112fa0e5769d6e3583a5 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/markers.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/metadata.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/metadata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e3d74e20fe1d63c0692848288b369304611a47c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/metadata.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/pylock.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/pylock.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e58699c17eaea6380dd7ec7e96af66e0eb0beea2 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/pylock.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/requirements.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/requirements.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3fc6770a9263674dd937ec6c119dafead67a15d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/requirements.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/specifiers.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/specifiers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a7e61b95b3b8355f3aedd9e5c49ca35c30becb7 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/specifiers.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/tags.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/tags.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7392c5ee0f182e357d5045bd19667fccee80a5c4 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/tags.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/utils.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8fc95a6200511d2ae68b2e04a62ebd2bfdc0ec8 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/utils.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/version.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2065124df55f43d7aaca95f5db9fdfb09e3c705 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/__pycache__/version.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_elffile.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_elffile.py new file mode 100644 index 0000000000000000000000000000000000000000..497b0645217512ae2ba8ff61341fd2bbfa3648cd --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/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. + +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 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_manylinux.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_manylinux.py new file mode 100644 index 0000000000000000000000000000000000000000..0e79e8a882be74fe76c80ccf49a9cd68fb636fd4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_manylinux.py @@ -0,0 +1,262 @@ +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 + +_ALLOWED_ARCHS = { + "x86_64", + "aarch64", + "ppc64", + "ppc64le", + "s390x", + "loongarch64", + "riscv64", +} + + +# `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) + 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 # noqa: PLC0415 + 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) -> _GLibCVersion: + """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, got: {version_str}", + RuntimeWarning, + stacklevel=2, + ) + return _GLibCVersion(-1, -1) + return _GLibCVersion(int(m.group("major")), int(m.group("minor"))) + + +@functools.lru_cache +def _get_glibc_version() -> _GLibCVersion: + version_str = _glibc_version_string() + if version_str is None: + return _GLibCVersion(-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 # noqa: PLC0415 + 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) and hasattr(_manylinux, "manylinux1_compatible"): + return bool(_manylinux.manylinux1_compatible) + if version == _GLibCVersion(2, 12) and hasattr( + _manylinux, "manylinux2010_compatible" + ): + return bool(_manylinux.manylinux2010_compatible) + if version == _GLibCVersion(2, 17) and hasattr( + _manylinux, "manylinux2014_compatible" + ): + return bool(_manylinux.manylinux2014_compatible) + return True + + +_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = { + # CentOS 7 w/ glibc 2.17 (PEP 599) + _GLibCVersion(2, 17): "manylinux2014", + # CentOS 6 w/ glibc 2.12 (PEP 571) + _GLibCVersion(2, 12): "manylinux2010", + # CentOS 5 w/ glibc 2.5 (PEP 513) + _GLibCVersion(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) + if _is_compatible(arch, glibc_version): + yield "manylinux_{}_{}_{}".format(*glibc_version, arch) + + # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. + if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version): + yield f"{legacy_tag}_{arch}" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_musllinux.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_musllinux.py new file mode 100644 index 0000000000000000000000000000000000000000..4e8116a79ca80d60657542a23b4bbcbc3c518eaf --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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], check=False, 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_parser.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c1f5cd226b926f96a3bb1e9fb0f18d1bd021c9 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_parser.py @@ -0,0 +1,365 @@ +"""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 List, Literal, NamedTuple, Sequence, Tuple, Union + +from ._tokenizer import DEFAULT_RULES, Tokenizer + + +class Node: + __slots__ = ("value",) + + 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.value!r})>" + + def serialize(self) -> str: + raise NotImplementedError + + +class Variable(Node): + __slots__ = () + + def serialize(self) -> str: + return str(self) + + +class Value(Node): + __slots__ = () + + def serialize(self) -> str: + return f'"{self}"' + + +class Op(Node): + __slots__ = () + + def serialize(self) -> str: + return str(self) + + +MarkerLogical = Literal["and", "or"] +MarkerVar = Union[Variable, Value] +MarkerItem = Tuple[MarkerVar, Op, MarkerVar] +MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]] +MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]] + + +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, + expected="semicolon (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, + expected=( + "comma (within version specifier), semicolon (after version specifier)" + if specifier + else "semicolon (after name with no version specifier)" + ), + ) + + return (url, specifier, marker) + + +def _parse_requirement_marker( + tokenizer: Tokenizer, *, span_start: int, expected: str +) -> MarkerList: + """ + requirement_marker = SEMICOLON marker WS? + """ + + if not tokenizer.check("SEMICOLON"): + tokenizer.raise_syntax_error( + f"Expected {expected} or end", + span_start=span_start, + span_end=None, + ) + 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: # noqa: RET503 + """ + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_structures.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..225e2eee01238571c50595eb104e0b70d5f503c4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_structures.py @@ -0,0 +1,69 @@ +# 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 typing + + +@typing.final +class InfinityType: + __slots__ = () + + 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() + + +@typing.final +class NegativeInfinityType: + __slots__ = () + + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_tokenizer.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e6d20dd3f56f880a92db7409a3e1335cb282a8f2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/_tokenizer.py @@ -0,0 +1,193 @@ +from __future__ import annotations + +import contextlib +import re +from dataclasses import dataclass +from typing import Generator, Mapping, 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 f"{self.message}\n {self.source}\n {marker}" + + +DEFAULT_RULES: dict[str, re.Pattern[str]] = { + "LEFT_PARENTHESIS": re.compile(r"\("), + "RIGHT_PARENTHESIS": re.compile(r"\)"), + "LEFT_BRACKET": re.compile(r"\["), + "RIGHT_BRACKET": re.compile(r"\]"), + "SEMICOLON": re.compile(r";"), + "COMMA": re.compile(r","), + "QUOTED_STRING": re.compile( + r""" + ( + ('[^']*') + | + ("[^"]*") + ) + """, + re.VERBOSE, + ), + "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"), + "BOOLOP": re.compile(r"\b(or|and)\b"), + "IN": re.compile(r"\bin\b"), + "NOT": re.compile(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) + |extras? + |dependency_groups + )\b + """, + re.VERBOSE, + ), + "SPECIFIER": re.compile( + Specifier._operator_regex_str + Specifier._version_regex_str, + re.VERBOSE | re.IGNORECASE, + ), + "AT": re.compile(r"\@"), + "URL": re.compile(r"[^ \t]+"), + "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"), + "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"), + "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"), + "WS": re.compile(r"[ \t]+"), + "END": re.compile(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: Mapping[str, re.Pattern[str]], + ) -> None: + self.source = source + self.rules = rules + 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 + ) -> Generator[None, None, 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..335b275fa7575b0a7c525a713fbe0252ad2d956f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__init__.py @@ -0,0 +1,147 @@ +####################################################################################### +# +# 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 ._spdx import EXCEPTIONS, LICENSES + +__all__ = [ + "InvalidLicenseExpression", + "NormalizedLicenseExpression", + "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 a parenthesis/boolean logic parser, create an + # expression that Python can parse. Everything that is not involved with the + # grammar itself is replaced with the placeholder `False` and the resultant + # expression should become a valid Python expression. + 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", "("} + ) or (token == ")" and python_tokens and python_tokens[-1] == "("): + message = f"Invalid license expression: {raw_license_expression!r}" + raise InvalidLicenseExpression(message) + else: + python_tokens.append(token) + + python_expression = " ".join(python_tokens) + try: + compile(python_expression, "", "eval") + except SyntaxError: + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..432727bbbc35924d13994ba71d12fa5753e4e0c8 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44fb021a20949d87a254c2104ed679b7566df367 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/__pycache__/_spdx.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py new file mode 100644 index 0000000000000000000000000000000000000000..a277af28220b6dbe4599471104d1c7a2bd1e1288 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/licenses/_spdx.py @@ -0,0 +1,799 @@ + +from __future__ import annotations + +from typing import TypedDict + +class SPDXLicense(TypedDict): + id: str + deprecated: bool + +class SPDXException(TypedDict): + id: str + deprecated: bool + + +VERSION = '3.27.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}, + 'any-osi-perl-modules': {'id': 'any-OSI-perl-modules', '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}, + 'artistic-dist': {'id': 'Artistic-dist', 'deprecated': False}, + 'aspell-ru': {'id': 'Aspell-RU', '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}, + 'boehm-gc-without-fee': {'id': 'Boehm-GC-without-fee', '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-pkgconf-disclaimer': {'id': 'BSD-2-Clause-pkgconf-disclaimer', '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}, + 'cc-pdm-1.0': {'id': 'CC-PDM-1.0', 'deprecated': False}, + 'cc-sa-1.0': {'id': 'CC-SA-1.0', '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}, + 'cryptoswift': {'id': 'CryptoSwift', '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-dtd': {'id': 'DocBook-DTD', 'deprecated': False}, + 'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False}, + 'docbook-stylesheet': {'id': 'DocBook-Stylesheet', '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}, + 'fsfullrsd': {'id': 'FSFULLRSD', 'deprecated': False}, + 'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False}, + 'fsl-1.1-alv2': {'id': 'FSL-1.1-ALv2', 'deprecated': False}, + 'fsl-1.1-mit': {'id': 'FSL-1.1-MIT', 'deprecated': False}, + 'ftl': {'id': 'FTL', 'deprecated': False}, + 'furuseth': {'id': 'Furuseth', 'deprecated': False}, + 'fwlw': {'id': 'fwlw', 'deprecated': False}, + 'game-programming-gems': {'id': 'Game-Programming-Gems', 'deprecated': False}, + 'gcr-docs': {'id': 'GCR-docs', 'deprecated': False}, + 'gd': {'id': 'GD', 'deprecated': False}, + 'generic-xts': {'id': 'generic-xts', '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}, + 'hdf5': {'id': 'HDF5', '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}, + 'innosetup': {'id': 'InnoSetup', '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}, + 'jove': {'id': 'jove', '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-1.6.35': {'id': 'libpng-1.6.35', '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}, + 'man2html': {'id': 'man2html', '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}, + 'mips': {'id': 'MIPS', '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-click': {'id': 'MIT-Click', '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}, + 'ngrep': {'id': 'ngrep', '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}, + 'ntia-pd': {'id': 'NTIA-PD', '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}, + 'sendmail-open-source-1.1': {'id': 'Sendmail-Open-Source-1.1', '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}, + 'smail-gpl': {'id': 'SMAIL-GPL', 'deprecated': False}, + 'smlnj': {'id': 'SMLNJ', 'deprecated': False}, + 'smppl': {'id': 'SMPPL', 'deprecated': False}, + 'snia': {'id': 'SNIA', 'deprecated': False}, + 'snprintf': {'id': 'snprintf', 'deprecated': False}, + 'sofa': {'id': 'SOFA', '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}, + 'sul-1.0': {'id': 'SUL-1.0', '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}, + 'thirdeye': {'id': 'ThirdEye', '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}, + 'trustedqsl': {'id': 'TrustedQSL', '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}, + 'unlicense-libtelnet': {'id': 'Unlicense-libtelnet', 'deprecated': False}, + 'unlicense-libwhirlpool': {'id': 'Unlicense-libwhirlpool', '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}, + 'wwl': {'id': 'wwl', '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}, + 'cgal-linking-exception': {'id': 'CGAL-linking-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}, + 'digia-qt-lgpl-exception-1.1': {'id': 'Digia-Qt-LGPL-exception-1.1', '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-389-ds-base-exception': {'id': 'GPL-3.0-389-ds-base-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}, + 'harbour-exception': {'id': 'harbour-exception', 'deprecated': False}, + 'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False}, + 'independent-modules-exception': {'id': 'Independent-modules-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}, + 'mxml-exception': {'id': 'mxml-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}, + 'polyparse-exception': {'id': 'polyparse-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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/markers.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3706fe492f4cf0762f7734d84c2d269f88bbc5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/markers.py @@ -0,0 +1,388 @@ +# 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 AbstractSet, Callable, Literal, Mapping, TypedDict, Union, 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__ = [ + "Environment", + "EvaluateContext", + "InvalidMarker", + "Marker", + "UndefinedComparison", + "UndefinedEnvironmentName", + "default_environment", +] + +Operator = Callable[[str, Union[str, AbstractSet[str]]], bool] +EvaluateContext = Literal["metadata", "lock_file", "requirement"] +MARKERS_ALLOWING_SET = {"extras", "dependency_groups"} +MARKERS_REQUIRING_VERSION = { + "implementation_version", + "platform_release", + "python_full_version", + "python_version", +} + + +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_extras( + result: MarkerList | MarkerAtom | str, +) -> MarkerList | MarkerAtom | str: + if not isinstance(result, tuple): + return result + + lhs, op, rhs = result + 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) + return lhs, op, rhs + + +def _normalize_extra_values(results: MarkerList) -> MarkerList: + """ + Normalize extra values. + """ + + return [_normalize_extras(r) for r in 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, + "<": lambda _lhs, _rhs: False, + "<=": operator.eq, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.eq, + ">": lambda _lhs, _rhs: False, +} + + +def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool: + op_str = op.serialize() + if key in MARKERS_REQUIRING_VERSION: + try: + spec = Specifier(f"{op_str}{rhs}") + except InvalidSpecifier: + pass + else: + return spec.contains(lhs, prereleases=True) + + oper: Operator | None = _operators.get(op_str) + if oper is None: + raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") + + return oper(lhs, rhs) + + +def _normalize( + lhs: str, rhs: str | AbstractSet[str], key: str +) -> tuple[str, str | AbstractSet[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": + assert isinstance(rhs, str), "extra value must be a string" + # Both sides are normalized at this point already + return (lhs, rhs) + if key in MARKERS_ALLOWING_SET: + if isinstance(rhs, str): # pragma: no cover + return (canonicalize_name(lhs), canonicalize_name(rhs)) + else: + return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs}) + + # other environment markers don't have such standards + return lhs, rhs + + +def _evaluate_markers( + markers: MarkerList, environment: dict[str, str | AbstractSet[str]] +) -> bool: + groups: list[list[bool]] = [[]] + + for marker in markers: + 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] + + assert isinstance(lhs_value, str), "lhs must be a string" + lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) + groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key)) + elif marker == "or": + groups.append([]) + elif marker == "and": + pass + else: # pragma: nocover + raise TypeError(f"Unexpected marker {marker!r}") + + 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. + + # If this fails and throws an error, the repr still expects _markers to + # be defined. + self._markers: MarkerList = [] + + 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"<{self.__class__.__name__}('{self}')>" + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Marker): + return NotImplemented + + return str(self) == str(other) + + def evaluate( + self, + environment: Mapping[str, str | AbstractSet[str]] | None = None, + context: EvaluateContext = "metadata", + ) -> 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 *context* parameter specifies what + context the markers are being evaluated for, which influences what markers + are considered valid. Acceptable values are "metadata" (for core metadata; + default), "lock_file", and "requirement" (i.e. all other situations). + + The environment is determined from the current Python process. + """ + current_environment = cast( + "dict[str, str | AbstractSet[str]]", default_environment() + ) + if context == "lock_file": + current_environment.update( + extras=frozenset(), dependency_groups=frozenset() + ) + elif context == "metadata": + current_environment["extra"] = "" + + if environment is not None: + current_environment.update(environment) + if "extra" in current_environment: + # The API used to allow setting extra to None. We need to handle + # this case for backwards compatibility. Also skip running + # normalize name if extra is empty. + extra = cast("str | None", current_environment["extra"]) + current_environment["extra"] = canonicalize_name(extra) if extra else "" + + return _evaluate_markers( + self._markers, _repair_python_full_version(current_environment) + ) + + +def _repair_python_full_version( + env: dict[str, str | AbstractSet[str]], +) -> dict[str, str | AbstractSet[str]]: + """ + Work around platform.python_version() returning something that is not PEP 440 + compliant for non-tagged Python builds. + """ + python_full_version = cast("str", env["python_full_version"]) + if python_full_version.endswith("+"): + env["python_full_version"] = f"{python_full_version}local" + return env diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/metadata.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..253f6b1b7ebd711fdc6bbbab3b56897061bab515 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/metadata.py @@ -0,0 +1,978 @@ +from __future__ import annotations + +import email.feedparser +import email.header +import email.message +import email.parser +import email.policy +import keyword +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 + +if typing.TYPE_CHECKING: + from .licenses import NormalizedLicenseExpression + +T = typing.TypeVar("T") + + +if sys.version_info >= (3, 11): # pragma: no cover + ExceptionGroup = ExceptionGroup # noqa: F821 +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 interoperability. + + # Metadata 2.4 - PEP 639 + license_expression: str + license_files: list[str] + + # Metadata 2.5 - PEP 794 + import_names: list[str] + import_namespaces: list[str] + + +# 'keywords' is special as it's a string in the core metadata spec, but we +# represent it as a list. +_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", + "import_names", + "import_namespaces", +} + +_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 potential 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 unparsable and add it + # to our list of unparsed fields. + # + # 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 = (s.strip() for s in pair.partition(",")) + + if label in urls: + # The label already exists in our set of urls, so this field + # is unparsable, and we can just add the whole thing to our + # unparsable 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", + "import-name": "import_names", + "import-namespace": "import_namespaces", + "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()} + + +# This class is for writing RFC822 messages +class RFC822Policy(email.policy.EmailPolicy): + """ + This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse`` + implementation that handles multi-line values, and some nice defaults. + """ + + utf8 = True + mangle_from_ = False + max_line_length = 0 + + def header_store_parse(self, name: str, value: str) -> tuple[str, str]: + size = len(name) + 2 + value = value.replace("\n", "\n" + " " * size) + return (name, value) + + +# This class is for writing RFC822 messages +class RFC822Message(email.message.EmailMessage): + """ + This is :class:`email.message.EmailMessage` with two small changes: it defaults to + our `RFC822Policy`, and it correctly writes unicode when being called + with `bytes()`. + """ + + def __init__(self) -> None: + super().__init__(policy=RFC822Policy()) + + def as_bytes( + self, unixfrom: bool = False, policy: email.policy.Policy | None = None + ) -> bytes: + """ + Return the bytes representation of the message. + + This handles unicode encoding. + """ + return self.as_string(unixfrom, policy=policy).encode("utf-8") + + +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_with_case 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_with_case.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 binary, _encoding in email.header.decode_header(h): + try: + binary.decode("utf8", "strict") + except UnicodeDecodeError: + # Enable mojibake. + encoding = "latin1" + valid_encoding = False + else: + encoding = "utf8" + chunks.append((binary, 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 import_names, we need to special case the empty field + # case, which converts to an empty list instead of None. We can't let + # the empty case slip through, as it will fail validation. + elif raw_name == "import_names" and value == [""]: + raw[raw_name] = [] + # 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 unparsable 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 unparsable. + 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", "2.5"] +_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"] + +_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: + 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 + + def _process_import_names(self, value: list[str]) -> list[str]: + for import_name in value: + name, semicolon, private = import_name.partition(";") + name = name.rstrip() + for identifier in name.split("."): + if not identifier.isidentifier(): + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}; " + f"{identifier!r} is not a valid identifier" + ) + elif keyword.iskeyword(identifier): + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}; " + f"{identifier!r} is a keyword" + ) + if semicolon and private.lstrip() != "private": + raise self._invalid_metadata( + f"{import_name!r} is invalid for {{field}}; " + "the only valid option is 'private'" + ) + return value + + _process_import_namespaces = _process_import_names + + +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`""" + import_names: _Validator[list[str] | None] = _Validator(added="2.5") + """:external:ref:`core-metadata-import-name`""" + import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5") + """:external:ref:`core-metadata-import-namespace`""" + 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)""" + + def as_rfc822(self) -> RFC822Message: + """ + Return an RFC822 message with the metadata. + """ + message = RFC822Message() + self._write_metadata(message) + return message + + def _write_metadata(self, message: RFC822Message) -> None: + """ + Return an RFC822 message with the metadata. + """ + for name, validator in self.__class__.__dict__.items(): + if isinstance(validator, _Validator) and name != "description": + value = getattr(self, name) + email_name = _RAW_TO_EMAIL_MAPPING[name] + if value is not None: + if email_name == "project-url": + for label, url in value.items(): + message[email_name] = f"{label}, {url}" + elif email_name == "keywords": + message[email_name] = ",".join(value) + elif email_name == "import-name" and value == []: + message[email_name] = "" + elif isinstance(value, list): + for item in value: + message[email_name] = str(item) + else: + message[email_name] = str(value) + + # The description is a special case because it is in the body of the message. + if self.description is not None: + message.set_payload(self.description) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/py.typed b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/pylock.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/pylock.py new file mode 100644 index 0000000000000000000000000000000000000000..a564f15246ad65038029f8fefb48621fa64a3abd --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/pylock.py @@ -0,0 +1,635 @@ +from __future__ import annotations + +import dataclasses +import logging +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Protocol, + TypeVar, +) + +from .markers import Marker +from .specifiers import SpecifierSet +from .utils import NormalizedName, is_normalized_name +from .version import Version + +if TYPE_CHECKING: # pragma: no cover + from pathlib import Path + + from typing_extensions import Self + +_logger = logging.getLogger(__name__) + +__all__ = [ + "Package", + "PackageArchive", + "PackageDirectory", + "PackageSdist", + "PackageVcs", + "PackageWheel", + "Pylock", + "PylockUnsupportedVersionError", + "PylockValidationError", + "is_valid_pylock_path", +] + +_T = TypeVar("_T") +_T2 = TypeVar("_T2") + + +class _FromMappingProtocol(Protocol): # pragma: no cover + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... + + +_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) + + +_PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$") + + +def is_valid_pylock_path(path: Path) -> bool: + """Check if the given path is a valid pylock file path.""" + return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name)) + + +def _toml_key(key: str) -> str: + return key.replace("_", "-") + + +def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 + if isinstance(value, (Version, Marker, SpecifierSet)): + return str(value) + if isinstance(value, Sequence) and key == "environments": + return [str(v) for v in value] + return value + + +def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: + return { + _toml_key(key): _toml_value(key, value) + for key, value in data + if value is not None + } + + +def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: + """Get a value from the dictionary and verify it's the expected type.""" + if (value := d.get(key)) is None: + return None + if not isinstance(value, expected_type): + raise PylockValidationError( + f"Unexpected type {type(value).__name__} " + f"(expected {expected_type.__name__})", + context=key, + ) + return value + + +def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: + """Get a required value from the dictionary and verify it's the expected type.""" + if (value := _get(d, expected_type, key)) is None: + raise _PylockRequiredKeyError(key) + return value + + +def _get_sequence( + d: Mapping[str, Any], expected_item_type: type[_T], key: str +) -> Sequence[_T] | None: + """Get a list value from the dictionary and verify it's the expected items type.""" + if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] + return None + if isinstance(value, (str, bytes)): + # special case: str and bytes are Sequences, but we want to reject it + raise PylockValidationError( + f"Unexpected type {type(value).__name__} (expected Sequence)", + context=key, + ) + for i, item in enumerate(value): + if not isinstance(item, expected_item_type): + raise PylockValidationError( + f"Unexpected type {type(item).__name__} " + f"(expected {expected_item_type.__name__})", + context=f"{key}[{i}]", + ) + return value + + +def _get_as( + d: Mapping[str, Any], + expected_type: type[_T], + target_type: Callable[[_T], _T2], + key: str, +) -> _T2 | None: + """Get a value from the dictionary, verify it's the expected type, + and convert to the target type. + + This assumes the target_type constructor accepts the value. + """ + if (value := _get(d, expected_type, key)) is None: + return None + try: + return target_type(value) + except Exception as e: + raise PylockValidationError(e, context=key) from e + + +def _get_required_as( + d: Mapping[str, Any], + expected_type: type[_T], + target_type: Callable[[_T], _T2], + key: str, +) -> _T2: + """Get a required value from the dict, verify it's the expected type, + and convert to the target type.""" + if (value := _get_as(d, expected_type, target_type, key)) is None: + raise _PylockRequiredKeyError(key) + return value + + +def _get_sequence_as( + d: Mapping[str, Any], + expected_item_type: type[_T], + target_item_type: Callable[[_T], _T2], + key: str, +) -> list[_T2] | None: + """Get list value from dictionary and verify expected items type.""" + if (value := _get_sequence(d, expected_item_type, key)) is None: + return None + result = [] + try: + for item in value: + typed_item = target_item_type(item) + result.append(typed_item) + except Exception as e: + raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e + return result + + +def _get_object( + d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str +) -> _FromMappingProtocolT | None: + """Get a dictionary value from the dictionary and convert it to a dataclass.""" + if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] + return None + try: + return target_type._from_dict(value) + except Exception as e: + raise PylockValidationError(e, context=key) from e + + +def _get_sequence_of_objects( + d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str +) -> list[_FromMappingProtocolT] | None: + """Get a list value from the dictionary and convert its items to a dataclass.""" + if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] + return None + result: list[_FromMappingProtocolT] = [] + try: + for item in value: + typed_item = target_item_type._from_dict(item) + result.append(typed_item) + except Exception as e: + raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e + return result + + +def _get_required_sequence_of_objects( + d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str +) -> Sequence[_FromMappingProtocolT]: + """Get a required list value from the dictionary and convert its items to a + dataclass.""" + if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: + raise _PylockRequiredKeyError(key) + return result + + +def _validate_normalized_name(name: str) -> NormalizedName: + """Validate that a string is a NormalizedName.""" + if not is_normalized_name(name): + raise PylockValidationError(f"Name {name!r} is not normalized") + return NormalizedName(name) + + +def _validate_path_url(path: str | None, url: str | None) -> None: + if not path and not url: + raise PylockValidationError("path or url must be provided") + + +def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: + if not hashes: + raise PylockValidationError("At least one hash must be provided") + if not all(isinstance(hash_val, str) for hash_val in hashes.values()): + raise PylockValidationError("Hash values must be strings") + return hashes + + +class PylockValidationError(Exception): + """Raised when when input data is not spec-compliant.""" + + context: str | None = None + message: str + + def __init__( + self, + cause: str | Exception, + *, + context: str | None = None, + ) -> None: + if isinstance(cause, PylockValidationError): + if cause.context: + self.context = ( + f"{context}.{cause.context}" if context else cause.context + ) + else: + self.context = context + self.message = cause.message + else: + self.context = context + self.message = str(cause) + + def __str__(self) -> str: + if self.context: + return f"{self.message} in {self.context!r}" + return self.message + + +class _PylockRequiredKeyError(PylockValidationError): + def __init__(self, key: str) -> None: + super().__init__("Missing required value", context=key) + + +class PylockUnsupportedVersionError(PylockValidationError): + """Raised when encountering an unsupported `lock_version`.""" + + +@dataclass(frozen=True, init=False) +class PackageVcs: + type: str + url: str | None = None + path: str | None = None + requested_revision: str | None = None + commit_id: str # type: ignore[misc] + subdirectory: str | None = None + + def __init__( + self, + *, + type: str, + url: str | None = None, + path: str | None = None, + requested_revision: str | None = None, + commit_id: str, + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "type", type) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "requested_revision", requested_revision) + object.__setattr__(self, "commit_id", commit_id) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_vcs = cls( + type=_get_required(d, str, "type"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + requested_revision=_get(d, str, "requested-revision"), + commit_id=_get_required(d, str, "commit-id"), + subdirectory=_get(d, str, "subdirectory"), + ) + _validate_path_url(package_vcs.path, package_vcs.url) + return package_vcs + + +@dataclass(frozen=True, init=False) +class PackageDirectory: + path: str + editable: bool | None = None + subdirectory: str | None = None + + def __init__( + self, + *, + path: str, + editable: bool | None = None, + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "path", path) + object.__setattr__(self, "editable", editable) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + return cls( + path=_get_required(d, str, "path"), + editable=_get(d, bool, "editable"), + subdirectory=_get(d, str, "subdirectory"), + ) + + +@dataclass(frozen=True, init=False) +class PackageArchive: + url: str | None = None + path: str | None = None + size: int | None = None + upload_time: datetime | None = None + hashes: Mapping[str, str] # type: ignore[misc] + subdirectory: str | None = None + + def __init__( + self, + *, + url: str | None = None, + path: str | None = None, + size: int | None = None, + upload_time: datetime | None = None, + hashes: Mapping[str, str], + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "hashes", hashes) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_archive = cls( + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + upload_time=_get(d, datetime, "upload-time"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + subdirectory=_get(d, str, "subdirectory"), + ) + _validate_path_url(package_archive.path, package_archive.url) + return package_archive + + +@dataclass(frozen=True, init=False) +class PackageSdist: + name: str | None = None + upload_time: datetime | None = None + url: str | None = None + path: str | None = None + size: int | None = None + hashes: Mapping[str, str] # type: ignore[misc] + + def __init__( + self, + *, + name: str | None = None, + upload_time: datetime | None = None, + url: str | None = None, + path: str | None = None, + size: int | None = None, + hashes: Mapping[str, str], + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "hashes", hashes) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_sdist = cls( + name=_get(d, str, "name"), + upload_time=_get(d, datetime, "upload-time"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + ) + _validate_path_url(package_sdist.path, package_sdist.url) + return package_sdist + + +@dataclass(frozen=True, init=False) +class PackageWheel: + name: str | None = None + upload_time: datetime | None = None + url: str | None = None + path: str | None = None + size: int | None = None + hashes: Mapping[str, str] # type: ignore[misc] + + def __init__( + self, + *, + name: str | None = None, + upload_time: datetime | None = None, + url: str | None = None, + path: str | None = None, + size: int | None = None, + hashes: Mapping[str, str], + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "hashes", hashes) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_wheel = cls( + name=_get(d, str, "name"), + upload_time=_get(d, datetime, "upload-time"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + ) + _validate_path_url(package_wheel.path, package_wheel.url) + return package_wheel + + +@dataclass(frozen=True, init=False) +class Package: + name: NormalizedName + version: Version | None = None + marker: Marker | None = None + requires_python: SpecifierSet | None = None + dependencies: Sequence[Mapping[str, Any]] | None = None + vcs: PackageVcs | None = None + directory: PackageDirectory | None = None + archive: PackageArchive | None = None + index: str | None = None + sdist: PackageSdist | None = None + wheels: Sequence[PackageWheel] | None = None + attestation_identities: Sequence[Mapping[str, Any]] | None = None + tool: Mapping[str, Any] | None = None + + def __init__( + self, + *, + name: NormalizedName, + version: Version | None = None, + marker: Marker | None = None, + requires_python: SpecifierSet | None = None, + dependencies: Sequence[Mapping[str, Any]] | None = None, + vcs: PackageVcs | None = None, + directory: PackageDirectory | None = None, + archive: PackageArchive | None = None, + index: str | None = None, + sdist: PackageSdist | None = None, + wheels: Sequence[PackageWheel] | None = None, + attestation_identities: Sequence[Mapping[str, Any]] | None = None, + tool: Mapping[str, Any] | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "version", version) + object.__setattr__(self, "marker", marker) + object.__setattr__(self, "requires_python", requires_python) + object.__setattr__(self, "dependencies", dependencies) + object.__setattr__(self, "vcs", vcs) + object.__setattr__(self, "directory", directory) + object.__setattr__(self, "archive", archive) + object.__setattr__(self, "index", index) + object.__setattr__(self, "sdist", sdist) + object.__setattr__(self, "wheels", wheels) + object.__setattr__(self, "attestation_identities", attestation_identities) + object.__setattr__(self, "tool", tool) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package = cls( + name=_get_required_as(d, str, _validate_normalized_name, "name"), + version=_get_as(d, str, Version, "version"), + requires_python=_get_as(d, str, SpecifierSet, "requires-python"), + dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract] + marker=_get_as(d, str, Marker, "marker"), + vcs=_get_object(d, PackageVcs, "vcs"), + directory=_get_object(d, PackageDirectory, "directory"), + archive=_get_object(d, PackageArchive, "archive"), + index=_get(d, str, "index"), + sdist=_get_object(d, PackageSdist, "sdist"), + wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"), + attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract] + tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] + ) + distributions = bool(package.sdist) + len(package.wheels or []) + direct_urls = ( + bool(package.vcs) + bool(package.directory) + bool(package.archive) + ) + if distributions > 0 and direct_urls > 0: + raise PylockValidationError( + "None of vcs, directory, archive must be set if sdist or wheels are set" + ) + if distributions == 0 and direct_urls != 1: + raise PylockValidationError( + "Exactly one of vcs, directory, archive must be set " + "if sdist and wheels are not set" + ) + try: + for i, attestation_identity in enumerate( # noqa: B007 + package.attestation_identities or [] + ): + _get_required(attestation_identity, str, "kind") + except Exception as e: + raise PylockValidationError( + e, context=f"attestation-identities[{i}]" + ) from e + return package + + @property + def is_direct(self) -> bool: + return not (self.sdist or self.wheels) + + +@dataclass(frozen=True, init=False) +class Pylock: + """A class representing a pylock file.""" + + lock_version: Version + environments: Sequence[Marker] | None = None + requires_python: SpecifierSet | None = None + extras: Sequence[NormalizedName] | None = None + dependency_groups: Sequence[str] | None = None + default_groups: Sequence[str] | None = None + created_by: str # type: ignore[misc] + packages: Sequence[Package] # type: ignore[misc] + tool: Mapping[str, Any] | None = None + + def __init__( + self, + *, + lock_version: Version, + environments: Sequence[Marker] | None = None, + requires_python: SpecifierSet | None = None, + extras: Sequence[NormalizedName] | None = None, + dependency_groups: Sequence[str] | None = None, + default_groups: Sequence[str] | None = None, + created_by: str, + packages: Sequence[Package], + tool: Mapping[str, Any] | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "lock_version", lock_version) + object.__setattr__(self, "environments", environments) + object.__setattr__(self, "requires_python", requires_python) + object.__setattr__(self, "extras", extras) + object.__setattr__(self, "dependency_groups", dependency_groups) + object.__setattr__(self, "default_groups", default_groups) + object.__setattr__(self, "created_by", created_by) + object.__setattr__(self, "packages", packages) + object.__setattr__(self, "tool", tool) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + pylock = cls( + lock_version=_get_required_as(d, str, Version, "lock-version"), + environments=_get_sequence_as(d, str, Marker, "environments"), + extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"), + dependency_groups=_get_sequence(d, str, "dependency-groups"), + default_groups=_get_sequence(d, str, "default-groups"), + created_by=_get_required(d, str, "created-by"), + requires_python=_get_as(d, str, SpecifierSet, "requires-python"), + packages=_get_required_sequence_of_objects(d, Package, "packages"), + tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] + ) + if not Version("1") <= pylock.lock_version < Version("2"): + raise PylockUnsupportedVersionError( + f"pylock version {pylock.lock_version} is not supported" + ) + if pylock.lock_version > Version("1.0"): + _logger.warning( + "pylock minor version %s is not supported", pylock.lock_version + ) + return pylock + + @classmethod + def from_dict(cls, d: Mapping[str, Any], /) -> Self: + """Create and validate a Pylock instance from a TOML dictionary. + + Raises :class:`PylockValidationError` if the input data is not + spec-compliant. + """ + return cls._from_dict(d) + + def to_dict(self) -> Mapping[str, Any]: + """Convert the Pylock instance to a TOML dictionary.""" + return dataclasses.asdict(self, dict_factory=_toml_dict_factory) + + def validate(self) -> None: + """Validate the Pylock instance against the specification. + + Raises :class:`PylockValidationError` otherwise.""" + self.from_dict(self.to_dict()) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/requirements.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..3079be69bf880f47e64dbf62993f0e54754b7315 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/requirements.py @@ -0,0 +1,86 @@ +# 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 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"<{self.__class__.__name__}('{self}')>" + + def __hash__(self) -> int: + return hash(tuple(self._iter_parts(canonicalize_name(self.name)))) + + def __eq__(self, other: object) -> 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/specifiers.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..5d26b0d1ae2d21b77e24b692d5a7e1fd01296edc --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/specifiers.py @@ -0,0 +1,1068 @@ +# 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, Final, Iterable, Iterator, TypeVar, Union + +from .utils import canonicalize_version +from .version import InvalidVersion, Version + +UnparsedVersion = Union[Version, str] +UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) +CallableOperator = Callable[[Version, str], bool] + + +def _coerce_version(version: UnparsedVersion) -> Version | None: + if not isinstance(version, Version): + try: + version = Version(version) + except InvalidVersion: + return None + return version + + +def _public_version(version: Version) -> Version: + return version.__replace__(local=None) + + +def _base_version(version: Version) -> Version: + return version.__replace__(pre=None, post=None, dev=None, local=None) + + +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): + __slots__ = () + __match_args__ = ("_str",) + + @property + def _str(self) -> str: + """Internal property for match_args""" + return str(self) + + @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 # noqa: B027 + 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). + """ + + __slots__ = ("_prereleases", "_spec", "_spec_version") + + _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.fullmatch(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 + + # Specifier version cache + self._spec_version: tuple[str, Version] | None = None + + def _get_spec_version(self, version: str) -> Version | None: + """One element cache, as only one spec Version is needed per Specifier.""" + if self._spec_version is not None and self._spec_version[0] == version: + return self._spec_version[1] + + version_specifier = _coerce_version(version) + if version_specifier is None: + return None + + self._spec_version = (version, version_specifier) + return version_specifier + + def _require_spec_version(self, version: str) -> Version: + """Get spec version, asserting it's valid (not for === operator). + + This method should only be called for operators where version + strings are guaranteed to be valid PEP 440 versions (not ===). + """ + spec_version = self._get_spec_version(version) + assert spec_version is not None + return spec_version + + @property + def prereleases(self) -> bool | None: + # 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 + + # Only the "!=" operator does not imply prereleases when + # the version in the specifier is a prerelease. + operator, version_str = self._spec + if operator != "!=": + # The == specifier with trailing .* cannot include prereleases + # e.g. "==1.0a1.*" is not valid. + if operator == "==" and version_str.endswith(".*"): + return False + + # "===" can have arbitrary string versions, so we cannot parse + # those, we take prereleases as unknown (None) for those. + version = self._get_spec_version(version_str) + if version is None: + return None + + # For all other operators, use the check if spec Version + # object implies pre-releases. + if version.is_prerelease: + return True + + return False + + @prereleases.setter + def prereleases(self, value: bool | None) -> 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]: + operator, version = self._spec + if operator == "===" or version.endswith(".*"): + return operator, version + + spec_version = self._require_spec_version(version) + + canonical_version = canonicalize_version( + spec_version, strip_trailing_zero=(operator != "~=") + ) + + return operator, 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( + _public_version(prospective), 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 = self._require_spec_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 = _public_version(prospective) + + 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 _public_version(prospective) <= self._require_spec_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 _public_version(prospective) >= self._require_spec_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 = self._require_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 + and _base_version(prospective) == _base_version(spec) + ): + 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 = self._require_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 + and _base_version(prospective) == _base_version(spec) + ): + 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 and _base_version( + prospective + ) == _base_version(spec): + 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 | str, 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") + True + >>> "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 will follow the recommendation from + :pep:`440` and match prereleases, as there are no other versions. + + >>> 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") + True + >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + True + """ + + return bool(list(self.filter([item], prereleases=prereleases))) + + 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 follow the recommendation from :pep:`440` + and match prereleases if there are no other versions. + + >>> 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'] + """ + prereleases_versions = [] + found_non_prereleases = False + + # Determine if to include prereleases by default + include_prereleases = ( + prereleases if prereleases is not None else self.prereleases + ) + + # Get the matching operator + operator_callable = self._get_operator(self.operator) + + # Filter versions + for version in iterable: + parsed_version = _coerce_version(version) + if parsed_version is None: + # === operator can match arbitrary (non-version) strings + if self.operator == "===" and self._compare_arbitrary( + version, self.version + ): + yield version + elif operator_callable(parsed_version, self.version): + # If it's not a prerelease or prereleases are allowed, yield it directly + if not parsed_version.is_prerelease or include_prereleases: + found_non_prereleases = True + yield version + # Otherwise collect prereleases for potential later use + elif prereleases is None and self._prereleases is not False: + prereleases_versions.append(version) + + # If no non-prereleases were found and prereleases weren't + # explicitly forbidden, yield the collected prereleases + if ( + not found_non_prereleases + and prereleases is None + and self._prereleases is not False + ): + yield from prereleases_versions + + +_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.fullmatch(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. + """ + + __slots__ = ("_prereleases", "_specs") + + 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. + if any(s.prereleases for s in self._specs): + return True + + return None + + @prereleases.setter + def prereleases(self, value: bool | None) -> 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 + ) or 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") + True + >>> "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 will follow the recommendation from :pep:`440` + and match prereleases, as there are no other versions. + :param installed: + Whether or not the item is installed. If set to ``True``, it will + accept prerelease versions even if the specifier does not allow them. + + >>> 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") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) + True + """ + version = _coerce_version(item) + + if version is not None and installed and version.is_prerelease: + prereleases = True + + check_item = item if version is None else version + return bool(list(self.filter([check_item], prereleases=prereleases))) + + 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 follow the recommendation from :pep:`440` + and match prereleases if there are no other versions. + + >>> 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"])) + ['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 and self.prereleases is not 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: + # When prereleases is None, we need to let all versions through + # the individual filters, then decide about prereleases at the end + # based on whether any non-prereleases matched ALL specs. + for spec in self._specs: + iterable = spec.filter( + iterable, prereleases=True if prereleases is None else prereleases + ) + + if prereleases is not None: + # If we have a forced prereleases value, + # we can immediately return the iterator. + return iter(iterable) + else: + # Handle empty SpecifierSet cases where prereleases is not None. + if prereleases is True: + return iter(iterable) + + if prereleases is False: + return ( + item + for item in iterable + if (version := _coerce_version(item)) is None + or not version.is_prerelease + ) + + # Finally if prereleases is None, apply PEP 440 logic: + # exclude prereleases unless there are no final releases that matched. + filtered_items: list[UnparsedVersionVar] = [] + found_prereleases: list[UnparsedVersionVar] = [] + found_final_release = False + + for item in iterable: + parsed_version = _coerce_version(item) + # Arbitrary strings are always included as it is not + # possible to determine if they are prereleases, + # and they have already passed all specifiers. + if parsed_version is None: + filtered_items.append(item) + found_prereleases.append(item) + elif parsed_version.is_prerelease: + found_prereleases.append(item) + else: + filtered_items.append(item) + found_final_release = True + + return iter(filtered_items if found_final_release else found_prereleases) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/tags.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..5ef27c897a4df35a2a6923b608a5e04a0a38b9ee --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/tags.py @@ -0,0 +1,651 @@ +# 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 ( + Any, + 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 __setstate__(self, state: tuple[None, dict[str, Any]]) -> None: + # The cached _hash is wrong when unpickling. + _, slots = state + for k, v in slots.items(): + setattr(self, k, v) + self._hash = hash((self._interpreter, self._abi, self._platform)) + + +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: + abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else [] + abis = list(abis) + # 'abi3' and 'none' are explicitly handled later. + for explicit_abi in ("abi3", "none"): + try: + abis.remove(explicit_abi) + except ValueError: # noqa: PERF203 + 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 = f"{interp_name}{interp_version}" + abis = _generic_abi() if abis is None else 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]))) + + if arch is None: + arch = _mac_arch(cpu_arch) + + if (10, 0) <= 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 android_platforms( + api_level: int | None = None, abi: str | None = None +) -> Iterator[str]: + """ + Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on + non-Android platforms, the ``api_level`` and ``abi`` arguments are required. + + :param int api_level: The maximum `API level + `__ to return. Defaults + to the current system's version, as returned by ``platform.android_ver``. + :param str abi: The `Android ABI `__, + e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by + ``sysconfig.get_platform``. Hyphens and periods will be replaced with + underscores. + """ + if platform.system() != "Android" and (api_level is None or abi is None): + raise TypeError( + "on non-Android platforms, the api_level and abi arguments are required" + ) + + if api_level is None: + # Python 3.13 was the first version to return platform.system() == "Android", + # and also the first version to define platform.android_ver(). + api_level = platform.android_ver().api_level # type: ignore[attr-defined] + + if abi is None: + abi = sysconfig.get_platform().split("-")[-1] + abi = _normalize_string(abi) + + # 16 is the minimum API level known to have enough features to support CPython + # without major patching. Yield every API level from the maximum down to the + # minimum, inclusive. + min_api_level = 16 + for ver in range(api_level, min_api_level - 1, -1): + yield f"android_{ver}_{abi}" + + +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() == "Android": + return android_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) + return str(version) if version else _version_nodot(sys.version_info[:2]) + + +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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/utils.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c41c8137f2679a0fac21bb845596e231ae88dbd8 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/utils.py @@ -0,0 +1,158 @@ +# 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 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) +_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.fullmatch(name): + raise InvalidName(f"name is invalid: {name!r}") + # Ensure all ``.`` and ``_`` are ``-`` + # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503 + # Much faster than re, and even faster than str.translate + value = name.lower().replace("_", "-").replace(".", "-") + # Condense repeats (faster than regex) + while "--" in value: + value = value.replace("--", "-") + return cast("NormalizedName", value) + + +def is_normalized_name(name: str) -> bool: + return _normalized_regex.fullmatch(name) is not None + + +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' + """ + if isinstance(version, str): + try: + version = Version(version) + except InvalidVersion: + return str(version) + return str(_TrimmedRelease(version) if strip_trailing_zero else version) + + +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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/version.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/version.py new file mode 100644 index 0000000000000000000000000000000000000000..1206c462d4fcaa670a816e201bb88b27dfc9cf88 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/packaging/version.py @@ -0,0 +1,792 @@ +# 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 re +import sys +import typing +from typing import ( + Any, + Callable, + Literal, + NamedTuple, + SupportsInt, + Tuple, + TypedDict, + Union, +) + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +if typing.TYPE_CHECKING: + from typing_extensions import Self, Unpack + +if sys.version_info >= (3, 13): # pragma: no cover + from warnings import deprecated as _deprecated +elif typing.TYPE_CHECKING: + from typing_extensions import deprecated as _deprecated +else: # pragma: no cover + import functools + import warnings + + def _deprecated(message: str) -> object: + def decorator(func: object) -> object: + @functools.wraps(func) + def wrapper(*args: object, **kwargs: object) -> object: + warnings.warn( + message, + category=DeprecationWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return wrapper + + return decorator + + +_LETTER_NORMALIZATION = { + "alpha": "a", + "beta": "b", + "c": "rc", + "pre": "rc", + "preview": "rc", + "rev": "post", + "r": "post", +} + +__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 _VersionReplace(TypedDict, total=False): + epoch: int | None + release: tuple[int, ...] | None + pre: tuple[Literal["a", "b", "rc"], int] | None + post: int | None + dev: int | None + local: str | 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: + __slots__ = () + + # This can also be a normal member (see the packaging_legacy package); + # we are just requiring it to be readable. Actually defining a property + # has runtime effect on subclasses, so it's typing only. + if typing.TYPE_CHECKING: + + @property + def _key(self) -> 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 + +# Note that ++ doesn't behave identically on CPython and PyPy, so not using it here +_VERSION_PATTERN = r""" + v?+ # optional leading 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                                        # local version
+            [a-z0-9]+
+            (?:[._-][a-z0-9]+)*+
+        )
+    )?+
+"""
+
+_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
+
+# Possessive qualifiers were added in Python 3.11.
+# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795
+# Older PyPy also had a bug.
+VERSION_PATTERN = (
+    _VERSION_PATTERN_OLD
+    if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5))
+    or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13))
+    or sys.version_info < (3, 11)
+    else _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:
+"""
+
+
+# Validation pattern for local version in replace()
+_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE)
+
+
+def _validate_epoch(value: object, /) -> int:
+    epoch = value or 0
+    if isinstance(epoch, int) and epoch >= 0:
+        return epoch
+    msg = f"epoch must be non-negative integer, got {epoch}"
+    raise InvalidVersion(msg)
+
+
+def _validate_release(value: object, /) -> tuple[int, ...]:
+    release = (0,) if value is None else value
+    if (
+        isinstance(release, tuple)
+        and len(release) > 0
+        and all(isinstance(i, int) and i >= 0 for i in release)
+    ):
+        return release
+    msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
+    raise InvalidVersion(msg)
+
+
+def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
+    if value is None:
+        return value
+    if (
+        isinstance(value, tuple)
+        and len(value) == 2
+        and value[0] in ("a", "b", "rc")
+        and isinstance(value[1], int)
+        and value[1] >= 0
+    ):
+        return value
+    msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, int) and value >= 0:
+        return ("post", value)
+    msg = f"post must be non-negative integer, got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, int) and value >= 0:
+        return ("dev", value)
+    msg = f"dev must be non-negative integer, got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_local(value: object, /) -> LocalType | None:
+    if value is None:
+        return value
+    if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
+        return _parse_local_version(value)
+    msg = f"local must be a valid version string, got {value!r}"
+    raise InvalidVersion(msg)
+
+
+# Backward compatibility for internals before 26.0. Do not use.
+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
+
+
+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
+    """
+
+    __slots__ = ("_dev", "_epoch", "_key_cache", "_local", "_post", "_pre", "_release")
+    __match_args__ = ("_str",)
+
+    _regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
+
+    _epoch: int
+    _release: tuple[int, ...]
+    _dev: tuple[str, int] | None
+    _pre: tuple[str, int] | None
+    _post: tuple[str, int] | None
+    _local: LocalType | None
+
+    _key_cache: CmpKey | None
+
+    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.fullmatch(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: {version!r}")
+        self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
+        self._release = tuple(map(int, match.group("release").split(".")))
+        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))
+        self._post = _parse_letter_version(
+            match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+        )
+        self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))
+        self._local = _parse_local_version(match.group("local"))
+
+        # Key which will be used for sorting
+        self._key_cache = None
+
+    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
+        epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
+        release = (
+            _validate_release(kwargs["release"])
+            if "release" in kwargs
+            else self._release
+        )
+        pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
+        post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
+        dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
+        local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
+
+        if (
+            epoch == self._epoch
+            and release == self._release
+            and pre == self._pre
+            and post == self._post
+            and dev == self._dev
+            and local == self._local
+        ):
+            return self
+
+        new_version = self.__class__.__new__(self.__class__)
+        new_version._key_cache = None
+        new_version._epoch = epoch
+        new_version._release = release
+        new_version._pre = pre
+        new_version._post = post
+        new_version._dev = dev
+        new_version._local = local
+
+        return new_version
+
+    @property
+    def _key(self) -> CmpKey:
+        if self._key_cache is None:
+            self._key_cache = _cmpkey(
+                self._epoch,
+                self._release,
+                self._pre,
+                self._post,
+                self._dev,
+                self._local,
+            )
+        return self._key_cache
+
+    @property
+    @_deprecated("Version._version is private and will be removed soon")
+    def _version(self) -> _Version:
+        return _Version(
+            self._epoch, self._release, self._dev, self._pre, self._post, self._local
+        )
+
+    @_version.setter
+    @_deprecated("Version._version is private and will be removed soon")
+    def _version(self, value: _Version) -> None:
+        self._epoch = value.epoch
+        self._release = value.release
+        self._dev = value.dev
+        self._pre = value.pre
+        self._post = value.post
+        self._local = value.local
+        self._key_cache = None
+
+    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'
+        """
+        # This is a hot function, so not calling self.base_version
+        version = ".".join(map(str, self.release))
+
+        # Epoch
+        if self.epoch:
+            version = f"{self.epoch}!{version}"
+
+        # Pre-release
+        if self.pre is not None:
+            version += "".join(map(str, self.pre))
+
+        # Post-release
+        if self.post is not None:
+            version += f".post{self.post}"
+
+        # Development release
+        if self.dev is not None:
+            version += f".dev{self.dev}"
+
+        # Local version segment
+        if self.local is not None:
+            version += f"+{self.local}"
+
+        return version
+
+    @property
+    def _str(self) -> str:
+        """Internal property for match_args"""
+        return str(self)
+
+    @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._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._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._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._post[1] if self._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._dev[1] if self._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._local:
+            return ".".join(str(x) for x in self._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.
+        """
+        release_segment = ".".join(map(str, self.release))
+        return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
+
+    @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):
+    __slots__ = ()
+
+    def __init__(self, version: str | Version) -> None:
+        if isinstance(version, Version):
+            self._epoch = version._epoch
+            self._release = version._release
+            self._dev = version._dev
+            self._pre = version._pre
+            self._post = version._post
+            self._local = version._local
+            self._key_cache = version._key_cache
+            return
+        super().__init__(version)  # pragma: no cover
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """
+        Release segment without any trailing zeros.
+
+        >>> _TrimmedRelease('1.0.0').release
+        (1,)
+        >>> _TrimmedRelease('0.0').release
+        (0,)
+        """
+        # This leaves one 0.
+        rel = super().release
+        len_release = len(rel)
+        i = len_release
+        while i > 1 and rel[i - 1] == 0:
+            i -= 1
+        return rel if i == len_release else rel[:i]
+
+
+def _parse_letter_version(
+    letter: str | None, number: str | bytes | SupportsInt | None
+) -> tuple[str, int] | None:
+    if letter:
+        # 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.
+        letter = _LETTER_NORMALIZATION.get(letter, letter)
+
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        return letter, int(number or 0)
+
+    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)
+        return "post", 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. We will use this for our sorting key.
+    len_release = len(release)
+    i = len_release
+    while i and release[i - 1] == 0:
+        i -= 1
+    _release = release if i == len_release else release[:i]
+
+    # 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..6b0908fb707440b3828bfe2edb1799382693199e
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/METADATA
@@ -0,0 +1,350 @@
+Metadata-Version: 2.4
+Name: platformdirs
+Version: 4.4.0
+Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`.
+Project-URL: Changelog, https://github.com/tox-dev/platformdirs/releases
+Project-URL: Documentation, https://platformdirs.readthedocs.io
+Project-URL: Homepage, https://github.com/tox-dev/platformdirs
+Project-URL: Source, https://github.com/tox-dev/platformdirs
+Project-URL: Tracker, https://github.com/tox-dev/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.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: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.9
+Provides-Extra: docs
+Requires-Dist: furo>=2024.8.6; extra == 'docs'
+Requires-Dist: proselint>=0.14; extra == 'docs'
+Requires-Dist: sphinx-autodoc-typehints>=3; extra == 'docs'
+Requires-Dist: sphinx>=8.1.3; extra == 'docs'
+Provides-Extra: test
+Requires-Dist: appdirs==1.4.4; extra == 'test'
+Requires-Dist: covdefaults>=2.3; extra == 'test'
+Requires-Dist: pytest-cov>=6; extra == 'test'
+Requires-Dist: pytest-mock>=3.14; extra == 'test'
+Requires-Dist: pytest>=8.3.4; extra == 'test'
+Provides-Extra: type
+Requires-Dist: mypy>=1.14.1; extra == 'type'
+Description-Content-Type: text/x-rst
+
+The problem
+===========
+
+.. image:: https://badge.fury.io/py/platformdirs.svg
+   :target: https://badge.fury.io/py/platformdirs
+.. image:: https://img.shields.io/pypi/pyversions/platformdirs.svg
+   :target: https://pypi.python.org/pypi/platformdirs/
+.. image:: https://github.com/tox-dev/platformdirs/actions/workflows/check.yaml/badge.svg
+   :target: https://github.com/platformdirs/platformdirs/actions
+.. image:: https://static.pepy.tech/badge/platformdirs/month
+   :target: https://pepy.tech/project/platformdirs
+
+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'
+    >>> user_config_dir(appname, appauthor)
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/Library/Application Support/SuperApp'
+    >>> site_config_dir(appname, appauthor)
+    '/Library/Application Support/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_config_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache'
+    >>> site_data_dir(appname, appauthor)
+    'C:\\ProgramData\\Acme\\SuperApp'
+    >>> site_config_dir(appname, appauthor)
+    'C:\\ProgramData\\Acme\\SuperApp'
+    >>> 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'
+    >>> user_config_dir(appname)
+    '/home/trentm/.config/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/home/trentm/.cache/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/usr/local/share/SuperApp'
+    >>> site_data_dir(appname, appauthor, multipath=True)
+    '/usr/local/share/SuperApp:/usr/share/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'
+    >>> user_log_dir(appname, appauthor)
+    '/home/trentm/.local/state/SuperApp/log'
+    >>> 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'
+
+On Android::
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/data/data/com.myApp/files/SuperApp'
+    >>> user_config_dir(appname)
+    '/data/data/com.myApp/shared_prefs/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/data/data/com.myApp/files/SuperApp'
+    >>> site_config_dir(appname)
+    '/data/data/com.myApp/shared_prefs/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp/log'
+    >>> 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.user_config_dir
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp'
+    >>> dirs.site_config_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.user_config_dir
+    '/Users/trentm/Library/Application Support/SuperApp/1.0'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp/1.0'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp/1.0'
+    >>> dirs.site_config_dir
+    '/Library/Application Support/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..09572f1780ad3554e93d8309547e9bc802a60371
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/RECORD
@@ -0,0 +1,15 @@
+platformdirs-4.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+platformdirs-4.4.0.dist-info/METADATA,sha256=u8UhbV9Md7-8VyJyZNUuZrzN5xzPeedeGmBG0CnTAiM,12831
+platformdirs-4.4.0.dist-info/RECORD,,
+platformdirs-4.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs-4.4.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
+platformdirs-4.4.0.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+platformdirs/__init__.py,sha256=iORRy6_lZ9tXLvO0W6fJPn8QV7F532ivl-f2WGmabBc,22284
+platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493
+platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013
+platformdirs/api.py,sha256=wPHOlwOsfz2oqQZ6A2FcCu5kEAj-JondzoNOHYFQ0h8,9281
+platformdirs/macos.py,sha256=0XoOgin1NK7Qki7iskD-oS8xKxw6bXgoKEgdqpCRAFQ,6322
+platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458
+platformdirs/version.py,sha256=i31fi3nNO19D2FdSx8aldD7IFLSqm2YrAo6SmkV0FLM,704
+platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.27.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f35fed9191b1142ddaada8a96de4a9461c5d796c
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs-4.4.0.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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..02daa5914a82da08293dc1675e75c11ed3fb2bd8
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__init__.py
@@ -0,0 +1,631 @@
+"""
+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
+
+if sys.platform == "win32":
+    from platformdirs.windows import Windows as _Result
+elif sys.platform == "darwin":
+    from platformdirs.macos import MacOS as _Result
+else:
+    from platformdirs.unix import Unix as _Result
+
+
+def _set_platform_dir_class() -> type[PlatformDirsABC]:
+    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
+
+
+if TYPE_CHECKING:
+    # Work around mypy issue: https://github.com/python/mypy/issues/10962
+    PlatformDirs = _Result
+else:
+    PlatformDirs = _set_platform_dir_class()  #: Currently active platform
+AppDirs = PlatformDirs  #: Backwards compatibility with appdirs
+
+
+def user_data_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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 | Literal[False] | None = 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__main__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..922c521358e349470ec48d6372b8f8ee8641128a
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..230db1563f82f4e599f3cb90e78d4a34a62b641e
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ff81c2d5efd80c96517c41a4bf57996774b6346
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/__main__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/android.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/android.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ffc4e513889697579c126b16acbb95b4371bcbc
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/android.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/api.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/api.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21e02023c6ff60506ef93206dcbaffa026d55fbc
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/api.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/macos.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/macos.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00b66974f156ad42ec92fe774868bc733e098d58
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/macos.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/unix.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/unix.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..290806770dc47cd12e5bfe837a97856b60881198
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/unix.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/version.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/version.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..010854d62580b961d72ee98c3bf1e785f1d5747d
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/version.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/windows.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/windows.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32a3644f3428bdea64eff0097b58a358aecb7a93
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/__pycache__/windows.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/android.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/android.py
new file mode 100644
index 0000000000000000000000000000000000000000..92efc852d3818b70a708ab61ba2b291eb5a6ee67
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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
+    """: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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/api.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..251600e6d1b6f7d38f6fee0b91de34d31b2124d0
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/api.py
@@ -0,0 +1,299 @@
+"""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 collections.abc import Iterator
+    from typing import Literal
+
+
+class PlatformDirsABC(ABC):  # noqa: PLR0904
+    """Abstract base class for platform directories."""
+
+    def __init__(  # noqa: PLR0913, PLR0917
+        self,
+        appname: str | None = None,
+        appauthor: str | Literal[False] | None = 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)
+
+    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.partition(os.pathsep)[0]
+        return Path(directory)
+
+    @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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/macos.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/macos.py
new file mode 100644
index 0000000000000000000000000000000000000000..30ab368913061aa4b7935e65f5696f7d8cffcf4f
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/macos.py
@@ -0,0 +1,146 @@
+"""macOS."""
+
+from __future__ import annotations
+
+import os.path
+import sys
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from pathlib import Path
+
+
+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. ``$homebrew_prefix/share/$appname/$version``.
+          If `multipath ` is enabled, and we're in Homebrew,
+          the response is a multi-path string separated by ":", e.g.
+          ``$homebrew_prefix/share/$appname/$version:/Library/Application Support/$appname/$version``
+        """
+        is_homebrew = "/opt/python" in sys.prefix
+        homebrew_prefix = sys.prefix.split("/opt/python")[0] if is_homebrew else ""
+        path_list = [self._append_app_name_and_version(f"{homebrew_prefix}/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 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 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. ``$homebrew_prefix/var/cache/$appname/$version``.
+          If `multipath ` is enabled, and we're in Homebrew,
+          the response is a multi-path string separated by ":", e.g.
+          ``$homebrew_prefix/var/cache/$appname/$version:/Library/Caches/$appname/$version``
+        """
+        is_homebrew = "/opt/python" in sys.prefix
+        homebrew_prefix = sys.prefix.split("/opt/python")[0] if is_homebrew else ""
+        path_list = [self._append_app_name_and_version(f"{homebrew_prefix}/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 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)
+
+    @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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/py.typed b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/unix.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/unix.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc75d8d0747b0d5ce84b96cfc37877a126d1a9b6
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/unix.py
@@ -0,0 +1,272 @@
+"""Unix."""
+
+from __future__ import annotations
+
+import os
+import sys
+from configparser import ConfigParser
+from pathlib import Path
+from typing import TYPE_CHECKING, NoReturn
+
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+
+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 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/version.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9451472c3c68e0d775e32c8b193bf93bf217107
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/version.py
@@ -0,0 +1,34 @@
+# file generated by setuptools-scm
+# don't change, don't track in version control
+
+__all__ = [
+    "__version__",
+    "__version_tuple__",
+    "version",
+    "version_tuple",
+    "__commit_id__",
+    "commit_id",
+]
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from typing import Tuple
+    from typing import Union
+
+    VERSION_TUPLE = Tuple[Union[int, str], ...]
+    COMMIT_ID = Union[str, None]
+else:
+    VERSION_TUPLE = object
+    COMMIT_ID = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+commit_id: COMMIT_ID
+__commit_id__: COMMIT_ID
+
+__version__ = version = '4.4.0'
+__version_tuple__ = version_tuple = (4, 4, 0)
+
+__commit_id__ = commit_id = None
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/windows.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/platformdirs/windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7bc96091a2b1cd078a0847519cb5dd50a5d8898
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..ffe8e40d77f07e829e420f056b7ecd9c81ec38a5
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/METADATA
@@ -0,0 +1,270 @@
+Metadata-Version: 2.4
+Name: tomli
+Version: 2.4.0
+Summary: A lil' TOML parser
+Keywords: toml
+Author-email: Taneli Hukkinen 
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+License-Expression: MIT
+Classifier: Operating System :: MacOS
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Typing :: Typed
+License-File: LICENSE
+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/actions/workflows/tests.yaml/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)
+  - [Building a `tomli`/`tomllib` compatibility layer](#building-a-tomlitomllib-compatibility-layer)
+- [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)
+  - [Pure Python](#pure-python)
+  - [Mypyc generated wheel](#mypyc-generated-wheel)
+
+
+
+## Intro
+
+Tomli is a Python library for parsing [TOML](https://toml.io).
+Version 2.4.0 and later are compatible with [TOML v1.1.0](https://toml.io/en/v1.1.0).
+Older versions are [TOML v1.0.0](https://toml.io/en/v1.0.0) compatible.
+
+A version of Tomli, the `tomllib` module,
+was added to the standard library in Python 3.11
+via [PEP 680](https://www.python.org/dev/peps/pep-0680/).
+Tomli continues to provide a backport on PyPI for Python versions
+where the standard library module is not available
+and that have not yet reached their end-of-life.
+
+Tomli uses [mypyc](https://github.com/mypyc/mypyc)
+to generate binary wheels for most of the widely used platforms,
+so Python 3.11+ users may prefer it over `tomllib` for improved performance.
+Pure Python wheels are available on any platform and should perform the same as `tomllib`.
+
+## Installation
+
+```bash
+pip install tomli
+```
+
+## Usage
+
+### Parse a TOML string
+
+```python
+import tomli
+
+toml_str = """
+[[players]]
+name = "Lehtinen"
+number = 26
+
+[[players]]
+name = "Numminen"
+number = 27
+"""
+
+toml_dict = tomli.loads(toml_str)
+assert toml_dict == {
+    "players": [{"name": "Lehtinen", "number": 26}, {"name": "Numminen", "number": 27}]
+}
+```
+
+### 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 isinstance(toml_dict["precision-matters"], 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.
+
+### Building a `tomli`/`tomllib` compatibility layer
+
+Python versions 3.11+ ship with a version of Tomli:
+the `tomllib` standard library module.
+To build code that uses the standard library if available,
+but still works seamlessly with Python 3.6+,
+do the following.
+
+Instead of a hard Tomli dependency, use the following
+[dependency specifier](https://packaging.python.org/en/latest/specifications/dependency-specifiers/)
+to only require Tomli when the standard library module is not available:
+
+```
+tomli >= 1.1.0 ; python_version < "3.11"
+```
+
+Then, in your code, import a TOML parser using the following fallback mechanism:
+
+```python
+import sys
+
+if sys.version_info >= (3, 11):
+    import tomllib
+else:
+    import tomli as tomllib
+
+tomllib.loads("['This parses fine with Python 3.6+']")
+```
+
+## FAQ
+
+### Why this parser?
+
+- it's lil'
+- pure Python with zero dependencies
+- the fastest pure Python parser [\*](#pure-python):
+  18x as fast as [tomlkit](https://pypi.org/project/tomlkit/),
+  2.1x 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
+  [toml-lang/toml-test](https://github.com/toml-lang/toml-test)
+  test suite
+- 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.
+
+Below are the results for commit [0724e2a](https://github.com/hukkin/tomli/tree/0724e2ab1858da7f5e05a9bffdb24c33589d951c).
+
+### Pure Python
+
+```console
+foo@bar:~/dev/tomli$ python --version
+Python 3.12.7
+foo@bar:~/dev/tomli$ pip freeze
+attrs==21.4.0
+click==8.1.7
+pytomlpp==1.0.13
+qtoml==0.3.1
+rtoml==0.11.0
+toml==0.10.2
+tomli @ file:///home/foo/dev/tomli
+tomlkit==0.13.2
+foo@bar:~/dev/tomli$ python benchmark/run.py
+Parsing data.toml 5000 times:
+------------------------------------------------------
+    parser |  exec time | performance (more is better)
+-----------+------------+-----------------------------
+     rtoml |    0.647 s | baseline (100%)
+  pytomlpp |    0.891 s | 72.62%
+     tomli |     3.14 s | 20.56%
+      toml |     6.69 s | 9.67%
+     qtoml |     8.27 s | 7.82%
+   tomlkit |     56.1 s | 1.15%
+```
+
+### Mypyc generated wheel
+
+```console
+foo@bar:~/dev/tomli$ python benchmark/run.py
+Parsing data.toml 5000 times:
+------------------------------------------------------
+    parser |  exec time | performance (more is better)
+-----------+------------+-----------------------------
+     rtoml |    0.668 s | baseline (100%)
+  pytomlpp |    0.893 s | 74.81%
+     tomli |     1.96 s | 34.18%
+      toml |     6.64 s | 10.07%
+     qtoml |     8.26 s | 8.09%
+   tomlkit |     52.9 s | 1.26%
+```
+
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..d2415a38de6198f1dad22ba1de542d15cd7065b3
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/RECORD
@@ -0,0 +1,11 @@
+tomli-2.4.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+tomli-2.4.0.dist-info/METADATA,sha256=9awKH4-6kItGRs1lUwnpGq2Wm2eHYWrFccpGKjgy_84,10567
+tomli-2.4.0.dist-info/RECORD,,
+tomli-2.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tomli-2.4.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+tomli-2.4.0.dist-info/licenses/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+tomli/__init__.py,sha256=ahtDjGJA2M_wWVvGpzx4YJtWxrWBx6qE-GH5-UYoECA,314
+tomli/_parser.py,sha256=txeATLE3zHyZ-ushXtYfrZ3LoIs7JzQF2W2KL1gwJPg,25958
+tomli/_re.py,sha256=oSNZ_ilFI6chEuQ01YRSoUydBQr_okF_mSdHTkFmv90,3396
+tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
+tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.12.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..e859590f886cd78344206af1a8ccb3080d4385e0
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli-2.4.0.dist-info/licenses/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..55699b1ea68247f72a382dc11cd2b5c4b07d24fd
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__init__.py
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+__all__ = ("loads", "load", "TOMLDecodeError")
+__version__ = "2.4.0"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
+
+from ._parser import TOMLDecodeError, load, loads
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74a0b00e31d4e76106d2626812e803712394ceed
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_parser.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_parser.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d1ee33094d2549055c887e6d1e8d1bb5ebacafc
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_parser.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_re.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_re.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b33fdb89ccd23f2290b5c76a6e609b8312ef647
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_re.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_types.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..977d6df26dcfe49b0ffc47fc6556ab25adddb127
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/__pycache__/_types.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/_parser.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..3038891afec8d4e6608ae4209365cf31f94b7f41
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/_parser.py
@@ -0,0 +1,782 @@
+# SPDX-License-Identifier: MIT
+# SPDX-FileCopyrightText: 2021 Taneli Hukkinen
+# Licensed to PSF under a Contributor Agreement.
+
+from __future__ import annotations
+
+import sys
+from types import MappingProxyType
+
+from ._re import (
+    RE_DATETIME,
+    RE_LOCALTIME,
+    RE_NUMBER,
+    match_to_datetime,
+    match_to_localtime,
+    match_to_number,
+)
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from collections.abc import Iterable
+    from typing import IO, Any, Final
+
+    from ._types import Key, ParseFloat, Pos
+
+# Inline tables/arrays are implemented using recursion. Pathologically
+# nested documents cause pure Python to raise RecursionError (which is OK),
+# but mypyc binary wheels will crash unrecoverably (not OK). According to
+# mypyc docs this will be fixed in the future:
+# https://mypyc.readthedocs.io/en/latest/differences_from_python.html#stack-overflows
+# Before mypyc's fix is in, recursion needs to be limited by this library.
+# Choosing `sys.getrecursionlimit()` as maximum inline table/array nesting
+# level, as it allows more nesting than pure Python, but still seems a far
+# lower number than where mypyc binaries crash.
+MAX_INLINE_NESTING: Final = sys.getrecursionlimit()
+
+ASCII_CTRL: Final = 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: Final = ASCII_CTRL - frozenset("\t")
+ILLEGAL_MULTILINE_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t\n")
+
+ILLEGAL_LITERAL_STR_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
+ILLEGAL_MULTILINE_LITERAL_STR_CHARS: Final = ILLEGAL_MULTILINE_BASIC_STR_CHARS
+
+ILLEGAL_COMMENT_CHARS: Final = ILLEGAL_BASIC_STR_CHARS
+
+TOML_WS: Final = frozenset(" \t")
+TOML_WS_AND_NEWLINE: Final = TOML_WS | frozenset("\n")
+BARE_KEY_CHARS: Final = frozenset(
+    "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "-_"
+)
+KEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset("\"'")
+HEXDIGIT_CHARS: Final = frozenset("abcdef" "ABCDEF" "0123456789")
+
+BASIC_STR_ESCAPE_REPLACEMENTS: Final = MappingProxyType(
+    {
+        "\\b": "\u0008",  # backspace
+        "\\t": "\u0009",  # tab
+        "\\n": "\u000a",  # linefeed
+        "\\f": "\u000c",  # form feed
+        "\\r": "\u000d",  # carriage return
+        "\\e": "\u001b",  # escape
+        '\\"': "\u0022",  # quote
+        "\\\\": "\u005c",  # backslash
+    }
+)
+
+
+class DEPRECATED_DEFAULT:
+    """Sentinel to be used as default arg during deprecation
+    period of TOMLDecodeError's free-form arguments."""
+
+
+class TOMLDecodeError(ValueError):
+    """An error raised if a document is not valid TOML.
+
+    Adds the following attributes to ValueError:
+    msg: The unformatted error message
+    doc: The TOML document being parsed
+    pos: The index of doc where parsing failed
+    lineno: The line corresponding to pos
+    colno: The column corresponding to pos
+    """
+
+    def __init__(
+        self,
+        msg: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
+        doc: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
+        pos: Pos | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,
+        *args: Any,
+    ):
+        if (
+            args
+            or not isinstance(msg, str)
+            or not isinstance(doc, str)
+            or not isinstance(pos, int)
+        ):
+            import warnings
+
+            warnings.warn(
+                "Free-form arguments for TOMLDecodeError are deprecated. "
+                "Please set 'msg' (str), 'doc' (str) and 'pos' (int) arguments only.",
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            if pos is not DEPRECATED_DEFAULT:
+                args = pos, *args
+            if doc is not DEPRECATED_DEFAULT:
+                args = doc, *args
+            if msg is not DEPRECATED_DEFAULT:
+                args = msg, *args
+            ValueError.__init__(self, *args)
+            return
+
+        lineno = doc.count("\n", 0, pos) + 1
+        if lineno == 1:
+            colno = pos + 1
+        else:
+            colno = pos - doc.rindex("\n", 0, pos)
+
+        if pos >= len(doc):
+            coord_repr = "end of document"
+        else:
+            coord_repr = f"line {lineno}, column {colno}"
+        errmsg = f"{msg} (at {coord_repr})"
+        ValueError.__init__(self, errmsg)
+
+        self.msg = msg
+        self.doc = doc
+        self.pos = pos
+        self.lineno = lineno
+        self.colno = colno
+
+
+def load(__fp: IO[bytes], *, 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]:
+    """Parse TOML from a string."""
+
+    # The spec allows converting "\r\n" to "\n", even in string
+    # literals. Let's do so to simplify parsing.
+    try:
+        src = __s.replace("\r\n", "\n")
+    except (AttributeError, TypeError):
+        raise TypeError(
+            f"Expected str object, not '{type(__s).__qualname__}'"
+        ) from None
+    pos = 0
+    out = Output()
+    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 TOMLDecodeError("Invalid statement", src, pos)
+
+        # 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 TOMLDecodeError(
+                "Expected newline or end of document after a statement", src, pos
+            )
+        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: Final = 0
+    # Marks a nest that has been explicitly created and can no longer
+    # be opened using the "[table]" syntax.
+    EXPLICIT_NEST: Final = 1
+
+    def __init__(self) -> None:
+        self._flags: dict[str, dict[Any, Any]] = {}
+        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:
+            inner_cont = cont[key_stem]
+            return flag in inner_cont["flags"] or flag in inner_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[str, Any]:
+        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  # type: ignore[no-any-return]
+
+    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:
+    def __init__(self) -> None:
+        self.data = NestedDict()
+        self.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 TOMLDecodeError(f"Expected {expect!r}", src, new_pos) from None
+
+    if not error_on.isdisjoint(src[pos:new_pos]):
+        while src[pos] not in error_on:
+            pos += 1
+        raise TOMLDecodeError(f"Found invalid character {src[pos]!r}", src, pos)
+    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 TOMLDecodeError(f"Cannot declare {key} twice", src, pos)
+    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)
+    try:
+        out.data.get_or_create_nest(key)
+    except KeyError:
+        raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
+
+    if not src.startswith("]", pos):
+        raise TOMLDecodeError(
+            "Expected ']' at the end of a table declaration", src, pos
+        )
+    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 TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)
+    # 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 TOMLDecodeError("Cannot overwrite a value", src, pos) from None
+
+    if not src.startswith("]]", pos):
+        raise TOMLDecodeError(
+            "Expected ']]' at the end of an array declaration", src, pos
+        )
+    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, nest_lvl=0)
+    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 TOMLDecodeError(f"Cannot redefine namespace {cont_key}", src, pos)
+        # 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 TOMLDecodeError(
+            f"Cannot mutate immutable namespace {abs_key_parent}", src, pos
+        )
+
+    try:
+        nest = out.data.get_or_create_nest(abs_key_parent)
+    except KeyError:
+        raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
+    if key_stem in nest:
+        raise TOMLDecodeError("Cannot overwrite a value", src, pos)
+    # 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, nest_lvl: int
+) -> tuple[Pos, Key, Any]:
+    pos, key = parse_key(src, pos)
+    try:
+        char: str | None = src[pos]
+    except IndexError:
+        char = None
+    if char != "=":
+        raise TOMLDecodeError("Expected '=' after a key in a key/value pair", src, pos)
+    pos += 1
+    pos = skip_chars(src, pos, TOML_WS)
+    pos, value = parse_value(src, pos, parse_float, nest_lvl)
+    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 TOMLDecodeError("Invalid initial character for a key part", src, pos)
+
+
+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, nest_lvl: int
+) -> tuple[Pos, list[Any]]:
+    pos += 1
+    array: list[Any] = []
+
+    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, nest_lvl)
+        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 TOMLDecodeError("Unclosed array", src, pos)
+        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, nest_lvl: int
+) -> tuple[Pos, dict[str, Any]]:
+    pos += 1
+    nested_dict = NestedDict()
+    flags = Flags()
+
+    pos = skip_comments_and_array_ws(src, pos)
+    if src.startswith("}", pos):
+        return pos + 1, nested_dict.dict
+    while True:
+        pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl)
+        key_parent, key_stem = key[:-1], key[-1]
+        if flags.is_(key, Flags.FROZEN):
+            raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)
+        try:
+            nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)
+        except KeyError:
+            raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None
+        if key_stem in nest:
+            raise TOMLDecodeError(f"Duplicate inline table key {key_stem!r}", src, pos)
+        nest[key_stem] = value
+        pos = skip_comments_and_array_ws(src, pos)
+        c = src[pos : pos + 1]
+        if c == "}":
+            return pos + 1, nested_dict.dict
+        if c != ",":
+            raise TOMLDecodeError("Unclosed inline table", src, pos)
+        pos += 1
+        pos = skip_comments_and_array_ws(src, pos)
+        if src.startswith("}", pos):
+            return pos + 1, nested_dict.dict
+        if isinstance(value, (dict, list)):
+            flags.set(key, Flags.FROZEN, recursive=True)
+
+
+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 TOMLDecodeError("Unescaped '\\' in a string", src, pos)
+            pos += 1
+        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)
+        return pos, ""
+    if escape_id == "\\x":
+        return parse_hex_char(src, pos, 2)
+    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 TOMLDecodeError("Unescaped '\\' in a string", src, pos) 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 TOMLDecodeError("Invalid hex value", src, pos)
+    pos += hex_len
+    hex_int = int(hex_str, 16)
+    if not is_unicode_scalar_value(hex_int):
+        raise TOMLDecodeError(
+            "Escaped character is not a Unicode scalar value", src, pos
+        )
+    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 TOMLDecodeError("Unterminated string", src, pos) 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 TOMLDecodeError(f"Illegal character {char!r}", src, pos)
+        pos += 1
+
+
+def parse_value(
+    src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int
+) -> tuple[Pos, Any]:
+    if nest_lvl > MAX_INLINE_NESTING:
+        # Pure Python should have raised RecursionError already.
+        # This ensures mypyc binaries eventually do the same.
+        raise RecursionError(  # pragma: no cover
+            "TOML inline arrays/tables are nested more than the allowed"
+            f" {MAX_INLINE_NESTING} levels"
+        )
+
+    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, nest_lvl + 1)
+
+    # Inline tables
+    if char == "{":
+        return parse_inline_table(src, pos, parse_float, nest_lvl + 1)
+
+    # 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 TOMLDecodeError("Invalid date or datetime", src, pos) 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 TOMLDecodeError("Invalid value", 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:
+        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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/_re.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/_re.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc374ed63d3e3742a97134349fc25b14223ab57b
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/_re.py
@@ -0,0 +1,119 @@
+# 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
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from typing import Any, Final
+
+    from ._types import ParseFloat
+
+_TIME_RE_STR: Final = r"""
+([01][0-9]|2[0-3])             # hours
+:([0-5][0-9])                  # minutes
+(?:
+    :([0-5][0-9])              # optional seconds
+    (?:\.([0-9]{1,6})[0-9]*)?  # optional fractions of a second
+)?
+"""
+
+RE_NUMBER: Final = 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: Final = re.compile(_TIME_RE_STR, flags=re.VERBOSE)
+RE_DATETIME: Final = 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[str]) -> 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 = int(hour_str), int(minute_str)
+    sec = int(sec_str) if sec_str else 0
+    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)
+
+
+# No need to limit cache size. This is only ever called on input
+# that matched RE_DATETIME, so there is an implicit bound of
+# 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.
+@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[str]) -> time:
+    hour_str, minute_str, sec_str, micros_str = match.groups()
+    sec = int(sec_str) if sec_str else 0
+    micros = int(micros_str.ljust(6, "0")) if micros_str else 0
+    return time(int(hour_str), int(minute_str), sec, micros)
+
+
+def match_to_number(match: re.Match[str], parse_float: ParseFloat) -> Any:
+    if match.group("floatpart"):
+        return parse_float(match.group())
+    return int(match.group(), 0)
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/_types.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..d949412e03b29d70592c7721fe747e5085c2e280
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/py.typed b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..7632ecf77545c5e5501cb3fc5719df0761104ca2
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/tomli/py.typed
@@ -0,0 +1 @@
+# Marker file for PEP 561
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..77936a9eb631d1aad5a9a9d12ce825c97392943e
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/METADATA
@@ -0,0 +1,69 @@
+Metadata-Version: 2.4
+Name: wheel
+Version: 0.46.3
+Summary: Command line tool for manipulating wheel files
+Keywords: wheel,packaging
+Author-email: Daniel Holth 
+Maintainer-email: Alex Grönholm 
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-Expression: MIT
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Topic :: System :: Archiving :: Packaging
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+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 :: 3.14
+License-File: LICENSE.txt
+Requires-Dist: packaging >= 24.0
+Requires-Dist: pytest >= 6.0.0 ; extra == "test"
+Requires-Dist: setuptools >= 77 ; 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..5890933bcb85e7a1f5bca660d3aa311b71884e5d
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/RECORD
@@ -0,0 +1,22 @@
+bin/wheel,sha256=OLjFs9G7MQ-f_mhuW2aLGpngsyphW_v5FIoyN88Hfk0,339
+wheel-0.46.3.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+wheel-0.46.3.dist-info/METADATA,sha256=IpEKqXyonLzCCgGeJ_4xNgt5KaS9ZsoNMQ-ZpE9szTU,2410
+wheel-0.46.3.dist-info/RECORD,,
+wheel-0.46.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+wheel-0.46.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+wheel-0.46.3.dist-info/entry_points.txt,sha256=JJdtSAGTvMLbIkTVZUAMvGKO39FtWfCVF8mp_NH6e4g,110
+wheel-0.46.3.dist-info/licenses/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107
+wheel/__init__.py,sha256=UweKvhe4SyP7zFyDoYo8BOuwTA6q3-_WpMmY2NNO54c,59
+wheel/__main__.py,sha256=_83wl9tyGU2cHiqfudpubGHdRL5uonPXnzeznznkxzs,512
+wheel/_bdist_wheel.py,sha256=bpmNa7_s-CYFkVgXf9ENAYTiJ01XBhRW4pxH1T8XYsI,21729
+wheel/_commands/__init__.py,sha256=fCRAQZNDyj2JLrufdgPsBlaRS_t_j_aBUMpXj09KZ4E,4432
+wheel/_commands/convert.py,sha256=0wSJMU0m-6LY16Om8Wmmloy-hJWFZeOmI8hT-2Z7Qms,12743
+wheel/_commands/pack.py,sha256=o3iwjfRHl7N9ul-M2kHbewLJZnqBLAWf0tzUCwoiTMw,3078
+wheel/_commands/tags.py,sha256=Rv2ySVb8-qX3osKp3uJgxcIMXkjt43XUD0-zvC6KvnY,4775
+wheel/_commands/unpack.py,sha256=AjDSS23XYyCSFfifnMutinrpPv-DK_2wbNHkKAUFwgM,1016
+wheel/_metadata.py,sha256=BP5jC9uC1hyicp7nL4FJ2LYixNFpEJIV_uMDY1KBZBg,6188
+wheel/_setuptools_logging.py,sha256=-5KC-lne0ilOUWIDfOkqapUWGMFZhuKYDIavIZiB5kM,781
+wheel/bdist_wheel.py,sha256=HrzYiSzMkh5ohAAhlQnYBS1p8qbr85X6F59xqxd9kBg,1102
+wheel/macosx_libfile.py,sha256=pL0wm88jRMl_4ASgGlNg_mz69Zmv5xm8JSkjLdwyvIQ,16712
+wheel/metadata.py,sha256=GknOO7JJiZMlcEe_fiD7nqnDTTLd0sX_-IgipM4L3-4,757
+wheel/wheelfile.py,sha256=m_g_7TNsEp-j-xnvSr5yDLEFb1nhyObueq9Q5_1_lBA,8720
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.12.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..dcebd58811da1ee2758dd0f45c575704afdd61bd
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/entry_points.txt
@@ -0,0 +1,6 @@
+[console_scripts]
+wheel=wheel._commands:main
+
+[distutils.commands]
+bdist_wheel=wheel.bdist_wheel:bdist_wheel
+
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/licenses/LICENSE.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/licenses/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a31470f14c5978d5fcc3bc173b8399b6c9a6443f
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel-0.46.3.dist-info/licenses/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5b076f05a69ac941356361db47159d6cc06c296
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__init__.py
@@ -0,0 +1,3 @@
+from __future__ import annotations
+
+__version__ = "0.46.3"
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__main__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c7de5fb7fd2fcc1bbb60b5c3977e82c3aa2f898
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__main__.py
@@ -0,0 +1,25 @@
+"""
+Wheel command line tool (enables the ``python -m wheel`` syntax)
+"""
+
+from __future__ import annotations
+
+import sys
+from typing import NoReturn
+
+
+def main() -> NoReturn:  # 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]
+
+    from ._commands import main as cli_main
+
+    sys.exit(cli_main())
+
+
+if __name__ == "__main__":
+    main()
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ec1e2c67c4f618c6d97603df1de7a34cf8be27f
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/__main__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/__main__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8db65fc435268d115866fb17c090982b03adb42
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/__main__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc9956971249fcd93795f8ed802a960f9449c2ac
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_bdist_wheel.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_metadata.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_metadata.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..135e556399ff5d14cbcd3b0885e79cca3937cc33
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_metadata.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2fba0f1f21ebc217ccf9a8385417e8d69389405
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/_setuptools_logging.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..858b38978fddb1c16562a6acdab5d4a6c08d29fa
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/bdist_wheel.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e025e54c2397d88f4b0ed9f1f5f6c9f7a1f10c7
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/macosx_libfile.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/metadata.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/metadata.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eda4d5b2dcf177eba163e0cd81c2428e082b1b7a
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/metadata.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3410f487a1e98860dacb6eb8370b2470e7c4fd81
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/__pycache__/wheelfile.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..575fbfb35105eb82faee5a368781ecf818379354
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_bdist_wheel.py
@@ -0,0 +1,616 @@
+"""
+Create a wheel (.whl) distribution.
+
+A wheel is a built archive format.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+import shutil
+import stat
+import struct
+import sys
+import sysconfig
+import warnings
+from collections.abc import Iterable, Sequence
+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, Literal, cast
+from zipfile import ZIP_DEFLATED, ZIP_STORED
+
+import setuptools
+from packaging import tags
+from packaging import version as _packaging_version
+from setuptools import Command
+
+from . import __version__ as wheel_version
+from ._metadata import pkginfo_to_metadata
+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()
+
+log = logging.getLogger("wheel")
+
+
+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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..42f1d7ef309663498fd2b4d691aa71e14be34e63
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__init__.py
@@ -0,0 +1,153 @@
+"""
+Wheel command-line utility.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+from argparse import ArgumentTypeError
+
+from ..wheelfile import WheelError
+
+
+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() -> argparse.ArgumentParser:
+    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() -> int:
+    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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ed3d056d8e27a90539f80ccee192f8c9904f3ff
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/convert.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/convert.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0468ea4d644a05605abcdfd411413ab1dba50a5e
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/convert.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/pack.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/pack.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44a8edf1bf2946bf3a09e92fda66f7f0136c71be
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/pack.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/tags.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/tags.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aec105e1c458faaf1e2b59dc59d8f283b8bf690a
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/tags.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/unpack.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/unpack.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd5cc359925b594c2b951f9381e835c184a1fa1e
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/__pycache__/unpack.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/convert.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..cafd12c86cbc0a661e69b9243ec5525a95274c9e
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/convert.py
@@ -0,0 +1,337 @@
+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 packaging.tags import parse_tag
+
+from .. import __version__
+from .._metadata import generate_requirements
+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) -> None:
+    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()
+            if description_lines:
+                value = "\n".join(
+                    (
+                        description_lines[0].lstrip(),
+                        dedent("\n".join(description_lines[1:])),
+                        "\n",
+                    )
+                )
+            else:
+                value = "\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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/pack.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/pack.py
new file mode 100644
index 0000000000000000000000000000000000000000..1321ce9308a68f00cf2f839d4ba02869c16ec26f
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/pack.py
@@ -0,0 +1,84 @@
+from __future__ import annotations
+
+import email.policy
+import os.path
+import re
+from email.generator import BytesGenerator
+from email.parser import BytesParser
+
+from ..wheelfile import WheelError, 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/tags.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..cec896b55b726d29a53f10e06d06b79e645b2e94
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/tags.py
@@ -0,0 +1,140 @@
+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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/unpack.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/unpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..83dc7423f8171a3b6ffd6641475af037b7c59495
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_commands/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:
+            target_path = Path(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
+            target_path.chmod(permissions)
+
+    print("OK")
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_metadata.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..e17a7b924526b9fcad83fc44996f17695dea0161
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_metadata.py
@@ -0,0 +1,184 @@
+"""
+Tools for converting old- to new-style metadata.
+"""
+
+from __future__ import annotations
+
+import functools
+import itertools
+import os.path
+import re
+import textwrap
+from collections.abc import Generator, Iterable, Iterator
+from email.message import Message
+from email.parser import Parser
+from typing import Literal
+
+from 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_setuptools_logging.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/_setuptools_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1a2482ba29ac5290c8f7d7688452ec3faf59332
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/bdist_wheel.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/bdist_wheel.py
new file mode 100644
index 0000000000000000000000000000000000000000..24199c246d44a6874ad991c2f3492ca30fc10f27
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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.",
+    FutureWarning,
+    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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/macosx_libfile.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/macosx_libfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..06e51af299d0fe15f7618f803cfb8ff52d199cf7
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/macosx_libfile.py
@@ -0,0 +1,486 @@
+"""
+IMPORTANT: DO NOT IMPORT THIS MODULE DIRECTLY.
+THIS IS ONLY KEPT IN PLACE FOR BACKWARDS COMPATIBILITY WITH
+setuptools.command.bdist_wheel.
+
+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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/metadata.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..e27900a2565c859ff32b0e4bf497c2548e4912de
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/metadata.py
@@ -0,0 +1,17 @@
+from warnings import warn
+
+from ._metadata import convert_requirements as convert_requirements
+from ._metadata import generate_requirements as generate_requirements
+from ._metadata import pkginfo_to_metadata as pkginfo_to_metadata
+from ._metadata import requires_to_requires_dist as requires_to_requires_dist
+from ._metadata import safe_extra as safe_extra
+from ._metadata import safe_name as safe_name
+from ._metadata import split_sections as split_sections
+
+warn(
+    f"The {__name__!r} package has been made private and should no longer be imported. "
+    f"Please either copy the code or find an alternative library to import it from, as "
+    f"this warning will be removed in a future version of 'wheel'.",
+    DeprecationWarning,
+    stacklevel=2,
+)
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/wheelfile.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/wheelfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b6fd71621b9a14274a17086edeb287db58d7fe0
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/wheel/wheelfile.py
@@ -0,0 +1,241 @@
+from __future__ import annotations
+
+__all__ = ["WHEEL_INFO_RE", "WheelFile", "WheelError"]
+
+import base64
+import csv
+import hashlib
+import logging
+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
+
+if TYPE_CHECKING:
+    from _typeshed import SizedBuffer, StrPath
+
+
+# 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
+
+log = logging.getLogger("wheel")
+
+
+class WheelError(Exception):
+    pass
+
+
+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)
+
+
+def get_zipinfo_datetime(
+    timestamp: float | None = None,
+) -> tuple[int, int, int, int, int]:
+    # 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) -> None:
+        log.info("creating %r and adding %r to it", self.filename, base_dir)
+        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,
+    ) -> 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("adding %r", 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) -> None:
+        # 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/INSTALLER b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+uv
\ No newline at end of file
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/METADATA b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..6420117987041c052142deea6b16884cdb435c2f
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/METADATA
@@ -0,0 +1,106 @@
+Metadata-Version: 2.4
+Name: zipp
+Version: 3.23.0
+Summary: Backport of pathlib-compatible object wrapper for zip files
+Author-email: "Jason R. Coombs" 
+License-Expression: MIT
+Project-URL: Source, https://github.com/jaraco/zipp
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+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: 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"
+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: 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: enabler
+Requires-Dist: pytest-enabler>=2.2; extra == "enabler"
+Provides-Extra: type
+Requires-Dist: pytest-mypy; extra == "type"
+Dynamic: license-file
+
+.. 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/astral-sh/ruff/main/assets/badge/v2.json
+    :target: https://github.com/astral-sh/ruff
+    :alt: Ruff
+
+.. image:: https://readthedocs.org/projects/zipp/badge/?version=latest
+..    :target: https://zipp.readthedocs.io/en/latest/?badge=latest
+
+.. image:: https://img.shields.io/badge/skeleton-2025-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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/RECORD b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..167e234a530053b60d4bf6d51b12598723433a8c
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/RECORD
@@ -0,0 +1,14 @@
+zipp-3.23.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
+zipp-3.23.0.dist-info/METADATA,sha256=vdZ9TRbPC_O4k-fRjNPS13StuC837Zhbx3cMYHIms1s,3563
+zipp-3.23.0.dist-info/RECORD,,
+zipp-3.23.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+zipp-3.23.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+zipp-3.23.0.dist-info/licenses/LICENSE,sha256=WlfLTbheKi3YjCkGKJCK3VfjRRRJ4KmnH9-zh3b9dZ0,1076
+zipp-3.23.0.dist-info/top_level.txt,sha256=iAbdoSHfaGqBfVb2XuR9JqSQHCoOsOtG6y9C_LSpqFw,5
+zipp/__init__.py,sha256=ieXh9GIMdABjKRX_JUJtP9k5wdBLK4Mt5X4nszSkmYE,11976
+zipp/_functools.py,sha256=f6Kt9LxZ4TE-cY1lJVdXSId3memSXmH9IdgMbU-_x2k,575
+zipp/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+zipp/compat/overlay.py,sha256=oEIGAnbr8yGjuKTrVSO2ByewPui71uppbX18BLnYTKE,783
+zipp/compat/py310.py,sha256=S7i6N9mToEn3asNb2ILyjnzvITOXrATD_J4emjyBbDU,256
+zipp/compat/py313.py,sha256=RndvDNtuY7H2D9ecnnzcPBMZ8mZc42gmXD_IwQAXXAE,654
+zipp/glob.py,sha256=DLV9LBsDxA6YVW82e3-tkoNrus1h4R-j3BR6VqS0AzE,3382
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/REQUESTED b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/WHEEL b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSE b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f60bd572013c6abcb3a82ba9b50d84935de6394f
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/licenses/LICENSE
@@ -0,0 +1,18 @@
+MIT License
+
+Copyright (c) 2025 
+
+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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/top_level.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e82f676f82a3381fa909d1e6578c7a22044fafca
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp-3.23.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+zipp
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed5b21463295b8cee93d855316fb5e9000f9b8ec
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__init__.py
@@ -0,0 +1,456 @@
+"""
+A Path-like interface for zipfiles.
+
+This codebase is shared between zipfile.Path in the stdlib
+and zipp in PyPI. See
+https://github.com/python/importlib_metadata/wiki/Development-Methodology
+for more detail.
+"""
+
+import functools
+import io
+import itertools
+import pathlib
+import posixpath
+import re
+import stat
+import sys
+import zipfile
+
+from ._functools import save_method_args
+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(''))
+    []
+
+    Multiple separators are treated like a single.
+
+    >>> list(_ancestry('//b//d///f//'))
+    ['//b//d///f', '//b//d', '//b']
+    """
+    path = path.rstrip(posixpath.sep)
+    while path.rstrip(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.
+    """
+
+    @save_method_args
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+
+    def __getstate__(self):
+        return self._saved___init__.args, self._saved___init__.kwargs
+
+    def __setstate__(self, state):
+        args, kwargs = state
+        super().__init__(*args, **kwargs)
+
+
+class CompleteDirs(InitializedState, 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):
+        return self._namelist
+
+    @functools.cached_property
+    def _namelist(self):
+        return super().namelist()
+
+    def _name_set(self):
+        return self._name_set_prop
+
+    @functools.cached_property
+    def _name_set_prop(self):
+        return super()._name_set()
+
+
+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'
+    # PyPy no longer special cased after 7.3.19 (or maybe 7.3.18)
+    # See jaraco/zipp#143
+    is_old_pypi = is_pypy and sys.pypy_version_info < (7, 3, 19)
+    stack_level = 3 + is_old_pypi
+    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 zip_mode == 'r' and not self.exists():
+            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) if self.at else self.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
+        return map(self._next, filter(matches, self.root.namelist()))
+
+    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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83bf5e8b8e481a3a35a9b4b368a8df1b8922d051
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/_functools.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/_functools.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f9ec53c33f9e5d193046bd47a7cc922ecf0ff95
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/_functools.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/glob.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/glob.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ebfe7967730e0a3c9cc0e73ca8a4d8411b1374b3
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/__pycache__/glob.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/_functools.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/_functools.py
new file mode 100644
index 0000000000000000000000000000000000000000..7390be21873e4ba439bde0553e4c0dcde8eb7d74
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/_functools.py
@@ -0,0 +1,20 @@
+import collections
+import functools
+
+
+# from jaraco.functools 4.0.2
+def save_method_args(method):
+    """
+    Wrap a method such that when it is called, the args and kwargs are
+    saved on the method.
+    """
+    args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')  # noqa: PYI024
+
+    @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
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6df654161479a20601317dd94a1771c4a314b60c
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/overlay.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/overlay.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d5823a1bb5fc751579eed725ee55e0de3512dee
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/overlay.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a737b2d6a413c2714665dd2ba41b74377582ddbb
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py310.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py313.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py313.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d97b31c3809aec086afb0f95680c0ce411ef9d70
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/__pycache__/py313.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/overlay.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/overlay.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a97ee7cd8b98f3a5487c0a0b0a80ffde5ff4dfd
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/overlay.py
@@ -0,0 +1,37 @@
+"""
+Expose zipp.Path as .zipfile.Path.
+
+Includes everything else in ``zipfile`` to match future usage. Just
+use:
+
+>>> from zipp.compat.overlay import zipfile
+
+in place of ``import zipfile``.
+
+Relative imports are supported too.
+
+>>> from zipp.compat.overlay.zipfile import ZipInfo
+
+The ``zipfile`` object added to ``sys.modules`` needs to be
+hashable (#126).
+
+>>> _ = hash(sys.modules['zipp.compat.overlay.zipfile'])
+"""
+
+import importlib
+import sys
+import types
+
+import zipp
+
+
+class HashableNamespace(types.SimpleNamespace):
+    def __hash__(self):
+        return hash(tuple(vars(self)))
+
+
+zipfile = HashableNamespace(**vars(importlib.import_module('zipfile')))
+zipfile.Path = zipp.Path
+zipfile._path = zipp
+
+sys.modules[__name__ + '.zipfile'] = zipfile  # type: ignore[assignment]
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/py310.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/py310.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1e7ec229062b8556cdd85f530d1ff301b2e6845
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/py310.py
@@ -0,0 +1,13 @@
+import io
+import sys
+
+
+def _text_encoding(encoding, stacklevel=2, /):  # pragma: no cover
+    return encoding
+
+
+text_encoding = (
+    io.text_encoding  # type: ignore[unused-ignore, attr-defined]
+    if sys.version_info > (3, 10)
+    else _text_encoding
+)
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/py313.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/py313.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae458690553f92107ce296adf4bb49add8e78250
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/compat/py313.py
@@ -0,0 +1,34 @@
+import functools
+import sys
+
+
+# from jaraco.functools 4.1
+def identity(x):
+    return x
+
+
+# from jaraco.functools 4.1
+def apply(transform):
+    def wrap(func):
+        return functools.wraps(func)(compose(transform, func))
+
+    return wrap
+
+
+# from jaraco.functools 4.1
+def compose(*funcs):
+    def compose_two(f1, f2):
+        return lambda *args, **kwargs: f1(f2(*args, **kwargs))
+
+    return functools.reduce(compose_two, funcs)
+
+
+def replace(pattern):
+    r"""
+    >>> replace(r'foo\z')
+    'foo\\Z'
+    """
+    return pattern[:-2] + pattern[-2:].replace(r'\z', r'\Z')
+
+
+legacy_end_marker = apply(replace) if sys.version_info < (3, 14) else identity
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/glob.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/glob.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b4ffb33187b65b4378925c472071c845bcecc26
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/_vendor/zipp/glob.py
@@ -0,0 +1,116 @@
+import os
+import re
+
+from .compat.py313 import legacy_end_marker
+
+_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.match_dirs(self.translate_core(pattern)))
+
+    @legacy_end_marker
+    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 match_dirs(self, pattern):
+        """
+        Ensure that zipfile.Path directory names are matched.
+
+        zipfile.Path directory names always end in a slash.
+        """
+        return rf'{pattern}[/]?'
+
+    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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py
new file mode 100644
index 0000000000000000000000000000000000000000..c69368a83ff1bdb89cf4853e00429f0125ca3dce
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb70bfb7115a2a94a8b942b31cafc3a550f0c005
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fddc9e8fb4861218f9a22dfe7ff2e70b77b7160
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/contexts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/contexts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a78bb08d4262aba06ed28ca4a10ef7ed9f43ba73
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/contexts.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/environment.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/environment.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d3e28b9953d09faa8df1262c1b78f3548fca6754
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/environment.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/fixtures.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/fixtures.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0b022b4d72439d71fed00e159193a3844378dd0
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/fixtures.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f28af3e1f143420d6920fe120d77225c0cf9568
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/namespaces.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/namespaces.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6742e6939551fc3d1dffab43761d8fba75daa0f2
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/namespaces.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c62457b17490ee95c898eef64ee53b60c4d7166a
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5dc674aa011b2d500e4599574843bdafbea8d56
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23948574f40a1926019864bd879c154bc97a6df9
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_deprecations.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36b655f6059adb9b1e9f3276e68f64187df18e27
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_egg.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f5850ada3361e753f275ed68a6162e68bc0ede1
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cab0671246da3bc89e272e7c5ef1b42aab5ff174
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffca566a0df1048d7d25c359562c5c0745ce9935
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_clib.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..376ae2f5347715a808eda5039cacbf99bd574923
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..869b5578e7cd609658824ed43633ce79299303d6
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_meta.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6758a4471b28573d66ca6c774141328c0ee0b8a8
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e50f18379bc335dd9d7f95180b4e175763c92d3d
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_config_discovery.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..805e95a90c46785d354c7da86090eb1ee8684907
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_depends.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_depends.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..efeb93ce06408049a06e44f8bc26f8353cf36df1
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_depends.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_develop.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_develop.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c3e469d5c4c7970496e79b3333a7bc4b81b23b8
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_develop.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_dist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_dist.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dab0f9d1820b027970148af073ec5c80a6677245
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_dist.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60a1622886e4bd7f9d30361b02e71b2fc7912324
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_dist_info.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e4a28feb3216de449dbaf7af90cee5b170bb0bf
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_distutils_adoption.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2c7a2b707dcb1203af18899d7cd734c0618a498
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_editable_install.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59a56c9e85f8fcf3baf22c9d7366c574d1afa209
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_egg_info.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_extern.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_extern.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aca5c283213fb5ec15069971044fa7b063363920
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_extern.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bfdc1bceaf6d0ee179e788988b8e9d809f0a59b5
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_find_packages.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60ab8319a9b13b98a7d01524187c483bfb0514b7
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_find_py_modules.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_glob.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_glob.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a83579278c0f7fdbd9b7abd2928f38dfcc1aa3c
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_glob.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..faabd604a1f6b4fa7f700a625d3f70637f3f7e0a
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_logging.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_logging.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2366241c500c2fa8e8076284ec64916b848a1f4a
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_logging.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..934c59910e9c042fa9ef8864b411090c6ea88959
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5073350f9e3a44b614a9f9741794cb850e879644
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_scripts.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_scripts.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e32a92f024520e16aec1f9c79596f93c4eccacb9
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_scripts.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c7a8d3f8f20de95916c74beef219b3da7ca2ada
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_sdist.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79afcf2ff511f1a661ec65713cb8fad021a7cb24
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_setopt.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e9839c7b309092cd6dd8f75d26b8e64b46c8589
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_setuptools.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9618e72dcdfcb52a156e40c14049fcdfb3b190d4
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_shutil_wrapper.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50fc659b824d95256aed3e263957bd013d579d82
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_unicode_utils.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3c167c93f79687e1169deba03f8b5b89f4b8eea
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f9f314c156fc676c8281fe6db11a0ff2cffde8f
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_warnings.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ebef3ecbb062c013239334e9efde3f4051f5c810
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f488f4d6f4f8d089792c3cb1362bd07cb1f69cb2
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/test_windows_wrappers.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/text.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/text.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c105bcf1d163c66c9f62c48037fcfa42e5830f36
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/text.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/textwrap.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/textwrap.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53566469d616292b268e5d2d3c91f64730a7be8b
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/__pycache__/textwrap.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71311449af0e1ca6865dffd1e906bf352d5d9ef6
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cda1986792efaead03fb702302726ae62fb33c2f
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/__pycache__/py39.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/py39.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/compat/py39.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fdb9dac1fa3f121a634082515d1a305fc09793c
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44c689f90314a2316bae61e7445c7a9dcaaf375e
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31b048e1995e3e0bd9cbb5ece58d37543941ddcb
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_apply_pyprojecttoml.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..036acd442123ce7531608dd9d026347f350f311f
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24a689e4d8ea5776b412cdb050ff4906fd76abe3
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3bc1e432c7bac3251778f954ce2cc9e6eb89056
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_setupcfg.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_setupcfg.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71d705dfa97f4dbdf433335ace3352df1ba266a2
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/__pycache__/test_setupcfg.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00a16423f448e7773f5e6dc9b365efe80f40a778
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f92a23b060addbf0aefb127576ef9d25cab633b5
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/__pycache__/__init__.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/__pycache__/preload.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/__pycache__/preload.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa65c4e3af971b0e9583ea97eaff9164aa04a70d
Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/__pycache__/preload.cpython-311.pyc differ
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/preload.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/downloads/preload.py
new file mode 100644
index 0000000000000000000000000000000000000000..8eeb5dd75d3dcb375cee5acaf11ad385084bff5a
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/setupcfg_examples.txt b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/setupcfg_examples.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6aab887ff1fe631d97f1abea90a8448040746a12
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f48c4316d9e9c3d09fe2abda9bd4aab63d90355
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_apply_pyprojecttoml.py
@@ -0,0 +1,774 @@
+"""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.IGNORECASE) 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 = "ankit@example.com"},
+]
+"""
+
+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,
+            'Ankit Ahlawat <अंकित@उदाहरण.भारत>',
+            marks=pytest.mark.xfail(
+                reason="CPython's `email.headerregistry.Address` only supports "
+                'RFC 5322, as of Oct 20, 2025 and latest Python 3.13.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.DOTALL)
+        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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_expand.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_expand.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5710ec63d7d9d4ed7b709203bb2fc4b512f2093
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_pyprojecttoml.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_pyprojecttoml.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d995d23af12b4f103dbb310635d14687ab1a0be
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_pyprojecttoml.py
@@ -0,0 +1,398 @@
+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.DOTALL)):
+            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.MULTILINE | re.DOTALL
+    )
+    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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fc8050743c4b1a8497d5ea20c571b565d074e59
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_pyprojecttoml_dynamic_deps.py
@@ -0,0 +1,111 @@
+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"
+
+    dist = Distribution({"extras_require": {"hello": ["world"]}})
+
+    with pytest.warns(SetuptoolsWarning, match=".extras_require. overwritten"):
+        dist = apply_configuration(dist, pyproject)
+
+    assert dist.extras_require == {"docs": ["sphinx"]}
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_setupcfg.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_setupcfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..495337a9a5815e3d2a0aefa584b8ee81f5136d95
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/config/test_setupcfg.py
@@ -0,0 +1,987 @@
+import configparser
+import contextlib
+import inspect
+import re
+import sys
+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
+
+IS_PYPY = '__pypy__' in sys.builtin_module_names
+
+
+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",
+        ],
+    )
+    @pytest.mark.xfail(IS_PYPY, reason="Exceptions missing on PyPy")
+    # TODO: investigate PyPy problem
+    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",
+        ],
+    )
+    @pytest.mark.xfail(IS_PYPY, reason="Warnings missing on PyPy (minor issue)")
+    # TODO: investigate PyPy problem
+    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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/indexes/test_links_priority/external.html b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/indexes/test_links_priority/external.html
new file mode 100644
index 0000000000000000000000000000000000000000..92e4702f634dfb37a404bec3103b76f6afcaa917
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/indexes/test_links_priority/external.html
@@ -0,0 +1,3 @@
+
+bad old link
+
diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..fefb028bd3ee7d45a414d6e96a7b2a21ffd7eda7
--- /dev/null
+++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..272e2a3d015cc115f246b226a5b4c0dec5ef9f5b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fbbb8cbec2c249f6c5d7aff058c9fc6a6d45484 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/test_pbr.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/test_pbr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59c0e63d1b52266359ed654892d4915bd925a1ad Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/test_pbr.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a78a23a6157cbcc106fb54eba24f267201a782d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/helpers.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..16b13022913f62ba86df6b2480d22e3119cdb8cc --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/helpers.py @@ -0,0 +1,80 @@ +"""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. +""" + +from __future__ import annotations + +import os +import subprocess +import tarfile +from collections.abc import Iterator +from pathlib import Path +from zipfile import ZipFile, ZipInfo + + +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) -> None: + self._filename = filename + if filename.endswith("tar.gz"): + self._obj: tarfile.TarFile | ZipFile = 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) -> Iterator[ZipInfo] | Iterator[tarfile.TarInfo]: + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/test_pbr.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/test_pbr.py new file mode 100644 index 0000000000000000000000000000000000000000..f89e5b8b2151430d0994836dd609f1b75490a336 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/test_pbr.py @@ -0,0 +1,20 @@ +import subprocess + +import pytest + + +@pytest.mark.uses_network +def test_pbr_integration(pbr_package, venv): + """Ensure pbr packages install.""" + cmd = [ + 'python', + '-m', + 'pip', + '-v', + 'install', + '--no-build-isolation', + pbr_package, + ] + venv.run(cmd, stderr=subprocess.STDOUT) + out = venv.run(["python", "-c", "import mypkg.hello"]) + assert "Hello world!" in out diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/test_pip_install_sdist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/integration/test_pip_install_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..4e84f218323e6ad67adfbce07cea5a16e91a311c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_bdist_deprecations.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_bdist_deprecations.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d67b06161a2b36e7b15fab09f797c5c15575c2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_bdist_wheel.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_bdist_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..68cc0c4d3662bcf6f0881df54105ebaf38403564 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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) -> None: + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build.py new file mode 100644 index 0000000000000000000000000000000000000000..f0f1d9dcf21bafe9dc82a76d373b366ddeecfcec --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_clib.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_clib.py new file mode 100644 index 0000000000000000000000000000000000000000..b5315df4f6599cd376e628c0d74cb14129cd89b8 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_ext.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..c7b60ac32fcd6628cf96396a7e5d8fdb50f67c19 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_meta.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd0a0a8ede8ecb8d0c5ae55c8c3b09559239ed5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_meta.py @@ -0,0 +1,959 @@ +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') -> None: + self.cwd = cwd + self.env = env or {} + self.backend_name = backend_name + + +class BuildBackend(BuildBackendBase): + """PEP 517 Build Backend""" + + def __init__(self, *args, **kwargs) -> None: + 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) -> None: + super().__init__(*args, **kwargs) + + (self.backend_name, _, self.backend_obj) = self.backend_name.partition(':') + + def __call__(self, name, *args, **kw) -> Any: + """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") + + +@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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_py.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_build_py.py new file mode 100644 index 0000000000000000000000000000000000000000..78848f718281cce38df5deb82b7afa855c6e0d07 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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): # noqa: PT031 + # 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_config_discovery.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_config_discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..b5df8203cdb6f9129a65d0c503c4f51e21315b1f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_core_metadata.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_core_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec6df3dfeb1a3bb6961348d760838eb453be86f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_core_metadata.py @@ -0,0 +1,550 @@ +from __future__ import annotations + +import functools +import io +from email import message_from_string +from email.generator import Generator +from email.message import EmailMessage +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 setuptools import sic +from setuptools._core_metadata import rfc822_escape, rfc822_unescape +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_pkg_info_roundtrip(self, tmp_path, dist): + """Ensure PKG-INFO round trips according to pypa/wheel's methodology""" + # Generate an simplified "egg-info" with PKG-INFO + pkg_info = _get_pkginfo(dist) + + # Emulate the way old versions of wheel.bdist_wheel used to parse and regenerate + # the message, then ensures the metadata generated by setuptools is compatible. + with io.StringIO(pkg_info) 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(pkg_info, "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 + + +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 _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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_depends.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_depends.py new file mode 100644 index 0000000000000000000000000000000000000000..1714c041f7a23e1ecbfc3245bf964f75c13734ca --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_develop.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_develop.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a3be28ba9bb8bacee4ce43eca86dc6f6c62a15 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_develop.py @@ -0,0 +1,113 @@ +"""develop tests""" + +import os +import platform +import subprocess +import sys + +import pytest + +from setuptools._path import paths_on_pythonpath + +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 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.xfail(reason="pkg_resources has been removed") + @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", + ) + @pytest.mark.uses_network + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_dist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..9685dcd7cbbeceb1e35d69de30b9e2fdc3f06227 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_dist.py @@ -0,0 +1,280 @@ +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 .fixtures 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, setuptools_wheel): + """ + 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, setuptools_wheel + ) + 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.name 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_dist_info.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_dist_info.py new file mode 100644 index 0000000000000000000000000000000000000000..f65d0afbe46299fa816b2c64dc538dbd66880dab --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_dist_info.py @@ -0,0 +1,147 @@ +"""Test .dist-info style distributions.""" + +import pathlib +import re +import shutil +import subprocess +import sys +from functools import partial + +import pytest + +from setuptools.archive_util import unpack_archive + +from .textwrap import DALS + +read = partial(pathlib.Path.read_text, encoding="utf-8") + + +class TestDistInfo: + 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.MULTILINE | re.IGNORECASE) + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_distutils_adoption.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_distutils_adoption.py new file mode 100644 index 0000000000000000000000000000000000000000..f99a58849950029f53322c19cde1c171fe26622c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_editable_install.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_editable_install.py new file mode 100644 index 0000000000000000000000000000000000000000..cf2dbe9e0ffba094f5e3006aadbb63fa90baa14a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_editable_install.py @@ -0,0 +1,1261 @@ +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 ( + _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"]) + + +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 + + +@pytest.mark.uses_network +def test_pbr_integration(pbr_package, venv, editable_opts): + """Ensure editable installs work with pbr, issue #3500""" + cmd = [ + 'python', + '-m', + 'pip', + '-v', + 'install', + '--editable', + pbr_package, + *editable_opts, + ] + venv.run(cmd, stderr=subprocess.STDOUT) + 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) + + with pytest.raises(SimulatedErr) as ctx: + cmd.run() + assert any('debugging-tips' in note for note in ctx.value.__notes__) + + +@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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_egg_info.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_egg_info.py new file mode 100644 index 0000000000000000000000000000000000000000..3653be096f11b77c71f58679d6e4a108903668a5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_egg_info.py @@ -0,0 +1,1306 @@ +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"(Invalid object reference|Problems to parse)" + with pytest.raises((errors.OptionError, ValueError), 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] + assert "invalid-identifier" in str(ex.value) + + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_extern.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_extern.py new file mode 100644 index 0000000000000000000000000000000000000000..d7eb3c62c190dacdd4a054d2934962be2f4ee860 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_find_packages.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_find_packages.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd9f8f6637d13cb898fcd446a6b090323d02014 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_find_py_modules.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_find_py_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..8034b544294e5d30274bac82f24f93613120a0d4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_glob.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_glob.py new file mode 100644 index 0000000000000000000000000000000000000000..8d225a44610163c7d56d65b07c06f0f598ccfe84 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_install_scripts.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_install_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..e62a6b7f318df2da0cf29e53c41f74e5525e78ac --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_logging.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..5d487bda2df44ae79053f927f2bb703d0216f123 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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( + ('flags', 'expected_level'), [([], "INFO"), (["--verbose"], "DEBUG")] +) +def test_verbosity_level(tmp_path, monkeypatch, flags, 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 = flags + ["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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_manifest.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..903a528db0cc2bba27bbcef24aa1c59dc4156528 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_namespaces.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_namespaces.py new file mode 100644 index 0000000000000000000000000000000000000000..ef4a6f65c486524e9735c54d1319d0f255f73d10 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_namespaces.py @@ -0,0 +1,79 @@ +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_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 + pkg_resources_imp = [ + sys.executable, + '-c', + 'import myns.pkgA', + ] + with paths_on_pythonpath([str(target)]): + subprocess.check_call(pkg_resources_imp, cwd=str(pkg_A)) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_scripts.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..8641f7b639161525e2fff3100744d7fa55d9d718 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_scripts.py @@ -0,0 +1,12 @@ +from setuptools import _scripts + + +class TestWindowsScriptWriter: + def test_header(self): + hdr = _scripts.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('\\"') diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_sdist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..5b435fe111346d026ba20bbbf68994282e8b64c7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_sdist.py @@ -0,0 +1,980 @@ +"""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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_setopt.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_setopt.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf25618a5d6e255ad0be0fbed51fc29c179dcfe --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_setuptools.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_setuptools.py new file mode 100644 index 0000000000000000000000000000000000000000..1d56e1a8a4ebc5c7aaeb9902ef9972f7de97ecbf --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_shutil_wrapper.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_shutil_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..74ff7e9a896328a3d57ca3639658e3b9d538585f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_unicode_utils.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_unicode_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a24a9bd5305d1de7c1c925466bb7d222c85864a7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_virtualenv.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_virtualenv.py new file mode 100644 index 0000000000000000000000000000000000000000..b02949baf9cef8eb4df9c697add28f79a93b64d4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_warnings.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..41193d4f717344546f8c70ad18b268a04740129b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_wheel.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..c3b215a4744c8118f2667c8a6cc1e1a2ebdce138 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_wheel.py @@ -0,0 +1,690 @@ +"""wheel tests""" + +from __future__ import annotations + +import contextlib +import glob +import inspect +import os +import pathlib +import stat +import subprocess +import sys +import sysconfig +import zipfile +from typing import Any + +import pytest +from jaraco import path +from packaging.tags import parse_tag + +from setuptools._importlib import metadata +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): + return { + os.path.join(os.path.relpath(dirpath, root), filename) + for dirpath, dirnames, filenames in os.walk(root) + for filename in filenames + } + + +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=sysconfig.get_python_version(), + 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 + + (dist,) = metadata.Distribution.discover(path=[egg_path]) + + # pyright is nitpicky; fine to assume dist.metadata.__getitem__ will fail or return None + # (https://github.com/pypa/setuptools/pull/5006#issuecomment-2894774288) + assert dist.metadata['Name'] == project_name # pyright: ignore # noqa: PGH003 + assert dist.metadata['Version'] == version # pyright: ignore # noqa: PGH003 + assert dist.read_text('requires.txt') == requires_txt + + +class Record: + def __init__(self, id, **kwargs) -> None: + 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='\n' + + 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_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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_windows_wrappers.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_windows_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..4f990eb1c3cc67c61ea17f791430651e91040f18 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/test_windows_wrappers.py @@ -0,0 +1,258 @@ +""" +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 + +from setuptools._importlib import resources + +pytestmark = pytest.mark.skipif(sys.platform != 'win32', reason="Windows only") + + +class WrapperTester: + @classmethod + def prep_script(cls, template): + python_exe = subprocess.list2cmdline([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 = resources.files('setuptools').joinpath(cls.wrapper_source).read_bytes() + 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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/text.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/text.py new file mode 100644 index 0000000000000000000000000000000000000000..e05cc633ede9e5ce4f74b66a7bf76327c2000caa --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/textwrap.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/setuptools/tests/textwrap.py new file mode 100644 index 0000000000000000000000000000000000000000..5e39618dca4ad6c3f0d4c8cb20af59ab85fb0eba --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/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/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97b456c8753144a3ef1a76d8f29809fe839f830f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__init__.py @@ -0,0 +1,36 @@ +"""Manipulation and analysis of geometric objects in the Cartesian plane.""" + +from shapely.lib import GEOSException +from shapely.lib import Geometry +from shapely.lib import geos_version, geos_version_string +from shapely.lib import geos_capi_version, geos_capi_version_string +from shapely.errors import setup_signal_checks +from shapely._geometry import * +from shapely.creation import * +from shapely.constructive import * +from shapely.predicates import * +from shapely.measurement import * +from shapely.set_operations import * +from shapely.linear import * +from shapely.coordinates import * +from shapely.strtree import * +from shapely.io import * +from shapely._coverage import * + +# Submodule always needs to be imported to ensure Geometry subclasses are registered +from shapely.geometry import ( + Point, + LineString, + Polygon, + MultiPoint, + MultiLineString, + MultiPolygon, + GeometryCollection, + LinearRing, +) + +from shapely import _version + +__version__ = _version.get_versions()["version"] + +setup_signal_checks() diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/affinity.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/affinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c64595b34ad196d474ad21d2fddabd2968f3a55 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/affinity.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/conftest.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a06ebe83c9dd41d8d39536641582095a244008b1 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/conftest.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/constructive.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/constructive.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43e9a8f6b6d8d831998dab3918e265c45773682d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/constructive.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/coordinates.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/coordinates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..587f674246b8d17f2d259a5a9b006eeacc43b696 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/coordinates.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/coords.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/coords.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f9affe05fc2ee50660961585d08d19e3c2941c7 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/coords.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/creation.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/creation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..188e4f9282fb2c1a6064675c217d83703432568e Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/creation.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/decorators.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/decorators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2f084c3a6b97fa56f7b9ad757f1c819418a1318 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/decorators.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/errors.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..303aff75e2a99e1e273502328f10947173115327 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/errors.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/geos.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/geos.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e6c107acd152798770a2595db03b26893863bc3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/geos.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/io.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35d8b82c43ada4f03971927e883c57609e202804 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/io.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/linear.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/linear.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9ad9be9addf59c4052afb65289dab154bd78153 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/linear.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/measurement.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/measurement.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1af145dc4097c05c5f9cf8c5e5ed8b0ca4c31acf Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/measurement.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/ops.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/ops.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bcae31e54cb788d565c25c99aac13ed4337299d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/__pycache__/ops.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_coverage.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..fd054603337f29e07044b0153e297228689cd040 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_coverage.py @@ -0,0 +1,168 @@ +import numpy as np + +from shapely import Geometry, GeometryType, lib +from shapely._geometry import get_parts +from shapely.decorators import multithreading_enabled, requires_geos + +__all__ = ["coverage_invalid_edges", "coverage_is_valid", "coverage_simplify"] + + +@requires_geos("3.12.0") +@multithreading_enabled +def coverage_is_valid(geometry, gap_width=0.0, **kwargs): + """Verify if a coverage is valid. + + The coverage is represented by an array of polygonal geometries with + exactly matching edges and no overlap. + + A valid coverage may contain holes (regions of no coverage). However, + sometimes it might be desirable to detect narrow gaps as invalidities in + the coverage. The `gap_width` parameter allows to specify the maximum + width of gaps to detect. When gaps are detected, this function will + return False and the `coverage_invalid_edges` function can be used to + find the edges of those gaps. + + Geometries that are not Polygon or MultiPolygon are ignored. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometry : array_like + Array of geometries to verify. + gap_width : float, default 0.0 + The maximum width of gaps to detect. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Returns + ------- + bool + + See Also + -------- + coverage_invalid_edges, coverage_simplify + + """ + geometries = np.asarray(geometry) + # we always consider the full array as a single coverage -> ravel the input + # to pass a 1D array + return lib.coverage_is_valid(geometries.ravel(order="K"), gap_width, **kwargs) + + +@requires_geos("3.12.0") +@multithreading_enabled +def coverage_invalid_edges(geometry, gap_width=0.0, **kwargs): + """Verify if a coverage is valid and return invalid edges. + + This functions returns linear indicators showing the location of invalid + edges (if any) in each polygon in the input array. + + The coverage is represented by an array of polygonal geometries with + exactly matching edges and no overlap. + + A valid coverage may contain holes (regions of no coverage). However, + sometimes it might be desirable to detect narrow gaps as invalidities in + the coverage. The `gap_width` parameter allows to specify the maximum + width of gaps to detect. When gaps are detected, the `coverage_is_valid` + function will return False and this function can be used to find the + edges of those gaps. + + Geometries that are not Polygon or MultiPolygon are ignored. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometry : array_like + Array of geometries to verify. + gap_width : float, default 0.0 + The maximum width of gaps to detect. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Returns + ------- + numpy.ndarray | shapely.Geometry + + See Also + -------- + coverage_is_valid, coverage_simplify + + """ + geometries = np.asarray(geometry) + # we always consider the full array as a single coverage -> ravel the input + # to pass a 1D array + return lib.coverage_invalid_edges(geometries.ravel(order="K"), gap_width, **kwargs) + + +@requires_geos("3.12.0") +@multithreading_enabled +def coverage_simplify(geometry, tolerance, *, simplify_boundary=True): + """Return a simplified version of an input geometry using coverage simplification. + + Assumes that the geometry forms a polygonal coverage. Under this assumption, the + function simplifies the edges using the Visvalingam-Whyatt algorithm, while + preserving a valid coverage. In the most simplified case, polygons are reduced to + triangles. + + A collection of valid polygons is considered a coverage if the polygons are: + + * **Non-overlapping** - polygons do not overlap (their interiors do not intersect) + * **Edge-Matched** - vertices along shared edges are identical + + The function allows simplification of all edges including the outer boundaries of + the coverage or simplification of only the inner (shared) edges. + + If there are other geometry types than Polygons or MultiPolygons present, + the function will raise an error. + + If the geometry is polygonal but does not form a valid coverage due to overlaps, + it will be simplified but it may result in invalid topology. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometry : Geometry or array_like + tolerance : float or array_like + The degree of simplification roughly equal to the square root of the area + of triangles that will be removed. + simplify_boundary : bool, optional + By default (True), simplifies both internal edges of the coverage as well + as its boundary. If set to False, only simplifies internal edges. + + Returns + ------- + numpy.ndarray | shapely.Geometry + + See Also + -------- + coverage_is_valid, coverage_invalid_edges + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> poly = Polygon([(0, 0), (20, 0), (20, 10), (10, 5), (0, 10), (0, 0)]) + >>> shapely.coverage_simplify(poly, tolerance=2) + + """ + scalar = False + if isinstance(geometry, Geometry): + scalar = True + + geometries = np.asarray(geometry) + shape = geometries.shape + geometries = geometries.ravel() + + # create_collection acts on the inner axis + collections = lib.create_collection( + geometries, np.intc(GeometryType.GEOMETRYCOLLECTION) + ) + + simplified = lib.coverage_simplify(collections, tolerance, simplify_boundary) + parts = get_parts(simplified).reshape(shape) + if scalar: + return parts.item() + return parts diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_enum.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8bf3ac5d9eb1df2ae7a1cfa6988fb0b15b9cd0 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_enum.py @@ -0,0 +1,23 @@ +from enum import IntEnum + + +class ParamEnum(IntEnum): + """Wraps IntEnum to provide validation of a requested item. + + Intended for enums used for function parameters. + + Use enum.get_value(item) for this behavior instead of builtin enum[item]. + """ + + @classmethod + def get_value(cls, item): + """Validate item and raise a ValueError with valid options if not present.""" + try: + return cls[item].value + except KeyError: + valid_options = {e.name for e in cls} + raise ValueError( + "'{}' is not a valid option, must be one of '{}'".format( + item, "', '".join(valid_options) + ) + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_geometry.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..586db3428fa3a0e4dffbdd7ad2e73da7397e9191 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_geometry.py @@ -0,0 +1,1027 @@ +import warnings +from enum import IntEnum + +import numpy as np + +from shapely import _geometry_helpers, geos_version, lib +from shapely._enum import ParamEnum +from shapely.decorators import ( + deprecate_positional, + multithreading_enabled, + requires_geos, +) + +__all__ = [ + "GeometryType", + "force_2d", + "force_3d", + "get_coordinate_dimension", + "get_dimensions", + "get_exterior_ring", + "get_geometry", + "get_interior_ring", + "get_m", + "get_num_coordinates", + "get_num_geometries", + "get_num_interior_rings", + "get_num_points", + "get_parts", + "get_point", + "get_precision", + "get_rings", + "get_srid", + "get_type_id", + "get_x", + "get_y", + "get_z", + "set_precision", + "set_srid", +] + + +class GeometryType(IntEnum): + """The enumeration of GEOS geometry types.""" + + MISSING = -1 + POINT = 0 + LINESTRING = 1 + LINEARRING = 2 + POLYGON = 3 + MULTIPOINT = 4 + MULTILINESTRING = 5 + MULTIPOLYGON = 6 + GEOMETRYCOLLECTION = 7 + + +# generic + + +@multithreading_enabled +def get_type_id(geometry, **kwargs): + """Return the type ID of a geometry. + + Possible values are: + + - None (missing) is -1 + - POINT is 0 + - LINESTRING is 1 + - LINEARRING is 2 + - POLYGON is 3 + - MULTIPOINT is 4 + - MULTILINESTRING is 5 + - MULTIPOLYGON is 6 + - GEOMETRYCOLLECTION is 7 + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the type ID of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + GeometryType + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.get_type_id(LineString([(0, 0), (1, 1), (2, 2), (3, 3)])) + 1 + >>> shapely.get_type_id([Point(1, 2), Point(2, 3)]).tolist() + [0, 0] + + """ + return lib.get_type_id(geometry, **kwargs) + + +@multithreading_enabled +def get_dimensions(geometry, **kwargs): + """Return the inherent dimensionality of a geometry. + + The inherent dimension is 0 for points, 1 for linestrings and linearrings, + and 2 for polygons. For geometrycollections it is the max of the containing + elements. Empty collections and None values return -1. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the dimensionality of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, Point, Polygon + >>> point = Point(0, 0) + >>> shapely.get_dimensions(point) + 0 + >>> polygon = Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]) + >>> shapely.get_dimensions(polygon) + 2 + >>> shapely.get_dimensions(GeometryCollection([point, polygon])) + 2 + >>> shapely.get_dimensions(GeometryCollection([])) + -1 + >>> shapely.get_dimensions(None) + -1 + + """ + return lib.get_dimensions(geometry, **kwargs) + + +@multithreading_enabled +def get_coordinate_dimension(geometry, **kwargs): + """Return the dimensionality of the coordinates in a geometry (2, 3 or 4). + + The return value can be one of the following: + + * Return 2 for geometries with XY coordinate types, + * Return 3 for XYZ or XYM coordinate types + (distinguished by :meth:`has_z` or :meth:`has_m`), + * Return 4 for XYZM coordinate types, + * Return -1 for missing geometries (``None`` values). + + Note that with GEOS < 3.12, if the first Z coordinate equals ``nan``, this function + will return ``2``. Geometries with M coordinates are supported with GEOS >= 3.12. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the coordinate dimension of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> shapely.get_coordinate_dimension(Point(0, 0)) + 2 + >>> shapely.get_coordinate_dimension(Point(0, 0, 1)) + 3 + >>> shapely.get_coordinate_dimension(None) + -1 + + """ + return lib.get_coordinate_dimension(geometry, **kwargs) + + +@multithreading_enabled +def get_num_coordinates(geometry, **kwargs): + """Return the total number of coordinates in a geometry. + + Returns 0 for not-a-geometry values. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the number of coordinates of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, Point + >>> point = Point(0, 0) + >>> shapely.get_num_coordinates(point) + 1 + >>> shapely.get_num_coordinates(Point(0, 0, 0)) + 1 + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.get_num_coordinates(line) + 2 + >>> shapely.get_num_coordinates(GeometryCollection([point, line])) + 3 + >>> shapely.get_num_coordinates(None) + 0 + + """ + return lib.get_num_coordinates(geometry, **kwargs) + + +@multithreading_enabled +def get_srid(geometry, **kwargs): + """Return the SRID of a geometry. + + Returns -1 for not-a-geometry values. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the SRID of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + set_srid + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> point = Point(0, 0) + >>> shapely.get_srid(point) + 0 + >>> with_srid = shapely.set_srid(point, 4326) + >>> shapely.get_srid(with_srid) + 4326 + + """ + return lib.get_srid(geometry, **kwargs) + + +@multithreading_enabled +def set_srid(geometry, srid, **kwargs): + """Return a geometry with its SRID set. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to set the SRID of. + srid : int + The SRID to set on the geometry. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_srid + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> point = Point(0, 0) + >>> shapely.get_srid(point) + 0 + >>> with_srid = shapely.set_srid(point, 4326) + >>> shapely.get_srid(with_srid) + 4326 + + """ + return lib.set_srid(geometry, np.intc(srid), **kwargs) + + +# points + + +@multithreading_enabled +def get_x(point, **kwargs): + """Return the x-coordinate of a point. + + Parameters + ---------- + point : Geometry or array_like + Non-point geometries will result in NaN being returned. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_y, get_z, get_m + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPoint, Point + >>> shapely.get_x(Point(1, 2)) + 1.0 + >>> shapely.get_x(MultiPoint([(1, 1), (1, 2)])) + nan + + """ + return lib.get_x(point, **kwargs) + + +@multithreading_enabled +def get_y(point, **kwargs): + """Return the y-coordinate of a point. + + Parameters + ---------- + point : Geometry or array_like + Non-point geometries will result in NaN being returned. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_x, get_z, get_m + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPoint, Point + >>> shapely.get_y(Point(1, 2)) + 2.0 + >>> shapely.get_y(MultiPoint([(1, 1), (1, 2)])) + nan + + """ + return lib.get_y(point, **kwargs) + + +@multithreading_enabled +def get_z(point, **kwargs): + """Return the z-coordinate of a point. + + Parameters + ---------- + point : Geometry or array_like + Non-point geometries or geometries without Z dimension will result + in NaN being returned. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_x, get_y, get_m + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPoint, Point + >>> shapely.get_z(Point(1, 2, 3)) + 3.0 + >>> shapely.get_z(Point(1, 2)) + nan + >>> shapely.get_z(MultiPoint([(1, 1, 1), (2, 2, 2)])) + nan + + """ + return lib.get_z(point, **kwargs) + + +@multithreading_enabled +@requires_geos("3.12.0") +def get_m(point, **kwargs): + """Return the m-coordinate of a point. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + point : Geometry or array_like + Non-point geometries or geometries without M dimension will result + in NaN being returned. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_x, get_y, get_z + + Examples + -------- + >>> import shapely + >>> from shapely import Point, from_wkt + >>> shapely.get_m(from_wkt("POINT ZM (1 2 3 4)")) + 4.0 + >>> shapely.get_m(from_wkt("POINT M (1 2 4)")) + 4.0 + >>> shapely.get_m(Point(1, 2, 3)) + nan + >>> shapely.get_m(from_wkt("MULTIPOINT M ((1 1 1), (2 2 2))")) + nan + + """ + return lib.get_m(point, **kwargs) + + +# linestrings + + +@multithreading_enabled +def get_point(geometry, index, **kwargs): + """Return the nth point of a linestring or linearring. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the point of. + index : int or array_like + Negative values count from the end of the linestring backwards. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_num_points + + Examples + -------- + >>> import shapely + >>> from shapely import LinearRing, LineString, MultiPoint, Point + >>> line = LineString([(0, 0), (1, 1), (2, 2), (3, 3)]) + >>> shapely.get_point(line, 1) + + >>> shapely.get_point(line, -2) + + >>> shapely.get_point(line, [0, 3]).tolist() + [, ] + + The function works the same for LinearRing input: + + >>> shapely.get_point(LinearRing([(0, 0), (1, 1), (2, 2), (0, 0)]), 1) + + + For non-linear geometries it returns None: + + >>> shapely.get_point(MultiPoint([(0, 0), (1, 1), (2, 2), (3, 3)]), 1) is None + True + >>> shapely.get_point(Point(1, 1), 0) is None + True + + """ + return lib.get_point(geometry, np.intc(index), **kwargs) + + +@multithreading_enabled +def get_num_points(geometry, **kwargs): + """Return the number of points in a linestring or linearring. + + Returns 0 for not-a-geometry values. The number of points in geometries + other than linestring or linearring equals zero. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the number of points of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_point + get_num_geometries + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, MultiPoint + >>> shapely.get_num_points(LineString([(0, 0), (1, 1), (2, 2), (3, 3)])) + 4 + >>> shapely.get_num_points(MultiPoint([(0, 0), (1, 1), (2, 2), (3, 3)])) + 0 + >>> shapely.get_num_points(None) + 0 + + """ + return lib.get_num_points(geometry, **kwargs) + + +# polygons + + +@multithreading_enabled +def get_exterior_ring(geometry, **kwargs): + """Return the exterior ring of a polygon. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the exterior ring of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_interior_ring + + Examples + -------- + >>> import shapely + >>> from shapely import Point, Polygon + >>> shapely.get_exterior_ring(Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)])) + + >>> shapely.get_exterior_ring(Point(1, 1)) is None + True + + """ + return lib.get_exterior_ring(geometry, **kwargs) + + +@multithreading_enabled +def get_interior_ring(geometry, index, **kwargs): + """Return the nth interior ring of a polygon. + + The number of interior rings in non-polygons equals zero. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the interior ring of. + index : int or array_like + Negative values count from the end of the interior rings backwards. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_exterior_ring + get_num_interior_rings + + Examples + -------- + >>> import shapely + >>> from shapely import Point, Polygon + >>> polygon_with_hole = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]] + ... ) + >>> shapely.get_interior_ring(polygon_with_hole, 0) + + >>> shapely.get_interior_ring(polygon_with_hole, 1) is None + True + >>> polygon = Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]) + >>> shapely.get_interior_ring(polygon, 0) is None + True + >>> shapely.get_interior_ring(Point(0, 0), 0) is None + True + + """ + return lib.get_interior_ring(geometry, np.intc(index), **kwargs) + + +@multithreading_enabled +def get_num_interior_rings(geometry, **kwargs): + """Return number of internal rings in a polygon. + + Returns 0 for not-a-geometry values. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the number of interior rings of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_exterior_ring + get_interior_ring + + Examples + -------- + >>> import shapely + >>> from shapely import Point, Polygon + >>> polygon = Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]) + >>> shapely.get_num_interior_rings(polygon) + 0 + >>> polygon_with_hole = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]] + ... ) + >>> shapely.get_num_interior_rings(polygon_with_hole) + 1 + >>> shapely.get_num_interior_rings(Point(0, 0)) + 0 + >>> shapely.get_num_interior_rings(None) + 0 + + """ + return lib.get_num_interior_rings(geometry, **kwargs) + + +# collections + + +@multithreading_enabled +def get_geometry(geometry, index, **kwargs): + """Return the nth geometry from a collection of geometries. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the nth geometry of. + index : int or array_like + Negative values count from the end of the collection backwards. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + - simple geometries act as length-1 collections + - out-of-range values return None + + See Also + -------- + get_num_geometries, get_parts + + Examples + -------- + >>> import shapely + >>> from shapely import Point, MultiPoint + >>> multipoint = MultiPoint([(0, 0), (1, 1), (2, 2), (3, 3)]) + >>> shapely.get_geometry(multipoint, 1) + + >>> shapely.get_geometry(multipoint, -1) + + >>> shapely.get_geometry(multipoint, 5) is None + True + >>> shapely.get_geometry(Point(1, 1), 0) + + >>> shapely.get_geometry(Point(1, 1), 1) is None + True + + """ + return lib.get_geometry(geometry, np.intc(index), **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# get_parts(geometry, return_index=False) +# shapely 2.1: shows deprecation warning about positional 'return_index' +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'geometry' +# get_parts(geometry, *, return_index=False) + + +@deprecate_positional(["return_index"]) +def get_parts(geometry, return_index=False): + """Get parts of each GeometryCollection or Multi* geometry object. + + A copy of each geometry in the GeometryCollection or Multi* geometry object + is returned. + + Note: This does not return the individual parts of Multi* geometry objects + in a GeometryCollection. You may need to call this function multiple times + to return individual parts of Multi* geometry objects in a + GeometryCollection. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the parts of. + return_index : bool, default False + If True, will return a tuple of ndarrays of (parts, indexes), where + indexes are the indexes of the original geometries in the source array. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``return_index`` is specified as + a positional argument. This will need to be specified as a keyword + argument in a future release. + + Returns + ------- + ndarray of parts or tuple of (parts, indexes) + + See Also + -------- + get_geometry, get_rings + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPoint + >>> shapely.get_parts(MultiPoint([(0, 1), (2, 3)])).tolist() + [, ] + >>> parts, index = shapely.get_parts([MultiPoint([(0, 1)]), \ +MultiPoint([(4, 5), (6, 7)])], return_index=True) + >>> parts.tolist() + [, , ] + >>> index.tolist() + [0, 1, 1] + + """ + geometry = np.asarray(geometry, dtype=np.object_) + geometry = np.atleast_1d(geometry) + + if geometry.ndim != 1: + raise ValueError("Array should be one dimensional") + + if return_index: + return _geometry_helpers.get_parts(geometry) + + return _geometry_helpers.get_parts(geometry)[0] + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# get_rings(geometry, return_index=False) +# shapely 2.1: shows deprecation warning about positional 'return_index' +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'geometry' +# get_rings(geometry, *, return_index=False) + + +@deprecate_positional(["return_index"]) +def get_rings(geometry, return_index=False): + """Get rings of Polygon geometry object. + + For each Polygon, the first returned ring is always the exterior ring + and potential subsequent rings are interior rings. + + If the geometry is not a Polygon, nothing is returned (empty array for + scalar geometry input or no element in output array for array input). + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the rings of. + return_index : bool, default False + If True, will return a tuple of ndarrays of (rings, indexes), where + indexes are the indexes of the original geometries in the source array. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``return_index`` is specified as + a positional argument. This will need to be specified as a keyword + argument in a future release. + + Returns + ------- + ndarray of rings or tuple of (rings, indexes) + + See Also + -------- + get_exterior_ring, get_interior_ring, get_parts + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> polygon_with_hole = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]] + ... ) + >>> shapely.get_rings(polygon_with_hole).tolist() + [, + ] + + With ``return_index=True``: + + >>> polygon = Polygon([(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]) + >>> rings, index = shapely.get_rings( + ... [polygon, polygon_with_hole], + ... return_index=True + ... ) + >>> rings.tolist() + [, + , + ] + >>> index.tolist() + [0, 1, 1] + + """ + geometry = np.asarray(geometry, dtype=np.object_) + geometry = np.atleast_1d(geometry) + + if geometry.ndim != 1: + raise ValueError("Array should be one dimensional") + + if return_index: + return _geometry_helpers.get_parts(geometry, extract_rings=True) + + return _geometry_helpers.get_parts(geometry, extract_rings=True)[0] + + +@multithreading_enabled +def get_num_geometries(geometry, **kwargs): + """Return number of geometries in a collection. + + Returns 0 for not-a-geometry values. The number of geometries in points, + linestrings, linearrings and polygons equals one. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the number of geometries of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_num_points + get_geometry + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPoint, Point + >>> shapely.get_num_geometries(MultiPoint([(0, 0), (1, 1), (2, 2), (3, 3)])) + 4 + >>> shapely.get_num_geometries(Point(1, 1)) + 1 + >>> shapely.get_num_geometries(None) + 0 + + """ + return lib.get_num_geometries(geometry, **kwargs) + + +@multithreading_enabled +def get_precision(geometry, **kwargs): + """Get the precision of a geometry. + + If a precision has not been previously set, it will be 0 (double + precision). Otherwise, it will return the precision grid size that was + set on a geometry. + + Returns NaN for not-a-geometry values. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the precision of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + set_precision + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> point = Point(1, 1) + >>> shapely.get_precision(point) + 0.0 + >>> geometry = shapely.set_precision(point, 1.0) + >>> shapely.get_precision(geometry) + 1.0 + >>> shapely.get_precision(None) + nan + + """ + return lib.get_precision(geometry, **kwargs) + + +class SetPrecisionMode(ParamEnum): + valid_output = 0 + pointwise = 1 + keep_collapsed = 2 + + +@multithreading_enabled +def set_precision(geometry, grid_size, mode="valid_output", **kwargs): + """Return geometry with the precision set to a precision grid size. + + By default, geometries use double precision coordinates (grid_size = 0). + + Coordinates will be rounded if the precision grid specified is less precise + than the input geometry. Duplicated vertices will be dropped from lines and + polygons for grid sizes greater than 0. Line and polygon geometries may + collapse to empty geometries if all vertices are closer together than + ``grid_size`` or if a polygon becomes significantly narrower than + ``grid_size``. Spikes or sections in polygons narrower than ``grid_size`` + after rounding the vertices will be removed, which can lead to multipolygons + or empty geometries. Z values, if present, will not be modified. + + Notes + ----- + * subsequent operations will always be performed in the precision of the + geometry with higher precision (smaller "grid_size"). That same precision + will be attached to the operation outputs. + * input geometries should be geometrically valid; unexpected results may + occur if input geometries are not. + * the geometry returned will be in + :ref:`mild canonical form `, and the order of vertices can + change and should not be relied upon. + * returns None if geometry is None. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to set the precision of. + grid_size : float + Precision grid size. If 0, will use double precision (will not modify + geometry if precision grid size was not previously set). If this + value is more precise than input geometry, the input geometry will + not be modified. + mode : {'valid_output', 'pointwise', 'keep_collapsed'}, default 'valid_output' + This parameter determines the way a precision reduction is applied on + the geometry. There are three modes: + + 1. `'valid_output'` (default): The output is always valid. Collapsed + geometry elements (including both polygons and lines) are removed. + Duplicate vertices are removed. + 2. `'pointwise'`: Precision reduction is performed pointwise. Output + geometry may be invalid due to collapse or self-intersection. + Duplicate vertices are not removed. In GEOS this option is called + NO_TOPO. + + .. note:: + + 'pointwise' mode requires at least GEOS 3.10. It is accepted in + earlier versions, but the results may be unexpected. + 3. `'keep_collapsed'`: Like the default mode, except that collapsed + linear geometry elements are preserved. Collapsed polygonal input + elements are removed. Duplicate vertices are removed. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_precision + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.set_precision(Point(0.9, 0.9), 1.0) + + >>> shapely.set_precision(Point(0.9, 0.9, 0.9), 1.0) + + >>> shapely.set_precision(LineString([(0, 0), (0, 0.1), (0, 1), (1, 1)]), 1.0) + + >>> shapely.set_precision(LineString([(0, 0), (0, 0.1), (0.1, 0.1)]), 1.0, mode="valid_output") + + >>> shapely.set_precision(LineString([(0, 0), (0, 0.1), (0.1, 0.1)]), 1.0, mode="pointwise") + + >>> shapely.set_precision(LineString([(0, 0), (0, 0.1), (0.1, 0.1)]), 1.0, mode="keep_collapsed") + + >>> shapely.set_precision(None, 1.0) is None + True + + """ # noqa: E501 + if isinstance(mode, str): + mode = SetPrecisionMode.get_value(mode) + elif not np.isscalar(mode): + raise TypeError("mode only accepts scalar values") + if mode == SetPrecisionMode.pointwise and geos_version < (3, 10, 0): + warnings.warn( + "'pointwise' is only supported for GEOS 3.10", + UserWarning, + stacklevel=2, + ) + return lib.set_precision(geometry, grid_size, np.intc(mode), **kwargs) + + +@multithreading_enabled +def force_2d(geometry, **kwargs): + """Force the dimensionality of a geometry to 2D. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to force to 2D. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon, from_wkt + >>> shapely.force_2d(Point(0, 0, 1)) + + >>> shapely.force_2d(Point(0, 0)) + + >>> shapely.force_2d(LineString([(0, 0, 0), (0, 1, 1), (1, 1, 2)])) + + >>> shapely.force_2d(from_wkt("POLYGON Z EMPTY")) + + >>> shapely.force_2d(None) is None + True + + """ + return lib.force_2d(geometry, **kwargs) + + +@multithreading_enabled +def force_3d(geometry, z=0.0, **kwargs): + """Force the dimensionality of a geometry to 3D. + + 2D geometries will get the provided Z coordinate; Z coordinates of 3D geometries + are unchanged (unless they are nan). + + Note that for empty geometries, 3D is only supported since GEOS 3.9 and then + still only for simple geometries (non-collections). + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to force to 3D. + z : float or array_like, default 0.0 + The Z coordinate value to set on the geometry. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.force_3d(Point(0, 0), z=3) + + >>> shapely.force_3d(Point(0, 0, 0), z=3) + + >>> shapely.force_3d(LineString([(0, 0), (0, 1), (1, 1)])) + + >>> shapely.force_3d(None) is None + True + + """ + if np.isnan(z).any(): + raise ValueError("It is not allowed to set the Z coordinate to NaN.") + return lib.force_3d(geometry, z, **kwargs) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_geos.pxd b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_geos.pxd new file mode 100644 index 0000000000000000000000000000000000000000..6a7eb68d09147c40f55fb04c3f0b2503f8493cff --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_geos.pxd @@ -0,0 +1,57 @@ +"""Provides a wrapper for GEOS types and functions. + +Note: GEOS functions in Cython must be called using the get_geos_handle context +manager. + +Examples +-------- + with get_geos_handle() as geos_handle: + SomeGEOSFunc(geos_handle, ...) + +""" + +cdef extern from "geos_c.h": + # Types + ctypedef void *GEOSContextHandle_t + ctypedef struct GEOSGeometry + ctypedef struct GEOSCoordSequence + ctypedef void (*GEOSMessageHandler_r)(const char *message, void *userdata) + + # GEOS Context & Messaging + GEOSContextHandle_t GEOS_init_r() nogil + void GEOS_finish_r(GEOSContextHandle_t handle) nogil + void GEOSContext_setErrorMessageHandler_r(GEOSContextHandle_t handle, GEOSMessageHandler_r ef, void* userData) nogil + void GEOSContext_setNoticeMessageHandler_r(GEOSContextHandle_t handle, GEOSMessageHandler_r nf, void* userData) nogil + + # Geometry functions + const GEOSGeometry* GEOSGetGeometryN_r(GEOSContextHandle_t handle, const GEOSGeometry* g, int n) nogil + const GEOSGeometry* GEOSGetExteriorRing_r(GEOSContextHandle_t handle, const GEOSGeometry* g) nogil + const GEOSGeometry* GEOSGetInteriorRingN_r(GEOSContextHandle_t handle, const GEOSGeometry* g, int n) nogil + int GEOSGeomTypeId_r(GEOSContextHandle_t handle, GEOSGeometry* g) nogil + + # Geometry creation / destruction + GEOSGeometry* GEOSGeom_clone_r(GEOSContextHandle_t handle, const GEOSGeometry* g) nogil + GEOSGeometry* GEOSGeom_createPoint_r(GEOSContextHandle_t handle, GEOSCoordSequence* s) nogil + GEOSGeometry* GEOSGeom_createLineString_r(GEOSContextHandle_t handle, GEOSCoordSequence* s) nogil + GEOSGeometry* GEOSGeom_createLinearRing_r(GEOSContextHandle_t handle, GEOSCoordSequence* s) nogil + GEOSGeometry* GEOSGeom_createEmptyPolygon_r(GEOSContextHandle_t handle) nogil + GEOSGeometry* GEOSGeom_createPolygon_r(GEOSContextHandle_t handle, GEOSGeometry* shell, GEOSGeometry** holes, unsigned int nholes) nogil + GEOSGeometry* GEOSGeom_createCollection_r(GEOSContextHandle_t handle, int type, GEOSGeometry** geoms, unsigned int ngeoms) nogil + void GEOSGeom_destroy_r(GEOSContextHandle_t handle, GEOSGeometry* g) nogil + + # Coordinate sequences + const GEOSCoordSequence* GEOSGeom_getCoordSeq_r(GEOSContextHandle_t handle, const GEOSGeometry* g) + GEOSCoordSequence* GEOSCoordSeq_clone_r(GEOSContextHandle_t handle, const GEOSCoordSequence* s) + GEOSCoordSequence* GEOSCoordSeq_create_r(GEOSContextHandle_t handle, unsigned int size, unsigned int dims) nogil + void GEOSCoordSeq_destroy_r(GEOSContextHandle_t handle, GEOSCoordSequence* s) nogil + int GEOSCoordSeq_setX_r(GEOSContextHandle_t handle, GEOSCoordSequence* s, unsigned int idx, double val) nogil + int GEOSCoordSeq_setY_r(GEOSContextHandle_t handle, GEOSCoordSequence* s, unsigned int idx, double val) nogil + int GEOSCoordSeq_setZ_r(GEOSContextHandle_t handle, GEOSCoordSequence* s, unsigned int idx, double val) nogil + int GEOSCoordSeq_getSize_r(GEOSContextHandle_t handle, GEOSCoordSequence* s, unsigned int* size) nogil + + +cdef class get_geos_handle: + cdef GEOSContextHandle_t handle + cdef char* last_error + cdef char* last_warning + cdef GEOSContextHandle_t __enter__(self) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_pygeos_api.pxd b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_pygeos_api.pxd new file mode 100644 index 0000000000000000000000000000000000000000..83a1a70a59b4cfa46543a2407bfdfeed0ab11eca --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_pygeos_api.pxd @@ -0,0 +1,58 @@ +""" +Provides a wrapper for the shapely.lib C API for use in Cython. +Internally, the shapely C extension uses a PyCapsule to provide run-time access +to function pointers within the C API. + +To use these functions, you must first call the following function in each Cython module: +`import_shapely_c_api()` + +This uses a macro to dynamically load the functions from pointers in the PyCapsule. +Each C function in shapely.lib exposed in the C API must be specially-wrapped to enable +this capability. + +Segfaults will occur if the C API is not imported properly. +""" + +cimport numpy as np +from cpython.ref cimport PyObject + +from shapely._geos cimport GEOSContextHandle_t, GEOSCoordSequence, GEOSGeometry + + +cdef extern from "c_api.h": + cdef enum ShapelyErrorCode: + PGERR_SUCCESS, + PGERR_NOT_A_GEOMETRY, + PGERR_GEOS_EXCEPTION, + PGERR_NO_MALLOC, + PGERR_GEOMETRY_TYPE, + PGERR_MULTIPOINT_WITH_POINT_EMPTY, + PGERR_COORD_OUT_OF_BOUNDS, + PGERR_EMPTY_GEOMETRY, + PGERR_GEOJSON_EMPTY_POINT, + PGERR_LINEARRING_NCOORDS, + PGERR_NAN_COORD, + PGWARN_INVALID_WKB, + PGWARN_INVALID_WKT, + PGWARN_INVALID_GEOJSON, + PGERR_PYSIGNAL + + cpdef enum ShapelyHandleNan: + SHAPELY_HANDLE_NAN_ALLOW, + SHAPELY_HANDLE_NAN_SKIP, + SHAPELY_HANDLE_NANS_ERROR + + # shapely.lib C API loader; returns -1 on error + # MUST be called before calling other C API functions + int import_shapely_c_api() except -1 + + # C functions provided by the shapely.lib C API + # Note: GeometryObjects are always managed as Python objects + # in Cython to avoid memory leaks, not PyObject* (even though + # they are declared that way in the header file). + object PyGEOS_CreateGeometry(GEOSGeometry *ptr, GEOSContextHandle_t ctx) + char PyGEOS_GetGEOSGeometry(PyObject *obj, GEOSGeometry **out) nogil + int PyGEOS_CoordSeq_FromBuffer( + GEOSContextHandle_t ctx, const double* buf, unsigned int size, + unsigned int dims, char is_ring, int handle_nan, + GEOSCoordSequence** coord_seq) nogil diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_ragged_array.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_ragged_array.py new file mode 100644 index 0000000000000000000000000000000000000000..df157c0b064c79c607255a0164005c0b245709a3 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_ragged_array.py @@ -0,0 +1,475 @@ +"""Provides a conversion to / from a ragged array representation of geometries. + +A ragged (or "jagged") array is an irregular array of arrays of which each +element can have a different length. As a result, such an array cannot be +represented as a standard, rectangular nD array. +The coordinates of geometries can be represented as arrays of arrays of +coordinate pairs (possibly multiple levels of nesting, depending on the +geometry type). + +Geometries, as a ragged array of coordinates, can be efficiently represented +as contiguous arrays of coordinates provided that there is another data +structure that keeps track of which range of coordinate values corresponds +to a given geometry. This can be done using offsets, counts, or indices. + +This module currently implements offsets into the coordinates array. This +is the ragged array representation defined by the the Apache Arrow project +as "variable size list array" (https://arrow.apache.org/docs/format/Columnar.html#variable-size-list-layout). +See for example https://cfconventions.org/Data/cf-conventions/cf-conventions-1.9/cf-conventions.html#representations-features +for different options. + +The exact usage of the Arrow list array with varying degrees of nesting for the +different geometry types is defined by the GeoArrow project: +https://github.com/geoarrow/geoarrow + +""" + +import numpy as np + +from shapely import creation, geos_version +from shapely._geometry import ( + GeometryType, + get_parts, + get_rings, + get_type_id, +) +from shapely._geometry_helpers import ( + _from_ragged_array_multi_linear, + _from_ragged_array_multipolygon, +) +from shapely.coordinates import get_coordinates +from shapely.predicates import is_empty, is_missing + +__all__ = ["from_ragged_array", "to_ragged_array"] + +_geos_ge_312 = geos_version >= (3, 12, 0) + + +# # GEOS -> coords/offset arrays (to_ragged_array) + + +def _get_arrays_point(arr, include_z, include_m): + # only one array of coordinates + coords = get_coordinates(arr, include_z=include_z, include_m=include_m) + + # empty points are represented by NaNs + # + missing geometries should also be present with some value + empties = is_empty(arr) | is_missing(arr) + if empties.any(): + indices = np.nonzero(empties)[0] + indices = indices - np.arange(len(indices)) + coords = np.insert(coords, indices, np.nan, axis=0) + + return coords, () + + +def _indices_to_offsets(indices, n): + # default to int32 offsets if possible (to prefer the non-large arrow list variants) + # n_coords is the length of the array the indices are poin + if len(indices) > 2147483647: + dtype = np.int64 + else: + dtype = np.int32 + + offsets = np.insert(np.bincount(indices).cumsum(dtype=dtype), 0, 0) + + if len(offsets) != n + 1: + # last geometries might be empty or missing + offsets = np.pad( + offsets, + (0, n + 1 - len(offsets)), + "constant", + constant_values=offsets[-1], + ) + return offsets + + +def _get_arrays_multipoint(arr, include_z, include_m): + # explode/flatten the MultiPoints + _, part_indices = get_parts(arr, return_index=True) + # the offsets into the multipoint parts + offsets = _indices_to_offsets(part_indices, len(arr)) + + # only one array of coordinates + coords = get_coordinates(arr, include_z=include_z, include_m=include_m) + + return coords, (offsets,) + + +def _get_arrays_linestring(arr, include_z, include_m): + # the coords and offsets into the coordinates of the linestrings + coords, indices = get_coordinates( + arr, return_index=True, include_z=include_z, include_m=include_m + ) + offsets = _indices_to_offsets(indices, len(arr)) + + return coords, (offsets,) + + +def _get_arrays_multilinestring(arr, include_z, include_m): + # explode/flatten the MultiLineStrings + arr_flat, part_indices = get_parts(arr, return_index=True) + # the offsets into the multilinestring parts + offsets2 = _indices_to_offsets(part_indices, len(arr)) + + # the coords and offsets into the coordinates of the linestrings + coords, indices = get_coordinates( + arr_flat, return_index=True, include_z=include_z, include_m=include_m + ) + offsets1 = _indices_to_offsets(indices, len(arr_flat)) + + return coords, (offsets1, offsets2) + + +def _get_arrays_polygon(arr, include_z, include_m): + # explode/flatten the Polygons into Rings + arr_flat, ring_indices = get_rings(arr, return_index=True) + # the offsets into the exterior/interior rings of the multipolygon parts + offsets2 = _indices_to_offsets(ring_indices, len(arr)) + + # the coords and offsets into the coordinates of the rings + coords, indices = get_coordinates( + arr_flat, return_index=True, include_z=include_z, include_m=include_m + ) + offsets1 = _indices_to_offsets(indices, len(arr_flat)) + + return coords, (offsets1, offsets2) + + +def _get_arrays_multipolygon(arr, include_z, include_m): + # explode/flatten the MultiPolygons + arr_flat, part_indices = get_parts(arr, return_index=True) + # the offsets into the multipolygon parts + offsets3 = _indices_to_offsets(part_indices, len(arr)) + + # explode/flatten the Polygons into Rings + arr_flat2, ring_indices = get_rings(arr_flat, return_index=True) + # the offsets into the exterior/interior rings of the multipolygon parts + offsets2 = _indices_to_offsets(ring_indices, len(arr_flat)) + + # the coords and offsets into the coordinates of the rings + coords, indices = get_coordinates( + arr_flat2, return_index=True, include_z=include_z, include_m=include_m + ) + offsets1 = _indices_to_offsets(indices, len(arr_flat2)) + + return coords, (offsets1, offsets2, offsets3) + + +def to_ragged_array(geometries, include_z=None, include_m=None): + """Convert geometries to a ragged array representation. + + This function converts an array of geometries to a ragged array + (i.e. irregular array of arrays) of coordinates, represented in memory + using a single contiguous array of the coordinates, and + up to 3 offset arrays that keep track where each sub-array + starts and ends. + + This follows the in-memory layout of the variable size list arrays defined + by Apache Arrow, as specified for geometries by the GeoArrow project: + https://github.com/geoarrow/geoarrow. + + Parameters + ---------- + geometries : array_like + Array of geometries (1-dimensional). + include_z, include_m : bool, default None + If both are False, return XY (2D) geometries. + If both are True, return XYZM (4D) geometries. + If either is True, return either XYZ or XYM (3D) geometries. + If a geometry has no Z or M dimension, extra coordinate data will be NaN. + By default, will infer the dimensionality from the + input geometries. Note that this inference can be unreliable with + empty geometries (for a guaranteed result, it is recommended to + specify the keyword). + + .. versionadded:: 2.1.0 + The ``include_m`` parameter was added to support XYM (3D) and + XYZM (4D) geometries available with GEOS 3.12.0 or later. + With older GEOS versions, M dimension coordinates will be NaN. + + Returns + ------- + tuple of (geometry_type, coords, offsets) + geometry_type : GeometryType + The type of the input geometries (required information for + roundtrip). + coords : np.ndarray + Contiguous array of shape (n, 2), (n, 3), or (n, 4) of all + coordinates of all input geometries. + offsets: tuple of np.ndarray + Offset arrays that make it possible to reconstruct the + geometries from the flat coordinates array. The number of + offset arrays depends on the geometry type. See + https://github.com/geoarrow/geoarrow/blob/main/format.md + for details. + Uses int32 dtype offsets if possible, otherwise int64 for + large inputs (coordinates > 32GB). + + Notes + ----- + Mixed singular and multi geometry types of the same basic type are + allowed (e.g., Point and MultiPoint) and all singular types will be + treated as multi types. + GeometryCollections and other mixed geometry types are not supported. + + See Also + -------- + from_ragged_array + + Examples + -------- + Consider a Polygon with one hole (interior ring): + + >>> import shapely + >>> from shapely import Polygon + >>> polygon = Polygon( + ... [(0, 0), (10, 0), (10, 10), (0, 10)], + ... holes=[[(2, 2), (3, 2), (2, 3)]] + ... ) + >>> polygon + + + This polygon can be thought of as a list of rings (first ring is the + exterior ring, subsequent rings are the interior rings), and each ring + as a list of coordinate pairs. This is very similar to how GeoJSON + represents the coordinates: + + >>> import json + >>> json.loads(shapely.to_geojson(polygon))["coordinates"] + [[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0], [0.0, 0.0]], + [[2.0, 2.0], [3.0, 2.0], [2.0, 3.0], [2.0, 2.0]]] + + This function will return a similar list of lists of lists, but + using a single contiguous array of coordinates, and multiple arrays of + offsets: + + >>> geometry_type, coords, offsets = shapely.to_ragged_array([polygon]) + >>> geometry_type + + >>> coords + array([[ 0., 0.], + [10., 0.], + [10., 10.], + [ 0., 10.], + [ 0., 0.], + [ 2., 2.], + [ 3., 2.], + [ 2., 3.], + [ 2., 2.]]) + + >>> offsets + (array([0, 5, 9], dtype=int32), array([0, 2], dtype=int32)) + + As an example how to interpret the offsets: the i-th ring in the + coordinates is represented by ``offsets[0][i]`` to ``offsets[0][i+1]``: + + >>> exterior_ring_start, exterior_ring_end = offsets[0][0], offsets[0][1] + >>> coords[exterior_ring_start:exterior_ring_end] + array([[ 0., 0.], + [10., 0.], + [10., 10.], + [ 0., 10.], + [ 0., 0.]]) + + """ + from shapely import has_m, has_z # avoid circular import + + geometries = np.asarray(geometries) + if include_z is None: + include_z = np.any(has_z(geometries[~is_empty(geometries)])) + if include_m is None: + if _geos_ge_312: + include_m = np.any(has_m(geometries[~is_empty(geometries)])) + else: + include_m = False + + geom_types = np.unique(get_type_id(geometries)) + # ignore missing values (type of -1) + geom_types = geom_types[geom_types >= 0] + + get_arrays_args = geometries, include_z, include_m + if len(geom_types) == 1: + typ = GeometryType(geom_types[0]) + if typ == GeometryType.POINT: + coords, offsets = _get_arrays_point(*get_arrays_args) + elif typ == GeometryType.LINESTRING: + coords, offsets = _get_arrays_linestring(*get_arrays_args) + elif typ == GeometryType.POLYGON: + coords, offsets = _get_arrays_polygon(*get_arrays_args) + elif typ == GeometryType.MULTIPOINT: + coords, offsets = _get_arrays_multipoint(*get_arrays_args) + elif typ == GeometryType.MULTILINESTRING: + coords, offsets = _get_arrays_multilinestring(*get_arrays_args) + elif typ == GeometryType.MULTIPOLYGON: + coords, offsets = _get_arrays_multipolygon(*get_arrays_args) + else: + raise ValueError(f"Geometry type {typ.name} is not supported") + + elif len(geom_types) == 2: + if set(geom_types) == {GeometryType.POINT, GeometryType.MULTIPOINT}: + typ = GeometryType.MULTIPOINT + coords, offsets = _get_arrays_multipoint(*get_arrays_args) + elif set(geom_types) == {GeometryType.LINESTRING, GeometryType.MULTILINESTRING}: + typ = GeometryType.MULTILINESTRING + coords, offsets = _get_arrays_multilinestring(*get_arrays_args) + elif set(geom_types) == {GeometryType.POLYGON, GeometryType.MULTIPOLYGON}: + typ = GeometryType.MULTIPOLYGON + coords, offsets = _get_arrays_multipolygon(*get_arrays_args) + else: + raise ValueError( + "Geometry type combination is not supported " + f"({[GeometryType(t).name for t in geom_types]})" + ) + else: + raise ValueError( + "Geometry type combination is not supported " + f"({[GeometryType(t).name for t in geom_types]})" + ) + + return typ, coords, offsets + + +# # coords/offset arrays -> GEOS (from_ragged_array) + + +def _point_from_flatcoords(coords): + result = creation.points(coords) + + # Older versions of GEOS (<= 3.9) don't automatically convert NaNs + # to empty points -> do manually + empties = np.isnan(coords).all(axis=1) + if empties.any(): + result[empties] = creation.empty(1, geom_type=GeometryType.POINT).item() + + return result + + +def _multipoint_from_flatcoords(coords, offsets): + # recreate points + if len(offsets): + coords = coords[offsets[0] :] + points = creation.points(coords) + + # recreate multipoints + multipoint_parts = np.diff(offsets) + multipoint_indices = np.repeat(np.arange(len(multipoint_parts)), multipoint_parts) + + result = np.empty(len(offsets) - 1, dtype=object) + result = creation.multipoints(points, indices=multipoint_indices, out=result) + result[multipoint_parts == 0] = creation.empty( + 1, geom_type=GeometryType.MULTIPOINT + ).item() + + return result + + +def _linestring_from_flatcoords(coords, offsets): + # recreate linestrings + if len(offsets): + coords = coords[offsets[0] :] + linestring_n = np.diff(offsets) + linestring_indices = np.repeat(np.arange(len(linestring_n)), linestring_n) + + result = np.empty(len(offsets) - 1, dtype=object) + result = creation.linestrings(coords, indices=linestring_indices, out=result) + result[linestring_n == 0] = creation.empty( + 1, geom_type=GeometryType.LINESTRING + ).item() + return result + + +def _multilinestrings_from_flatcoords(coords, offsets1, offsets2): + # ensure correct dtypes + offsets1 = np.asarray(offsets1, dtype="int64") + offsets2 = np.asarray(offsets2, dtype="int64") + + # recreate multilinestrings + result = _from_ragged_array_multi_linear( + coords, offsets1, offsets2, geometry_type=GeometryType.MULTILINESTRING + ) + return result + + +def _polygon_from_flatcoords(coords, offsets1, offsets2): + # ensure correct dtypes + offsets1 = np.asarray(offsets1, dtype="int64") + offsets2 = np.asarray(offsets2, dtype="int64") + + # recreate polygons + result = _from_ragged_array_multi_linear( + coords, offsets1, offsets2, geometry_type=GeometryType.POLYGON + ) + return result + + +def _multipolygons_from_flatcoords(coords, offsets1, offsets2, offsets3): + # ensure correct dtypes + offsets1 = np.asarray(offsets1, dtype="int64") + offsets2 = np.asarray(offsets2, dtype="int64") + offsets3 = np.asarray(offsets3, dtype="int64") + + # recreate multipolygons + result = _from_ragged_array_multipolygon(coords, offsets1, offsets2, offsets3) + return result + + +def from_ragged_array(geometry_type, coords, offsets=None): + """Create geometries from a contiguous array of coordinates and offset arrays. + + This function creates geometries from the ragged array representation + as returned by ``to_ragged_array``. + + This follows the in-memory layout of the variable size list arrays defined + by Apache Arrow, as specified for geometries by the GeoArrow project: + https://github.com/geoarrow/geoarrow. + + See :func:`to_ragged_array` for more details. + + Parameters + ---------- + geometry_type : GeometryType + The type of geometry to create. + coords : np.ndarray + Contiguous array of shape (n, 2) or (n, 3) of all coordinates + for the geometries. + offsets: tuple of np.ndarray + Offset arrays that allow to reconstruct the geometries based on the + flat coordinates array. The number of offset arrays depends on the + geometry type. See + https://github.com/geoarrow/geoarrow/blob/main/format.md for details. + + Returns + ------- + np.ndarray + Array of geometries (1-dimensional). + + See Also + -------- + to_ragged_array + + """ + coords = np.asarray(coords, dtype="float64") + + if geometry_type == GeometryType.POINT: + if not (offsets is None or len(offsets) == 0): + raise ValueError("'offsets' should not be provided for geometry type Point") + return _point_from_flatcoords(coords) + + if offsets is None: + raise ValueError( + "'offsets' must be provided for any geometry type except for Point" + ) + + if geometry_type == GeometryType.LINESTRING: + return _linestring_from_flatcoords(coords, *offsets) + elif geometry_type == GeometryType.POLYGON: + return _polygon_from_flatcoords(coords, *offsets) + elif geometry_type == GeometryType.MULTIPOINT: + return _multipoint_from_flatcoords(coords, *offsets) + elif geometry_type == GeometryType.MULTILINESTRING: + return _multilinestrings_from_flatcoords(coords, *offsets) + elif geometry_type == GeometryType.MULTIPOLYGON: + return _multipolygons_from_flatcoords(coords, *offsets) + else: + raise ValueError(f"Geometry type {geometry_type.name} is not supported") diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_version.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..0783624d57a07bd2f073c00a845a6a0651f7195c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/_version.py @@ -0,0 +1,21 @@ + +# This file was generated by 'versioneer.py' (0.28) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +import json + +version_json = ''' +{ + "date": "2025-09-24T15:22:48+0200", + "dirty": false, + "error": null, + "full-revisionid": "5fb639d1056888d135fe56bfaf750c9648addeec", + "version": "2.1.2" +} +''' # END VERSION_JSON + + +def get_versions(): + return json.loads(version_json) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/affinity.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/affinity.py new file mode 100644 index 0000000000000000000000000000000000000000..381c6b6c1efe8bd9f8b44d8736d4d5d62c1f234f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/affinity.py @@ -0,0 +1,266 @@ +"""Affine transforms, both in general and specific, named transforms.""" + +from math import cos, pi, sin, tan + +import numpy as np + +import shapely + +__all__ = ["affine_transform", "rotate", "scale", "skew", "translate"] + + +def affine_transform(geom, matrix): + r"""Return a transformed geometry using an affine transformation matrix. + + The coefficient matrix is provided as a list or tuple with 6 or 12 items + for 2D or 3D transformations, respectively. + + For 2D affine transformations, the 6 parameter matrix is:: + + [a, b, d, e, xoff, yoff] + + which represents the augmented matrix:: + + [x'] / a b xoff \ [x] + [y'] = | d e yoff | [y] + [1 ] \ 0 0 1 / [1] + + or the equations for the transformed coordinates:: + + x' = a * x + b * y + xoff + y' = d * x + e * y + yoff + + For 3D affine transformations, the 12 parameter matrix is:: + + [a, b, c, d, e, f, g, h, i, xoff, yoff, zoff] + + which represents the augmented matrix:: + + [x'] / a b c xoff \ [x] + [y'] = | d e f yoff | [y] + [z'] | g h i zoff | [z] + [1 ] \ 0 0 0 1 / [1] + + or the equations for the transformed coordinates:: + + x' = a * x + b * y + c * z + xoff + y' = d * x + e * y + f * z + yoff + z' = g * x + h * y + i * z + zoff + """ + if len(matrix) == 6: + ndim = 2 + a, b, d, e, xoff, yoff = matrix + if geom.has_z: + ndim = 3 + i = 1.0 + c = f = g = h = zoff = 0.0 + elif len(matrix) == 12: + ndim = 3 + a, b, c, d, e, f, g, h, i, xoff, yoff, zoff = matrix + if not geom.has_z: + ndim = 2 + else: + raise ValueError("'matrix' expects either 6 or 12 coefficients") + + # if ndim == 2: + # A = np.array([[a, b], [d, e]], dtype=float) + # off = np.array([xoff, yoff], dtype=float) + # else: + # A = np.array([[a, b, c], [d, e, f], [g, h, i]], dtype=float) + # off = np.array([xoff, yoff, zoff], dtype=float) + + def _affine_coords(coords): + # These are equivalent, but unfortunately not robust + # result = np.matmul(coords, A.T) + off + # result = np.matmul(A, coords.T).T + off + # Therefore, manual matrix multiplication is needed + if ndim == 2: + x, y = coords.T + xp = a * x + b * y + xoff + yp = d * x + e * y + yoff + result = np.stack([xp, yp]).T + elif ndim == 3: + x, y, z = coords.T + xp = a * x + b * y + c * z + xoff + yp = d * x + e * y + f * z + yoff + zp = g * x + h * y + i * z + zoff + result = np.stack([xp, yp, zp]).T + return result + + return shapely.transform(geom, _affine_coords, include_z=ndim == 3) + + +def interpret_origin(geom, origin, ndim): + """Return interpreted coordinate tuple for origin parameter. + + This is a helper function for other transform functions. + + The point of origin can be a keyword 'center' for the 2D bounding box + center, 'centroid' for the geometry's 2D centroid, a Point object or a + coordinate tuple (x0, y0, z0). + """ + # get coordinate tuple from 'origin' from keyword or Point type + if origin == "center": + # bounding box center + minx, miny, maxx, maxy = geom.bounds + origin = ((maxx + minx) / 2.0, (maxy + miny) / 2.0) + elif origin == "centroid": + origin = geom.centroid.coords[0] + elif isinstance(origin, str): + raise ValueError(f"'origin' keyword {origin!r} is not recognized") + elif getattr(origin, "geom_type", None) == "Point": + origin = origin.coords[0] + + # origin should now be tuple-like + if len(origin) not in (2, 3): + raise ValueError("Expected number of items in 'origin' to be either 2 or 3") + if ndim == 2: + return origin[0:2] + else: # 3D coordinate + if len(origin) == 2: + return origin + (0.0,) + else: + return origin + + +def rotate(geom, angle, origin="center", use_radians=False): + r"""Return a rotated geometry on a 2D plane. + + The angle of rotation can be specified in either degrees (default) or + radians by setting ``use_radians=True``. Positive angles are + counter-clockwise and negative are clockwise rotations. + + The point of origin can be a keyword 'center' for the bounding box + center (default), 'centroid' for the geometry's centroid, a Point object + or a coordinate tuple (x0, y0). + + The affine transformation matrix for 2D rotation is: + + / cos(r) -sin(r) xoff \ + | sin(r) cos(r) yoff | + \ 0 0 1 / + + where the offsets are calculated from the origin Point(x0, y0): + + xoff = x0 - x0 * cos(r) + y0 * sin(r) + yoff = y0 - x0 * sin(r) - y0 * cos(r) + """ + if geom.is_empty: + return geom + if not use_radians: # convert from degrees + angle = angle * pi / 180.0 + cosp = cos(angle) + sinp = sin(angle) + if abs(cosp) < 2.5e-16: + cosp = 0.0 + if abs(sinp) < 2.5e-16: + sinp = 0.0 + x0, y0 = interpret_origin(geom, origin, 2) + + # fmt: off + matrix = (cosp, -sinp, 0.0, + sinp, cosp, 0.0, + 0.0, 0.0, 1.0, + x0 - x0 * cosp + y0 * sinp, y0 - x0 * sinp - y0 * cosp, 0.0) + # fmt: on + return affine_transform(geom, matrix) + + +def scale(geom, xfact=1.0, yfact=1.0, zfact=1.0, origin="center"): + r"""Return a scaled geometry, scaled by factors along each dimension. + + The point of origin can be a keyword 'center' for the 2D bounding box + center (default), 'centroid' for the geometry's 2D centroid, a Point + object or a coordinate tuple (x0, y0, z0). + + Negative scale factors will mirror or reflect coordinates. + + The general 3D affine transformation matrix for scaling is: + + / xfact 0 0 xoff \ + | 0 yfact 0 yoff | + | 0 0 zfact zoff | + \ 0 0 0 1 / + + where the offsets are calculated from the origin Point(x0, y0, z0): + + xoff = x0 - x0 * xfact + yoff = y0 - y0 * yfact + zoff = z0 - z0 * zfact + """ + if geom.is_empty: + return geom + x0, y0, z0 = interpret_origin(geom, origin, 3) + + # fmt: off + matrix = (xfact, 0.0, 0.0, + 0.0, yfact, 0.0, + 0.0, 0.0, zfact, + x0 - x0 * xfact, y0 - y0 * yfact, z0 - z0 * zfact) + # fmt: on + return affine_transform(geom, matrix) + + +def skew(geom, xs=0.0, ys=0.0, origin="center", use_radians=False): + r"""Return a skewed geometry, sheared by angles along x and y dimensions. + + The shear angle can be specified in either degrees (default) or radians + by setting ``use_radians=True``. + + The point of origin can be a keyword 'center' for the bounding box + center (default), 'centroid' for the geometry's centroid, a Point object + or a coordinate tuple (x0, y0). + + The general 2D affine transformation matrix for skewing is: + + / 1 tan(xs) xoff \ + | tan(ys) 1 yoff | + \ 0 0 1 / + + where the offsets are calculated from the origin Point(x0, y0): + + xoff = -y0 * tan(xs) + yoff = -x0 * tan(ys) + """ + if geom.is_empty: + return geom + if not use_radians: # convert from degrees + xs = xs * pi / 180.0 + ys = ys * pi / 180.0 + tanx = tan(xs) + tany = tan(ys) + if abs(tanx) < 2.5e-16: + tanx = 0.0 + if abs(tany) < 2.5e-16: + tany = 0.0 + x0, y0 = interpret_origin(geom, origin, 2) + + # fmt: off + matrix = (1.0, tanx, 0.0, + tany, 1.0, 0.0, + 0.0, 0.0, 1.0, + -y0 * tanx, -x0 * tany, 0.0) + # fmt: on + return affine_transform(geom, matrix) + + +def translate(geom, xoff=0.0, yoff=0.0, zoff=0.0): + r"""Return a translated geometry shifted by offsets along each dimension. + + The general 3D affine transformation matrix for translation is: + + / 1 0 0 xoff \ + | 0 1 0 yoff | + | 0 0 1 zoff | + \ 0 0 0 1 / + """ + if geom.is_empty: + return geom + + # fmt: off + matrix = (1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0, + xoff, yoff, zoff) + # fmt: on + return affine_transform(geom, matrix) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1d805901f3f8ba31a20a94647871d27638ec8a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__init__.py @@ -0,0 +1 @@ +"""Algorithms implemented in Shapely.""" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79f2771d8c34ea688620d22b5918a4a009e36312 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/_oriented_envelope.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/_oriented_envelope.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4a167c21cb143441e410b43729cb3033ef8fa20 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/_oriented_envelope.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/cga.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/cga.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd1a9787175389c6cce2a7c11bc000eeec830ef8 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/cga.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/polylabel.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/polylabel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfd83405951a4f194751880515bfa01772a2a098 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/__pycache__/polylabel.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/_oriented_envelope.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/_oriented_envelope.py new file mode 100644 index 0000000000000000000000000000000000000000..2e7ade75c9cff41d65d1ee5dbd3a8745f29ce0b7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/_oriented_envelope.py @@ -0,0 +1,56 @@ +import math +from itertools import islice + +import numpy as np + +import shapely +from shapely.affinity import affine_transform + + +def _oriented_envelope_min_area(geometry, **kwargs): + """Compute the oriented envelope (minimum rotated rectangle). + + This is a fallback implementation for GEOS < 3.12 to have the correct + minimum area behaviour. + """ + if geometry is None: + return None + if geometry.is_empty: + return shapely.from_wkt("POLYGON EMPTY") + + # first compute the convex hull + hull = geometry.convex_hull + try: + coords = hull.exterior.coords + except AttributeError: # may be a Point or a LineString + return hull + # generate the edge vectors between the convex hull's coords + edges = ( + (pt2[0] - pt1[0], pt2[1] - pt1[1]) + for pt1, pt2 in zip(coords, islice(coords, 1, None)) + ) + + def _transformed_rects(): + for dx, dy in edges: + # compute the normalized direction vector of the edge + # vector. + length = math.sqrt(dx**2 + dy**2) + ux, uy = dx / length, dy / length + # compute the normalized perpendicular vector + vx, vy = -uy, ux + # transform hull from the original coordinate system to + # the coordinate system defined by the edge and compute + # the axes-parallel bounding rectangle. + transf_rect = affine_transform(hull, (ux, uy, vx, vy, 0, 0)).envelope + # yield the transformed rectangle and a matrix to + # transform it back to the original coordinate system. + yield (transf_rect, (ux, vx, uy, vy, 0, 0)) + + # check for the minimum area rectangle and return it + transf_rect, inv_matrix = min(_transformed_rects(), key=lambda r: r[0].area) + return affine_transform(transf_rect, inv_matrix) + + +_oriented_envelope_min_area_vectorized = np.frompyfunc( + _oriented_envelope_min_area, 1, 1 +) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/cga.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/cga.py new file mode 100644 index 0000000000000000000000000000000000000000..1887c40cf9f845ccf9505e2b1d36e62f7e4d32b6 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/cga.py @@ -0,0 +1,50 @@ +"""Shapely CGA algorithms.""" + +import numpy as np + +import shapely + + +def signed_area(ring): + """Return the signed area enclosed by a ring in linear time. + + Algorithm used: https://web.archive.org/web/20080209143651/http://cgafaq.info:80/wiki/Polygon_Area + """ + coords = np.array(ring.coords)[:, :2] + xs, ys = np.vstack([coords, coords[1]]).T + return np.sum(xs[1:-1] * (ys[2:] - ys[:-2])) / 2.0 + + +def _reverse_conditioned(rings, condition): + """Return a copy of the rings potentially reversed depending on `condition`.""" + condition = np.asarray(condition) + if np.all(condition): + rings = shapely.reverse(rings) + elif np.any(condition): + rings = np.array(rings) + rings[condition] = shapely.reverse(rings[condition]) + return rings + + +def _orient_polygon(geometry, exterior_cw=False): + if geometry is None: + return None + if geometry.geom_type in ["MultiPolygon", "GeometryCollection"]: + return geometry.__class__( + [_orient_polygon(geom, exterior_cw) for geom in geometry.geoms] + ) + # elif geometry.geom_type in ["LinearRing"]: + # return reverse_conditioned(geometry, is_ccw(geometry) != ccw) + elif geometry.geom_type == "Polygon": + rings = np.array([geometry.exterior, *geometry.interiors]) + reverse_condition = shapely.is_ccw(rings) + reverse_condition[0] = not reverse_condition[0] + if exterior_cw: + reverse_condition = np.logical_not(reverse_condition) + if np.any(reverse_condition): + rings = _reverse_conditioned(rings, reverse_condition) + return geometry.__class__(rings[0], rings[1:]) + return geometry + + +_orient_polygons_vectorized = np.frompyfunc(_orient_polygon, nin=2, nout=1) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/polylabel.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/polylabel.py new file mode 100644 index 0000000000000000000000000000000000000000..c21ddd43e600b3851965b7dc7be4d465c59683bb --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/algorithms/polylabel.py @@ -0,0 +1,43 @@ +"""Provides functions for finding the pole of inaccessibility for a given polygon.""" + +from shapely._geometry import get_point +from shapely.constructive import maximum_inscribed_circle + + +def polylabel(polygon, tolerance=1.0): + """Find pole of inaccessibility for a given polygon. + + Based on Vladimir Agafonkin's https://github.com/mapbox/polylabel + + Parameters + ---------- + polygon : shapely.geometry.Polygon + Polygon for which to find the pole of inaccessibility. + tolerance : int or float, optional + `tolerance` represents the highest resolution in units of the + input geometry that will be considered for a solution. (default + value is 1.0). + + Returns + ------- + shapely.geometry.Point + A point representing the pole of inaccessibility for the given input + polygon. + + Raises + ------ + shapely.errors.TopologicalError + If the input polygon is not a valid geometry. + + Examples + -------- + >>> from shapely.ops import polylabel + >>> from shapely import LineString + >>> polygon = LineString([(0, 0), (50, 200), (100, 100), (20, 50), + ... (-100, -20), (-150, -200)]).buffer(100) + >>> polylabel(polygon, tolerance=0.001) + + + """ + line = maximum_inscribed_circle(polygon, tolerance) + return get_point(line, 0) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/conftest.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..a1180405ceb5601231fc5b5e67ffae4000161711 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/conftest.py @@ -0,0 +1,70 @@ +"""Pytest and scipy-doctest configuration for Shapely.""" + +import numpy +import pytest + +from shapely import geos_version_string + +try: + from scipy_doctest.conftest import dt_config + + HAVE_SCPDT = True +except ModuleNotFoundError: + HAVE_SCPDT = False + +shapely20_todo = pytest.mark.xfail( + strict=True, reason="Not yet implemented for Shapely 2.0" +) +shapely20_wontfix = pytest.mark.xfail(strict=True, reason="Will fail for Shapely 2.0") + + +def pytest_report_header(config): + """Header for pytest.""" + vers = [ + f"GEOS version: {geos_version_string}", + f"NumPy version: {numpy.__version__}", + ] + return "\n".join(vers) + + +if HAVE_SCPDT: + import doctest + import warnings + from contextlib import contextmanager + + @contextmanager + def warnings_errors_and_rng(test=None): + """Filter out some warnings.""" + depr_msgs = "|".join( + [ + # https://github.com/pyproj4/pyproj/issues/1468 + "Conversion of an array with ndim", + ] + ) + + runtime_msgs = "|".join( + [ + # https://github.com/libgeos/geos/pull/1226 + "invalid value encountered in coverage_union", + ] + ) + + with warnings.catch_warnings(): + if depr_msgs: + warnings.filterwarnings("ignore", depr_msgs, DeprecationWarning) + if runtime_msgs: + warnings.filterwarnings("ignore", runtime_msgs, RuntimeWarning) + yield + + # find and check doctests under this context manager + dt_config.user_context_mgr = warnings_errors_and_rng + + # relax all NumPy scalar type repr, e.g. `np.int32(0)` matches `0` + dt_config.strict_check = False + + dt_config.optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS + + # ignores are for things fail doctest collection (optionals etc) + dt_config.pytest_extra_ignore = [ + "shapely/geos.py", + ] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/constructive.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/constructive.py new file mode 100644 index 0000000000000000000000000000000000000000..bf97bb61afa4817f97609dc05e5853bea8246827 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/constructive.py @@ -0,0 +1,1552 @@ +"""Methods that yield new objects not derived from set-theoretic analysis.""" + +import numpy as np + +from shapely import lib +from shapely._enum import ParamEnum +from shapely.algorithms._oriented_envelope import _oriented_envelope_min_area_vectorized +from shapely.algorithms.cga import _orient_polygons_vectorized +from shapely.decorators import ( + deprecate_positional, + multithreading_enabled, + requires_geos, +) +from shapely.errors import UnsupportedGEOSVersionError + +__all__ = [ + "BufferCapStyle", + "BufferJoinStyle", + "boundary", + "buffer", + "build_area", + "centroid", + "clip_by_rect", + "concave_hull", + "constrained_delaunay_triangles", + "convex_hull", + "delaunay_triangles", + "envelope", + "extract_unique_points", + "make_valid", + "maximum_inscribed_circle", + "minimum_bounding_circle", + "minimum_clearance_line", + "minimum_rotated_rectangle", + "node", + "normalize", + "offset_curve", + "orient_polygons", + "oriented_envelope", + "point_on_surface", + "polygonize", + "polygonize_full", + "remove_repeated_points", + "reverse", + "segmentize", + "simplify", + "snap", + "voronoi_polygons", +] + + +class BufferCapStyle(ParamEnum): + """Enumeration of buffer cap styles. + + Attributes + ---------- + round : int + Represents a round cap style. + flat : int + Represents a flat cap style. + square : int + Represents a square cap style. + + """ + + round = 1 + flat = 2 + square = 3 + + +class BufferJoinStyle(ParamEnum): + """Enumeration of buffer join styles. + + Attributes + ---------- + round : int + Specifies a round join style. + mitre : int + Specifies a mitre join style. + bevel : int + Specifies a bevel join style. + + """ + + round = 1 + mitre = 2 + bevel = 3 + + +@multithreading_enabled +def boundary(geometry, **kwargs): + """Return the topological boundary of a geometry. + + This function will return None for geometrycollections. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry for which to return the boundary. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LinearRing, LineString, \ +MultiLineString, MultiPoint, Point, Polygon + >>> shapely.boundary(Point(0, 0)) + + >>> shapely.boundary(LineString([(0, 0), (1, 1), (1, 2)])) + + >>> shapely.boundary(LinearRing([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])) + + >>> shapely.boundary(Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])) + + >>> shapely.boundary(MultiPoint([(0, 0), (1, 2)])) + + >>> shapely.boundary(MultiLineString([[(0, 0), (1, 1)], [(0, 1), (1, 0)]])) + + >>> shapely.boundary(GeometryCollection([Point(0, 0)])) is None + True + + """ + return lib.boundary(geometry, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# buffer(geometry, distance, quad_segs=8, ...) +# shapely 2.1: shows deprecation warning about positional 'quad_segs', etc. +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'distance' +# buffer(geometry, distance, *, quad_segs=8, ...) + + +@deprecate_positional( + ["quad_segs", "cap_style", "join_style", "mitre_limit", "single_sided"], + category=DeprecationWarning, +) +@multithreading_enabled +def buffer( + geometry, + distance, + quad_segs=8, + cap_style="round", + join_style="round", + mitre_limit=5.0, + single_sided=False, + **kwargs, +): + """Compute the buffer of a geometry for positive and negative buffer distance. + + The buffer of a geometry is defined as the Minkowski sum (or difference, + for negative distance) of the geometry with a circle with radius equal + to the absolute value of the buffer distance. + + The buffer operation always returns a polygonal result. The negative + or zero-distance buffer of lines and points is always empty. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the buffer. + distance : float or array_like + Specifies the circle radius in the Minkowski sum (or difference). + quad_segs : int, default 8 + Specifies the number of linear segments in a quarter circle in the + approximation of circular arcs. + cap_style : shapely.BufferCapStyle or {'round', 'square', 'flat'}, default 'round' + Specifies the shape of buffered line endings. BufferCapStyle.round ('round') + results in circular line endings (see ``quad_segs``). Both BufferCapStyle.square + ('square') and BufferCapStyle.flat ('flat') result in rectangular line endings, + only BufferCapStyle.flat ('flat') will end at the original vertex, + while BufferCapStyle.square ('square') involves adding the buffer width. + join_style : shapely.BufferJoinStyle or {'round', 'mitre', 'bevel'}, default 'round' + Specifies the shape of buffered line midpoints. BufferJoinStyle.round ('round') + results in rounded shapes. BufferJoinStyle.bevel ('bevel') results in a beveled + edge that touches the original vertex. BufferJoinStyle.mitre ('mitre') results + in a single vertex that is beveled depending on the ``mitre_limit`` parameter. + mitre_limit : float, default 5.0 + Crops of 'mitre'-style joins if the point is displaced from the + buffered vertex by more than this limit. + single_sided : bool, default False + Only buffer at one side of the geometry. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``quad_segs``, ``cap_style``, + ``join_style``, ``mitre_limit`` or ``single_sided`` are + specified as positional arguments. In a future release, these will + need to be specified as keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon, BufferCapStyle, BufferJoinStyle + >>> shapely.buffer(Point(10, 10), 2, quad_segs=1) + + >>> shapely.buffer(Point(10, 10), 2, quad_segs=2) + + >>> shapely.buffer(Point(10, 10), -2, quad_segs=1) + + >>> line = LineString([(10, 10), (20, 10)]) + >>> shapely.buffer(line, 2, cap_style="square") + + >>> shapely.buffer(line, 2, cap_style="flat") + + >>> shapely.buffer(line, 2, single_sided=True, cap_style="flat") + + >>> line2 = LineString([(10, 10), (20, 10), (20, 20)]) + >>> shapely.buffer(line2, 2, cap_style="flat", join_style="bevel") + + >>> shapely.buffer(line2, 2, cap_style="flat", join_style="mitre") + + >>> shapely.buffer(line2, 2, cap_style="flat", join_style="mitre", mitre_limit=1) + + >>> square = Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]) + >>> shapely.buffer(square, 2, join_style="mitre") + + >>> shapely.buffer(square, -2, join_style="mitre") + + >>> shapely.buffer(square, -5, join_style="mitre") + + >>> shapely.buffer(line, float("nan")) is None + True + + """ + if isinstance(cap_style, str): + cap_style = BufferCapStyle.get_value(cap_style) + if isinstance(join_style, str): + join_style = BufferJoinStyle.get_value(join_style) + if not np.isscalar(quad_segs): + raise TypeError("quad_segs only accepts scalar values") + if not np.isscalar(cap_style): + raise TypeError("cap_style only accepts scalar values") + if not np.isscalar(join_style): + raise TypeError("join_style only accepts scalar values") + if not np.isscalar(mitre_limit): + raise TypeError("mitre_limit only accepts scalar values") + if not np.isscalar(single_sided): + raise TypeError("single_sided only accepts scalar values") + return lib.buffer( + geometry, + distance, + np.intc(quad_segs), + np.intc(cap_style), + np.intc(join_style), + mitre_limit, + np.bool_(single_sided), + **kwargs, + ) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# offset_curve(geometry, distance, quad_segs=8, ...) +# shapely 2.1: shows deprecation warning about positional 'quad_segs', etc. +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'distance' +# offset_curve(geometry, distance, *, quad_segs=8, ...) + + +@deprecate_positional( + ["quad_segs", "join_style", "mitre_limit"], category=DeprecationWarning +) +@multithreading_enabled +def offset_curve( + geometry, distance, quad_segs=8, join_style="round", mitre_limit=5.0, **kwargs +): + """Return a (Multi)LineString at a distance from the object. + + For positive distance the offset will be at the left side of the input + line. For a negative distance it will be at the right side. In general, + this function tries to preserve the direction of the input. + + Note: the behaviour regarding orientation of the resulting line depends + on the GEOS version. With GEOS < 3.11, the line retains the same + direction for a left offset (positive distance) or has opposite direction + for a right offset (negative distance), and this behaviour was documented + as such in previous Shapely versions. Starting with GEOS 3.11, the + function tries to preserve the orientation of the original line. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the offset. + distance : float or array_like + Specifies the offset distance from the input geometry. Negative + for right side offset, positive for left side offset. + quad_segs : int, default 8 + Specifies the number of linear segments in a quarter circle in the + approximation of circular arcs. + join_style : {'round', 'bevel', 'mitre'}, default 'round' + Specifies the shape of outside corners. 'round' results in + rounded shapes. 'bevel' results in a beveled edge that touches the + original vertex. 'mitre' results in a single vertex that is beveled + depending on the ``mitre_limit`` parameter. + mitre_limit : float, default 5.0 + Crops of 'mitre'-style joins if the point is displaced from the + buffered vertex by more than this limit. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``quad_segs``, ``join_style`` or + ``mitre_limit`` are specified as positional arguments. In a future + release, these will need to be specified as keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line = LineString([(0, 0), (0, 2)]) + >>> shapely.offset_curve(line, 2) + + >>> shapely.offset_curve(line, -2) + + + """ + if isinstance(join_style, str): + join_style = BufferJoinStyle.get_value(join_style) + if not np.isscalar(quad_segs): + raise TypeError("quad_segs only accepts scalar values") + if not np.isscalar(join_style): + raise TypeError("join_style only accepts scalar values") + if not np.isscalar(mitre_limit): + raise TypeError("mitre_limit only accepts scalar values") + return lib.offset_curve( + geometry, + distance, + np.intc(quad_segs), + np.intc(join_style), + np.double(mitre_limit), + **kwargs, + ) + + +@multithreading_enabled +def centroid(geometry, **kwargs): + """Compute the geometric center (center-of-mass) of a geometry. + + For multipoints this is computed as the mean of the input coordinates. + For multilinestrings the centroid is weighted by the length of each + line segment. For multipolygons the centroid is weighted by the area of + each polygon. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the centroid. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, MultiPoint, Polygon + >>> shapely.centroid(Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)])) + + >>> shapely.centroid(LineString([(0, 0), (2, 2), (10, 10)])) + + >>> shapely.centroid(MultiPoint([(0, 0), (10, 10)])) + + >>> shapely.centroid(Polygon()) + + + """ + return lib.centroid(geometry, **kwargs) + + +@multithreading_enabled +def clip_by_rect(geometry, xmin, ymin, xmax, ymax, **kwargs): + """Return the portion of a geometry within a rectangle. + + The geometry is clipped in a fast but possibly dirty way. The output is + not guaranteed to be valid. No exceptions will be raised for topological + errors. + + Note: empty geometries or geometries that do not overlap with the + specified bounds will result in GEOMETRYCOLLECTION EMPTY. + + Parameters + ---------- + geometry : Geometry or array_like + The geometry to be clipped. + xmin : float + Minimum x value of the rectangle. + ymin : float + Minimum y value of the rectangle. + xmax : float + Maximum x value of the rectangle. + ymax : float + Maximum y value of the rectangle. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Polygon + >>> line = LineString([(0, 0), (10, 10)]) + >>> shapely.clip_by_rect(line, 0., 0., 1., 1.) + + >>> polygon = Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]) + >>> shapely.clip_by_rect(polygon, 0., 0., 1., 1.) + + + """ + if not all(np.isscalar(val) for val in [xmin, ymin, xmax, ymax]): + raise TypeError("xmin/ymin/xmax/ymax only accepts scalar values") + return lib.clip_by_rect( + geometry, + np.double(xmin), + np.double(ymin), + np.double(xmax), + np.double(ymax), + **kwargs, + ) + + +@requires_geos("3.11.0") +@multithreading_enabled +def concave_hull(geometry, ratio=0.0, allow_holes=False, **kwargs): + """Compute a concave geometry that encloses an input geometry. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the concave hull. + ratio : float, default 0.0 + Number in the range [0, 1]. Higher numbers will include fewer vertices + in the hull. + allow_holes : bool, default False + If set to True, the concave hull may have holes. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPoint, Polygon + >>> multi_point = MultiPoint([(0, 0), (0, 3), (1, 1), (3, 0), (3, 3)]) + >>> shapely.concave_hull(multi_point, ratio=0.1) + + >>> shapely.concave_hull(multi_point, ratio=1.0) + + >>> shapely.concave_hull(Polygon()) + + + """ + if not np.isscalar(ratio): + raise TypeError("ratio must be scalar") + if not np.isscalar(allow_holes): + raise TypeError("allow_holes must be scalar") + return lib.concave_hull(geometry, np.double(ratio), np.bool_(allow_holes), **kwargs) + + +@multithreading_enabled +def convex_hull(geometry, **kwargs): + """Compute the minimum convex geometry that encloses an input geometry. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the convex hull. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPoint, Polygon + >>> shapely.convex_hull(MultiPoint([(0, 0), (10, 0), (10, 10)])) + + >>> shapely.convex_hull(Polygon()) + + + """ + return lib.convex_hull(geometry, **kwargs) + + +@multithreading_enabled +def delaunay_triangles(geometry, tolerance=0.0, only_edges=False, **kwargs): + """Compute a Delaunay triangulation around the vertices of an input geometry. + + The output is a geometrycollection containing polygons (default) + or linestrings (see ``only_edges``). Returns an empty geometry for input + geometries that contain less than 3 vertices. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the Delaunay triangulation. + tolerance : float or array_like, default 0.0 + Snap input vertices together if their distance is less than this value. + only_edges : bool or array_like, default False + If set to True, the triangulation will return a collection of + linestrings instead of polygons. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Returns + ------- + GeometryCollection or array of GeometryCollections + + See Also + -------- + constrained_delaunay_triangles + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, MultiPoint, Polygon + >>> points = MultiPoint([(50, 30), (60, 30), (100, 100)]) + >>> shapely.delaunay_triangles(points).normalize() + + >>> shapely.delaunay_triangles(points, only_edges=True) + + >>> shapely.delaunay_triangles( + ... MultiPoint([(50, 30), (51, 30), (60, 30), (100, 100)]), + ... tolerance=2 + ... ).normalize() + + >>> shapely.delaunay_triangles(Polygon([(50, 30), (60, 30), (100, 100), (50, 30)]))\ +.normalize() + + >>> shapely.delaunay_triangles(LineString([(50, 30), (60, 30), (100, 100)]))\ +.normalize() + + >>> shapely.delaunay_triangles(GeometryCollection([])) + + + """ + return lib.delaunay_triangles(geometry, tolerance, only_edges, **kwargs) + + +@requires_geos("3.10.0") +@multithreading_enabled +def constrained_delaunay_triangles(geometry, **kwargs): + """Compute the constrained Delaunay triangulation of polygons. + + A constrained Delaunay triangulation requires the edges of the input + polygon(s) to be in the set of resulting triangle edges. An unconstrained + delaunay triangulation only triangulates based on the vertices, hence + triangle edges could cross polygon boundaries. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometry : Geometry or array_like + **kwargs + For other keyword-only arguments, see the + `NumPy ufunc docs `_. + + Returns + ------- + GeometryCollection or array of GeometryCollections + * GeometryCollection of polygons, given polygonal input + * Empty GeometryCollection, given non-polygonal input + + See Also + -------- + delaunay_triangles + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPoint, MultiPolygon, Polygon + >>> shapely.constrained_delaunay_triangles(Polygon([(10, 10), (20, 40), (90, 90), (90, 10), (10, 10)])) + + >>> shapely.constrained_delaunay_triangles(Polygon()) + + >>> shapely.constrained_delaunay_triangles(MultiPolygon([Polygon(((50, 30), (60, 30), (100, 100), (50, 30))), Polygon(((10, 10), (20, 40), (90, 90), (90, 10), (10, 10)))])) + + >>> shapely.constrained_delaunay_triangles(MultiPolygon()) + + >>> shapely.constrained_delaunay_triangles(MultiPoint([(50, 30), (51, 30), (60, 30), (100, 100)])) + + + """ # noqa: E501 + return lib.constrained_delaunay_triangles(geometry, **kwargs) + + +@multithreading_enabled +def envelope(geometry, **kwargs): + """Compute the minimum bounding box that encloses an input geometry. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the envelope. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, MultiPoint, Point + >>> shapely.envelope(LineString([(0, 0), (10, 10)])) + + >>> shapely.envelope(MultiPoint([(0, 0), (10, 10)])) + + >>> shapely.envelope(Point(0, 0)) + + >>> shapely.envelope(GeometryCollection([])) + + + """ + return lib.envelope(geometry, **kwargs) + + +@multithreading_enabled +def extract_unique_points(geometry, **kwargs): + """Return all distinct vertices of an input geometry as a multipoint. + + Note that only 2 dimensions of the vertices are considered when testing + for equality. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to extract unique points. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, MultiPoint, Point, Polygon + >>> shapely.extract_unique_points(Point(0, 0)) + + >>> shapely.extract_unique_points(LineString([(0, 0), (1, 1), (1, 1)])) + + >>> shapely.extract_unique_points(Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])) + + >>> shapely.extract_unique_points(MultiPoint([(0, 0), (1, 1), (0, 0)])) + + >>> shapely.extract_unique_points(LineString()) + + + """ + return lib.extract_unique_points(geometry, **kwargs) + + +@multithreading_enabled +def build_area(geometry, **kwargs): + """Create an areal geometry formed by the constituent linework of given geometry. + + Equivalent of the PostGIS ST_BuildArea() function. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to build an area. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, Polygon + >>> polygon1 = Polygon([(0, 0), (3, 0), (3, 3), (0, 3), (0, 0)]) + >>> polygon2 = Polygon([(1, 1), (1, 2), (2, 2), (1, 1)]) + >>> shapely.build_area(GeometryCollection([polygon1, polygon2])) + + + """ + return lib.build_area(geometry, **kwargs) + + +@multithreading_enabled +def make_valid(geometry, *, method="linework", keep_collapsed=True, **kwargs): + """Repair invalid geometries. + + Two ``methods`` are available: + + * the 'linework' algorithm tries to preserve every edge and vertex in the input. It + combines all rings into a set of noded lines and then extracts valid polygons from + that linework. An alternating even-odd strategy is used to assign areas as + interior or exterior. A disadvantage is that for some relatively simple invalid + geometries this produces rather complex results. + * the 'structure' algorithm tries to reason from the structure of the input to find + the 'correct' repair: exterior rings bound area, interior holes exclude area. + It first makes all rings valid, then shells are merged and holes are subtracted + from the shells to generate valid result. It assumes that holes and shells are + correctly categorized in the input geometry. + + Example: + + .. plot:: code/make_valid_methods.py + + When using ``make_valid`` on a Polygon, the result can be a GeometryCollection. For + this example this is the case when the 'linework' ``method`` is used. LineStrings in + the result are drawn in red. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to repair. + method : {'linework', 'structure'}, default 'linework' + Algorithm to use when repairing geometry. 'structure' + requires GEOS >= 3.10. + + .. versionadded:: 2.1.0 + keep_collapsed : bool, default True + For the 'structure' method, True will keep components that have collapsed into a + lower dimensionality. For example, a ring collapsing to a line, or a line + collapsing to a point. Must be True for the 'linework' method. + + .. versionadded:: 2.1.0 + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> polygon = Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]) + >>> shapely.is_valid(polygon) + False + >>> shapely.make_valid(polygon) + + >>> shapely.make_valid(polygon, method="structure", keep_collapsed=True) + + >>> shapely.make_valid(polygon, method="structure", keep_collapsed=False) + + + """ + if not np.isscalar(method): + raise TypeError("method only accepts scalar values") + if not np.isscalar(keep_collapsed): + raise TypeError("keep_collapsed only accepts scalar values") + + if method == "linework": + if keep_collapsed is False: + raise ValueError( + "The 'linework' method does not support 'keep_collapsed=False'" + ) + + # The make_valid code can be removed once support for GEOS < 3.10 is dropped. + # In GEOS >= 3.10, make_valid just calls make_valid_with_params with + # method="linework" and keep_collapsed=True, so there is no advantage to keep + # both code paths in shapely on long term. + return lib.make_valid(geometry, **kwargs) + + elif method == "structure": + if lib.geos_version < (3, 10, 0): + raise ValueError( + "The 'structure' method is only available in GEOS >= 3.10.0" + ) + + return lib.make_valid_with_params( + geometry, np.intc(1), np.bool_(keep_collapsed), **kwargs + ) + + else: + raise ValueError(f"Unknown method: {method}") + + +@multithreading_enabled +def minimum_clearance_line(geometry, **kwargs): + """Return a LineString whose endpoints define the minimum clearance. + + A geometry's "minimum clearance" is the smallest distance by which a vertex + of the geometry could be moved to produce an invalid geometry. + + If the geometry has no minimum clearance, an empty LineString will be + returned. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to determine the minimum clearance line for. + **kwargs + For other keyword-only arguments, see the + `NumPy ufunc docs `_. + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> poly = Polygon([(0, 0), (10, 0), (10, 10), (5, 5), (0, 10), (0, 0)]) + >>> shapely.minimum_clearance_line(poly) + + + See Also + -------- + minimum_clearance + + """ + return lib.minimum_clearance_line(geometry, **kwargs) + + +@multithreading_enabled +def normalize(geometry, **kwargs): + """Convert Geometry to strict normal form (or canonical form). + + In :ref:`strict canonical form `, the coordinates, rings of + a polygon and parts of multi geometries are ordered consistently. Typically + useful for testing purposes (for example in combination with + ``equals_exact``). + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to normalize. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import MultiLineString + >>> line = MultiLineString([[(0, 0), (1, 1)], [(2, 2), (3, 3)]]) + >>> shapely.normalize(line) + + + """ + return lib.normalize(geometry, **kwargs) + + +@multithreading_enabled +def point_on_surface(geometry, **kwargs): + """Return a point that intersects an input geometry. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute a point on the surface. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, MultiPoint, Polygon + >>> shapely.point_on_surface(Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)])) + + >>> shapely.point_on_surface(LineString([(0, 0), (2, 2), (10, 10)])) + + >>> shapely.point_on_surface(MultiPoint([(0, 0), (10, 10)])) + + >>> shapely.point_on_surface(Polygon()) + + + """ + return lib.point_on_surface(geometry, **kwargs) + + +@multithreading_enabled +def node(geometry, **kwargs): + """Return the fully noded version of the linear input as MultiLineString. + + Given a linear input geometry, this function returns a new MultiLineString + in which no lines cross each other but only touch at and points. To + obtain this, all intersections between segments are computed and added + to the segments, and duplicate segments are removed. + + Non-linear input (points) will result in an empty MultiLineString. + + This function can for example be used to create a fully-noded linework + suitable to passed as input to ``polygonize``. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the noded version. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> line = LineString([(0, 0), (1,1), (0, 1), (1, 0)]) + >>> shapely.node(line) + + >>> shapely.node(Point(1, 1)) + + + """ + return lib.node(geometry, **kwargs) + + +def polygonize(geometries, **kwargs): + """Create polygons formed from the linework of a set of Geometries. + + Polygonizes an array of Geometries that contain linework which + represents the edges of a planar graph. Any type of Geometry may be + provided as input; only the constituent lines and rings will be used to + create the output polygons. + + Lines or rings that when combined do not completely close a polygon + will result in an empty GeometryCollection. Duplicate segments are + ignored. + + This function returns the polygons within a GeometryCollection. + Individual Polygons can be obtained using ``get_geometry`` to get + a single polygon or ``get_parts`` to get an array of polygons. + MultiPolygons can be constructed from the output using + ``shapely.multipolygons(shapely.get_parts(shapely.polygonize(geometries)))``. + + Parameters + ---------- + geometries : array_like + An array of geometries. + axis : int + Axis along which the geometries are polygonized. + The default is to perform a reduction over the last dimension + of the input array. A 1D array results in a scalar geometry. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Returns + ------- + GeometryCollection or array of GeometryCollections + + See Also + -------- + get_parts, get_geometry + polygonize_full + node + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> lines = [ + ... LineString([(0, 0), (1, 1)]), + ... LineString([(0, 0), (0, 1)]), + ... LineString([(0, 1), (1, 1)]) + ... ] + >>> shapely.polygonize(lines) + + + """ + return lib.polygonize(geometries, **kwargs) + + +def polygonize_full(geometries, **kwargs): + """Create polygons formed from the linework of a set of Geometries. + + All extra outputs are returned as well. + + Polygonizes an array of Geometries that contain linework which + represents the edges of a planar graph. Any type of Geometry may be + provided as input; only the constituent lines and rings will be used to + create the output polygons. + + This function performs the same polygonization as ``polygonize`` but does + not only return the polygonal result but all extra outputs as well. The + return value consists of 4 elements: + + * The polygonal valid output + * **Cut edges**: edges connected on both ends but not part of polygonal output + * **dangles**: edges connected on one end but not part of polygonal output + * **invalid rings**: polygons formed but which are not valid + + This function returns the geometries within GeometryCollections. + Individual geometries can be obtained using ``get_geometry`` to get + a single geometry or ``get_parts`` to get an array of geometries. + + Parameters + ---------- + geometries : array_like + An array of geometries. + axis : int + Axis along which the geometries are polygonized. + The default is to perform a reduction over the last dimension + of the input array. A 1D array results in a scalar geometry. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Returns + ------- + (polygons, cuts, dangles, invalid) + tuple of 4 GeometryCollections or arrays of GeometryCollections + + See Also + -------- + polygonize + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> lines = [ + ... LineString([(0, 0), (1, 1)]), + ... LineString([(0, 0), (0, 1), (1, 1)]), + ... LineString([(0, 1), (1, 1)]) + ... ] + >>> shapely.polygonize_full(lines) + (, + , + , + ) + + """ + return lib.polygonize_full(geometries, **kwargs) + + +@requires_geos("3.11.0") +@multithreading_enabled +def remove_repeated_points(geometry, tolerance=0.0, **kwargs): + """Return a copy of a Geometry with repeated points removed. + + From the start of the coordinate sequence, each next point within the + tolerance is removed. + + Removing repeated points with a non-zero tolerance may result in an invalid + geometry being returned. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to remove repeated points from. + tolerance : float or array_like, default=0.0 + Use 0.0 to remove only exactly repeated points. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Polygon + >>> shapely.remove_repeated_points(LineString([(0,0), (0,0), (1,0)]), tolerance=0) + + >>> shapely.remove_repeated_points(Polygon([(0, 0), (0, .5), (0, 1), (.5, 1), (0,0)]), tolerance=.5) + + + """ # noqa: E501 + return lib.remove_repeated_points(geometry, tolerance, **kwargs) + + +@multithreading_enabled +def reverse(geometry, **kwargs): + """Return a copy of a Geometry with the order of coordinates reversed. + + If a Geometry is a polygon with interior rings, the interior rings are also + reversed. + + Points are unchanged. None is returned where Geometry is None. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to reverse the coordinates of. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_ccw : Checks if a Geometry is clockwise. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Polygon + >>> shapely.reverse(LineString([(0, 0), (1, 2)])) + + >>> shapely.reverse(Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])) + + >>> shapely.reverse(None) is None + True + + """ + return lib.reverse(geometry, **kwargs) + + +@requires_geos("3.10.0") +@multithreading_enabled +def segmentize(geometry, max_segment_length, **kwargs): + """Add vertices to line segments based on maximum segment length. + + Additional vertices will be added to every line segment in an input geometry + so that segments are no longer than the provided maximum segment length. New + vertices will evenly subdivide each segment. + + Only linear components of input geometries are densified; other geometries + are returned unmodified. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to segmentize. + max_segment_length : float or array_like + Additional vertices will be added so that all line segments are no + longer than this value. Must be greater than 0. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Polygon + >>> line = LineString([(0, 0), (0, 10)]) + >>> shapely.segmentize(line, max_segment_length=5) + + >>> polygon = Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]) + >>> shapely.segmentize(polygon, max_segment_length=5) + + >>> shapely.segmentize(None, max_segment_length=5) is None + True + + """ + return lib.segmentize(geometry, max_segment_length, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# simplify(geometry, tolerance, preserve_topology=True, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'preserve_topology' +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'tolerance' +# simplify(geometry, tolerance, *, preserve_topology=True, **kwargs) + + +@deprecate_positional(["preserve_topology"], category=DeprecationWarning) +@multithreading_enabled +def simplify(geometry, tolerance, preserve_topology=True, **kwargs): + """Return a simplified version of an input geometry. + + The Douglas-Peucker algorithm is used to simplify the geometry. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to simplify. + tolerance : float or array_like + The maximum allowed geometry displacement. The higher this value, the + smaller the number of vertices in the resulting geometry. + preserve_topology : bool, default True + By default (True), the operation will avoid creating invalid + geometries (checking for collapses, ring-intersections, etc), but + this is computationally more expensive. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``preserve_topology`` is specified as + a positional argument. This will need to be specified as a keyword + argument in a future release. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Polygon + >>> line = LineString([(0, 0), (1, 10), (0, 20)]) + >>> shapely.simplify(line, tolerance=0.9) + + >>> shapely.simplify(line, tolerance=1) + + >>> polygon_with_hole = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]] + ... ) + >>> shapely.simplify(polygon_with_hole, tolerance=4, preserve_topology=True) + + >>> shapely.simplify(polygon_with_hole, tolerance=4, preserve_topology=False) + + + """ + if preserve_topology: + return lib.simplify_preserve_topology(geometry, tolerance, **kwargs) + else: + return lib.simplify(geometry, tolerance, **kwargs) + + +@multithreading_enabled +def snap(geometry, reference, tolerance, **kwargs): + """Snap the vertices and segments of the geometry to vertices of the reference. + + Vertices and segments of the input geometry are snapped to vertices of the + reference geometry, returning a new geometry; the input geometries are not + modified. The result geometry is the input geometry with the vertices and + segments snapped. If no snapping occurs then the input geometry is returned + unchanged. The tolerance is used to control where snapping is performed. + + Where possible, this operation tries to avoid creating invalid geometries; + however, it does not guarantee that output geometries will be valid. It is + the responsibility of the caller to check for and handle invalid geometries. + + Because too much snapping can result in invalid geometries being created, + heuristics are used to determine the number and location of snapped + vertices that are likely safe to snap. These heuristics may omit + some potential snaps that are otherwise within the tolerance. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to snap. + reference : Geometry or array_like + Geometry or geometries to snap to. + tolerance : float or array_like + The maximum distance between the input and reference geometries for + snapping to occur. A value of 0 will snap only identical points. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon, MultiPoint + + >>> point = Point(0.5, 2.5) + >>> target_point = Point(0, 2) + >>> shapely.snap(point, target_point, tolerance=1) + + >>> shapely.snap(point, target_point, tolerance=0.49) + + + >>> polygon = Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]) + >>> shapely.snap(polygon, Point(8, 10), tolerance=5) + + >>> shapely.snap(polygon, LineString([(8, 10), (8, 0)]), tolerance=5) + + + You can snap one line to another, for example to clean imprecise coordinates: + + >>> line1 = LineString([(0.1, 0.1), (0.49, 0.51), (1.01, 0.89)]) + >>> line2 = LineString([(0, 0), (0.5, 0.5), (1.0, 1.0)]) + >>> shapely.snap(line1, line2, 0.25) + + + Snapping also supports Z coordinates: + + >>> point1 = Point(0.1, 0.1, 0.5) + >>> multipoint = MultiPoint([(0, 0, 1), (0, 0, 0)]) + >>> shapely.snap(point1, multipoint, 1) + + + Snapping to an empty geometry has no effect: + + >>> shapely.snap(line1, LineString([]), 0.25) + + + Snapping to a non-geometry (None) will always return None: + + >>> shapely.snap(line1, None, 0.25) is None + True + + Only one vertex of a polygon is snapped to a target point, + even if all vertices are equidistant to it, + in order to prevent collapse of the polygon: + + >>> poly = shapely.box(0, 0, 1, 1) + >>> poly + + >>> shapely.snap(poly, Point(0.5, 0.5), 1) + + + """ + return lib.snap(geometry, reference, tolerance, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# voronoi_polygons(geometry, tolerance=0.0, extend_to=None, ...) +# shapely 2.1: shows deprecation warning about positional 'extend_to' +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'tolerance' +# voronoi_polygons(geometry, tolerance=0.0, extend_to=None, ...) + + +@deprecate_positional( + ["extend_to", "only_edges", "ordered"], category=DeprecationWarning +) +@multithreading_enabled +def voronoi_polygons( + geometry, tolerance=0.0, extend_to=None, only_edges=False, ordered=False, **kwargs +): + """Compute a Voronoi diagram from the vertices of an input geometry. + + The output is a geometrycollection containing polygons (default) + or linestrings (see only_edges). Returns empty if an input geometry + contains less than 2 vertices or if the provided extent has zero area. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the Voronoi diagram. + tolerance : float or array_like, default 0.0 + Snap input vertices together if their distance is less than this value. + extend_to : Geometry or array_like, optional + If provided, the diagram will be extended to cover the envelope of this + geometry (unless this envelope is smaller than the input geometry). + only_edges : bool or array_like, default False + If set to True, the triangulation will return a collection of + linestrings instead of polygons. + ordered : bool or array_like, default False + If set to True, polygons within the GeometryCollection will be ordered + according to the order of the input vertices. Note that this may slow + down the computation. Requires GEOS >= 3.12.0. + + .. versionadded:: 2.1.0 + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``extend_to``, ``only_edges`` or + ``ordered`` are specified as positional arguments. In a future + release, these will need to be specified as keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, MultiPoint, Point + >>> points = MultiPoint([(2, 2), (4, 2)]) + >>> shapely.voronoi_polygons(points).normalize() + + >>> shapely.voronoi_polygons(points, only_edges=True) + + >>> shapely.voronoi_polygons(MultiPoint([(2, 2), (4, 2), (4.2, 2)]), 0.5, only_edges=True) + + >>> shapely.voronoi_polygons(points, extend_to=LineString([(0, 0), (10, 10)]), only_edges=True) + + >>> shapely.voronoi_polygons(LineString([(2, 2), (4, 2)]), only_edges=True) + + >>> shapely.voronoi_polygons(Point(2, 2)) + + >>> shapely.voronoi_polygons(points, ordered=True) + + + """ # noqa: E501 + if ordered is not False and lib.geos_version < (3, 12, 0): + raise UnsupportedGEOSVersionError( + "Ordered Voronoi polygons require GEOS >= 3.12.0, " + f"found {lib.geos_version_string}" + ) + return lib.voronoi_polygons( + geometry, tolerance, extend_to, only_edges, ordered, **kwargs + ) + + +@multithreading_enabled +def _oriented_envelope_geos(geometry, **kwargs): + return lib.oriented_envelope(geometry, **kwargs) + + +def oriented_envelope(geometry, **kwargs): + """Compute the oriented envelope (minimum rotated rectangle) of the input geometry. + + The oriented envelope encloses an input geometry, such that the resulting + rectangle has minimum area. + + Unlike envelope this rectangle is not constrained to be parallel to the + coordinate axes. If the convex hull of the object is a degenerate (line + or point) this degenerate is returned. + + The starting point of the rectangle is not fixed. You can use + :func:`~shapely.normalize` to reorganize the rectangle to + :ref:`strict canonical form ` so the starting point is + always the lower left point. + + ``minimum_rotated_rectangle`` is an alias for ``oriented_envelope``. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the oriented envelope. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, MultiPoint, Point, Polygon + >>> shapely.oriented_envelope(MultiPoint([(0, 0), (10, 0), (10, 10)])).normalize() + + >>> shapely.oriented_envelope(LineString([(1, 1), (5, 1), (10, 10)])).normalize() + + >>> shapely.oriented_envelope(Polygon([(1, 1), (15, 1), (5, 10), (1, 1)]))\ +.normalize() + + >>> shapely.oriented_envelope(LineString([(1, 1), (10, 1)])).normalize() + + >>> shapely.oriented_envelope(Point(2, 2)) + + >>> shapely.oriented_envelope(GeometryCollection([])) + + + """ + if lib.geos_version < (3, 12, 0): + f = _oriented_envelope_min_area_vectorized + else: + f = _oriented_envelope_geos + return f(geometry, **kwargs) + + +minimum_rotated_rectangle = oriented_envelope + + +@multithreading_enabled +def minimum_bounding_circle(geometry, **kwargs): + """Compute the minimum bounding circle that encloses an input geometry. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the minimum bounding circle. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, MultiPoint, Point, Polygon + >>> shapely.minimum_bounding_circle( + ... Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]) + ... ) + + >>> shapely.minimum_bounding_circle(LineString([(1, 1), (10, 10)])) + + >>> shapely.minimum_bounding_circle(MultiPoint([(2, 2), (4, 2)])) + + >>> shapely.minimum_bounding_circle(Point(0, 1)) + + >>> shapely.minimum_bounding_circle(GeometryCollection([])) + + + See Also + -------- + minimum_bounding_radius, maximum_inscribed_circle + + """ + return lib.minimum_bounding_circle(geometry, **kwargs) + + +@multithreading_enabled +def maximum_inscribed_circle(geometry, tolerance=None, **kwargs): + """Find the largest circle that is fully contained within the input geometry. + + Constructs the "maximum inscribed circle" (MIC) for a polygonal geometry, + up to a specified tolerance. The MIC is determined by a point in the + interior of the area which has the farthest distance from the area + boundary, along with a boundary point at that distance. In the context of + geography the center of the MIC is known as the "pole of inaccessibility". + A cartographic use case is to determine a suitable point to place a map + label within a polygon. + The radius length of the MIC is a measure of how "narrow" a polygon is. + It is the distance at which the negative buffer becomes empty. + + The function supports polygons with holes and multipolygons. + + Returns a two-point linestring, with the first point at the center of the + inscribed circle and the second on the boundary of the inscribed circle. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometry : Geometry or array_like + tolerance : float or array_like, optional + Stop the algorithm when the search area is smaller than this tolerance. + When not specified, uses `max(width, height) / 1000` per geometry as + the default. + **kwargs + For other keyword-only arguments, see the + `NumPy ufunc docs `_. + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> poly = Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]) + >>> shapely.maximum_inscribed_circle(poly) + + + See Also + -------- + minimum_bounding_circle + """ + if tolerance is None: + tolerance = 0.0 + elif np.isscalar(tolerance) and tolerance < 0: + raise ValueError("'tolerance' should be positive") + return lib.maximum_inscribed_circle(geometry, tolerance, **kwargs) + + +@multithreading_enabled +def _orient_polygons_geos(geometry, exterior_cw=False, **kwargs): + return lib.orient_polygons(geometry, exterior_cw, **kwargs) + + +@multithreading_enabled +def orient_polygons(geometry, *, exterior_cw=False, **kwargs): + """Enforce a ring orientation on all polygonal elements in the input geometry. + + Forces (Multi)Polygons to use a counter-clockwise orientation for their + exterior ring, and a clockwise orientation for their interior rings (or + the oppposite if ``exterior_cw=True``). + + Also processes geometries inside a GeometryCollection in the same way. + Other geometries are returned unchanged. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to orient consistently. + exterior_cw : bool, default False + If True, exterior rings will be clockwise and interior rings + will be counter-clockwise. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + A polygon with both shell and hole having clockwise orientation: + + >>> from shapely import Polygon, orient_polygons + >>> polygon = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ... ) + >>> polygon + + + By default, the exterior ring is oriented counter-clockwise and + the holes clockwise: + + >>> orient_polygons(polygon) + + + Asking for the opposite orientation: + + >>> orient_polygons(polygon, exterior_cw=True) + + + """ + if lib.geos_version < (3, 12, 0): + f = _orient_polygons_vectorized + else: + f = _orient_polygons_geos + return f(geometry, exterior_cw, **kwargs) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/coordinates.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/coordinates.py new file mode 100644 index 0000000000000000000000000000000000000000..b4b429dee2d67259c49950541e47ba9a7ea957d4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/coordinates.py @@ -0,0 +1,335 @@ +"""Methods that operate on the coordinates of geometries.""" + +import numpy as np + +import shapely +from shapely import lib +from shapely.decorators import deprecate_positional + +__all__ = ["count_coordinates", "get_coordinates", "set_coordinates", "transform"] + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: only supported XY and XYZ geometries +# transform(geometry, transformation, include_z=False) +# shapely 2.1: shows deprecation warning about positional 'include_z' arg +# transform(geometry, transformation, include_z=False, *, interleaved=True) +# shapely 2.2(?): enforce keyword-only arguments after 'transformation' +# transform(geometry, transformation, *, include_z=False, interleaved=True) + + +@deprecate_positional(["include_z"], category=DeprecationWarning) +def transform( + geometry, + transformation, + include_z: bool | None = False, + *, + interleaved: bool = True, +): + """Apply a function to the coordinates of a geometry. + + With the default of ``include_z=False``, all returned geometries will be + two-dimensional; the third dimension will be discarded, if present. + When specifying ``include_z=True``, the returned geometries preserve + the dimensionality of the respective input geometries. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to transform. + transformation : function + A function that transforms a (N, 2) or (N, 3) ndarray of float64 to + another (N, 2) or (N, 3) ndarray of float64. + The function may not change N. + include_z : bool, optional, default False + If False, always return 2D geometries. + If True, the data being passed to the + transformation function will include the third dimension + (if a geometry has no third dimension, the z-coordinates + will be NaN). If None, will infer the dimensionality per + input geometry using ``has_z``, which may result in 2 calls to + the transformation function. Note that this inference + can be unreliable with empty geometries or NaN coordinates: for a + guaranteed result, it is recommended to specify ``include_z`` explicitly. + interleaved : bool, default True + If set to False, the transformation function should accept 2 or 3 separate + one-dimensional arrays (x, y and optional z) instead of a single + two-dimensional array. + + .. versionadded:: 2.1.0 + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``include_z`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + has_z + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.transform(Point(0, 0), lambda x: x + 1) + + >>> shapely.transform(LineString([(2, 2), (4, 4)]), lambda x: x * [2, 3]) + + >>> shapely.transform(None, lambda x: x) is None + True + >>> shapely.transform([Point(0, 0), None], lambda x: x).tolist() + [, None] + + The presence of a third dimension can be automatically detected, or + controlled explicitly: + + >>> shapely.transform(Point(0, 0, 0), lambda x: x + 1) + + >>> shapely.transform(Point(0, 0, 0), lambda x: x + 1, include_z=True) + + >>> shapely.transform(Point(0, 0, 0), lambda x: x + 1, include_z=None) + + + With interleaved=False, the call signature of the transformation is different: + + >>> shapely.transform(LineString([(1, 2), (3, 4)]), lambda x, y: (x + 1, y), \ +interleaved=False) + + + Or with a z coordinate: + + >>> shapely.transform(Point(0, 0, 0), lambda x, y, z: (x + 1, y, z + 2), \ +interleaved=False, include_z=True) + + + Using pyproj >= 2.1, the following example will reproject Shapely geometries + from EPSG 4326 to EPSG 32618: + + >>> from pyproj import Transformer + >>> transformer = Transformer.from_crs(4326, 32618, always_xy=True) + >>> shapely.transform(Point(-75, 50), transformer.transform, interleaved=False) + + + """ + geometry_arr = np.array(geometry, dtype=np.object_) # makes a copy + if include_z is None: + has_z = shapely.has_z(geometry_arr) + result = np.empty_like(geometry_arr) + result[has_z] = transform( + geometry_arr[has_z], transformation, include_z=True, interleaved=interleaved + ) + result[~has_z] = transform( + geometry_arr[~has_z], + transformation, + include_z=False, + interleaved=interleaved, + ) + else: + # TODO: expose include_m + include_m = False + coordinates = lib.get_coordinates(geometry_arr, include_z, include_m, False) + if interleaved: + new_coordinates = transformation(coordinates) + else: + new_coordinates = np.asarray( + transformation(*coordinates.T), dtype=np.float64 + ).T + # check the array to yield understandable error messages + if not isinstance(new_coordinates, np.ndarray) or new_coordinates.ndim != 2: + raise ValueError( + "The provided transformation did not return a two-dimensional numpy " + "array" + ) + if new_coordinates.dtype != np.float64: + raise ValueError( + "The provided transformation returned an array with an unexpected " + f"dtype ({new_coordinates.dtype})" + ) + if new_coordinates.shape != coordinates.shape: + # if the shape is too small we will get a segfault + raise ValueError( + "The provided transformation returned an array with an unexpected " + f"shape ({new_coordinates.shape})" + ) + result = lib.set_coordinates(geometry_arr, new_coordinates) + if result.ndim == 0 and not isinstance(geometry, np.ndarray): + return result.item() + return result + + +def count_coordinates(geometry): + """Count the number of coordinate pairs in a geometry array. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to count the coordinates of. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.count_coordinates(Point(0, 0)) + 1 + >>> shapely.count_coordinates(LineString([(2, 2), (4, 2)])) + 2 + >>> shapely.count_coordinates(None) + 0 + >>> shapely.count_coordinates([Point(0, 0), None]) + 1 + + """ + return lib.count_coordinates(np.asarray(geometry, dtype=np.object_)) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: only supported XY and XYZ geometries +# get_coordinates(geometry, include_z=False, return_index=False) +# shapely 2.1: shows deprecation warning about positional 'include_z' and 'return_index' +# get_coordinates(geometry, include_z=False, return_index=False, *, include_m=False) +# shapely 2.2(?): enforce keyword-only arguments after 'geometry' +# get_coordinates(geometry, *, include_z=False, include_m=False, return_index=False) + + +@deprecate_positional(["include_z", "return_index"], category=DeprecationWarning) +def get_coordinates(geometry, include_z=False, return_index=False, *, include_m=False): + """Get coordinates from a geometry array as an array of floats. + + The shape of the returned array is (N, 2), with N being the number of + coordinate pairs. The shape of the data may also be (N, 3) or (N, 4), + depending on ``include_z`` and ``include_m`` options. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to get the coordinates of. + include_z, include_m : bool, default False + If both are False, return XY (2D) geometries. + If both are True, return XYZM (4D) geometries. + If either are True, return XYZ or XYM (3D) geometries. + If a geometry has no Z or M dimension, extra coordinate data will be NaN. + + .. versionadded:: 2.1.0 + The ``include_m`` parameter was added to support XYM (3D) and + XYZM (4D) geometries available with GEOS 3.12.0 or later. + With older GEOS versions, M dimension coordinates will be NaN. + + return_index : bool, default False + If True, also return the index of each returned geometry as a separate + ndarray of integers. For multidimensional arrays, this indexes into the + flattened array (in C contiguous order). + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``include_z`` or ``return_index`` are + specified as positional arguments. In a future release, these will + need to be specified as keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.get_coordinates(Point(1, 2)).tolist() + [[1.0, 2.0]] + >>> shapely.get_coordinates(LineString([(2, 2), (4, 4)])).tolist() + [[2.0, 2.0], [4.0, 4.0]] + >>> shapely.get_coordinates(None) + array([], shape=(0, 2), dtype=float64) + + By default the third dimension is ignored: + + >>> shapely.get_coordinates(Point(1, 2, 3)).tolist() + [[1.0, 2.0]] + >>> shapely.get_coordinates(Point(1, 2, 3), include_z=True).tolist() + [[1.0, 2.0, 3.0]] + + If geometries don't have Z or M dimension, these values will be NaN: + + >>> pt = Point(1, 2) + >>> shapely.get_coordinates(pt, include_z=True).tolist() + [[1.0, 2.0, nan]] + >>> shapely.get_coordinates(pt, include_z=True, include_m=True).tolist() + [[1.0, 2.0, nan, nan]] + + When ``return_index=True``, indexes are returned also: + + >>> geometries = [LineString([(2, 2), (4, 4)]), Point(0, 0)] + >>> coordinates, index = shapely.get_coordinates(geometries, return_index=True) + >>> coordinates.tolist(), index.tolist() + ([[2.0, 2.0], [4.0, 4.0], [0.0, 0.0]], [0, 0, 1]) + + """ + return lib.get_coordinates( + np.asarray(geometry, dtype=np.object_), include_z, include_m, return_index + ) + + +def set_coordinates(geometry, coordinates): + """Adapts the coordinates of a geometry array in-place. + + If the coordinates array has shape (N, 2), all returned geometries + will be two-dimensional, and the third dimension will be discarded, + if present. If the coordinates array has shape (N, 3), the returned + geometries preserve the dimensionality of the input geometries. + + .. warning:: + + The geometry array is modified in-place! If you do not want to + modify the original array, you can do + ``set_coordinates(arr.copy(), newcoords)``. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to set the coordinates of. + coordinates: array_like + An array of coordinates to set. + + See Also + -------- + transform : Returns a copy of a geometry array with a function applied to its + coordinates. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.set_coordinates(Point(0, 0), [[1, 1]]) + + >>> shapely.set_coordinates( + ... [Point(0, 0), LineString([(0, 0), (0, 0)])], + ... [[1, 2], [3, 4], [5, 6]] + ... ).tolist() + [, ] + >>> shapely.set_coordinates([None, Point(0, 0)], [[1, 2]]).tolist() + [None, ] + + Third dimension of input geometry is discarded if coordinates array does + not include one: + + >>> shapely.set_coordinates(Point(0, 0, 0), [[1, 1]]) + + >>> shapely.set_coordinates(Point(0, 0, 0), [[1, 1, 1]]) + + + """ + geometry_arr = np.asarray(geometry, dtype=np.object_) + coordinates = np.atleast_2d(np.asarray(coordinates)).astype(np.float64) + if coordinates.ndim != 2: + raise ValueError( + f"The coordinate array should have dimension of 2 (has {coordinates.ndim})" + ) + n_coords = lib.count_coordinates(geometry_arr) + if (coordinates.shape[0] != n_coords) or (coordinates.shape[1] not in {2, 3}): + raise ValueError( + f"The coordinate array has an invalid shape {coordinates.shape}" + ) + lib.set_coordinates(geometry_arr, coordinates) + if geometry_arr.ndim == 0 and not isinstance(geometry, np.ndarray): + return geometry_arr.item() + return geometry_arr diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/coords.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/coords.py new file mode 100644 index 0000000000000000000000000000000000000000..146c966b9efdeacb9de1404ce53994d929a2319b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/coords.py @@ -0,0 +1,119 @@ +"""Coordinate sequence utilities.""" + +from array import array + + +class CoordinateSequence: + """Access to coordinate tuples from the parent geometry's coordinate sequence. + + Examples + -------- + >>> from shapely.wkt import loads + >>> g = loads('POINT (0.0 0.0)') + >>> list(g.coords) + [(0.0, 0.0)] + >>> g = loads('POINT M (1 2 4)') + >>> g.coords[:] + [(1.0, 2.0, 4.0)] + + """ + + def __init__(self, coords): + """Initialize the CoordinateSequence. + + Parameters + ---------- + coords : array + The coordinate array. + + """ + self._coords = coords + + def __len__(self): + """Return the length of the CoordinateSequence. + + Returns + ------- + int + The length of the CoordinateSequence. + + """ + return self._coords.shape[0] + + def __iter__(self): + """Iterate over the CoordinateSequence.""" + for i in range(self.__len__()): + yield tuple(self._coords[i].tolist()) + + def __getitem__(self, key): + """Get the item at the specified index or slice. + + Parameters + ---------- + key : int or slice + The index or slice. + + Returns + ------- + tuple or list + The item at the specified index or slice. + + """ + m = self.__len__() + if isinstance(key, int): + if key + m < 0 or key >= m: + raise IndexError("index out of range") + if key < 0: + i = m + key + else: + i = key + return tuple(self._coords[i].tolist()) + elif isinstance(key, slice): + res = [] + start, stop, stride = key.indices(m) + for i in range(start, stop, stride): + res.append(tuple(self._coords[i].tolist())) + return res + else: + raise TypeError("key must be an index or slice") + + def __array__(self, dtype=None, copy=None): + """Return a copy of the coordinate array. + + Parameters + ---------- + dtype : data-type, optional + The desired data-type for the array. + copy : bool, optional + If None (default) or True, a copy of the array is always returned. + If False, a ValueError is raised as this is not supported. + + Returns + ------- + array + The coordinate array. + + Raises + ------ + ValueError + If `copy=False` is specified. + + """ + if copy is False: + raise ValueError("`copy=False` isn't supported. A copy is always created.") + elif copy is True: + return self._coords.copy() + else: + return self._coords + + @property + def xy(self): + """X and Y arrays.""" + m = self.__len__() + x = array("d") + y = array("d") + for i in range(m): + xy = self._coords[i].tolist() + x.append(xy[0]) + y.append(xy[1]) + return x, y diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/creation.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/creation.py new file mode 100644 index 0000000000000000000000000000000000000000..953eb4a4296c4d22b33d4e93884412a23842cd04 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/creation.py @@ -0,0 +1,831 @@ +"""Methods to create geometries.""" + +import numpy as np + +from shapely import Geometry, GeometryType, lib +from shapely._enum import ParamEnum +from shapely._geometry_helpers import collections_1d, simple_geometries_1d +from shapely.decorators import deprecate_positional, multithreading_enabled +from shapely.io import from_wkt + +__all__ = [ + "box", + "destroy_prepared", + "empty", + "geometrycollections", + "linearrings", + "linestrings", + "multilinestrings", + "multipoints", + "multipolygons", + "points", + "polygons", + "prepare", +] + + +class HandleNaN(ParamEnum): + allow = 0 + skip = 1 + error = 2 + + +def _xyz_to_coords(x, y, z): + if y is None: + return x + if z is None: + coords = np.broadcast_arrays(x, y) + else: + coords = np.broadcast_arrays(x, y, z) + return np.stack(coords, axis=-1) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# points(coords, y=None, z=None, indices=None, out=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'indices' arg +# points(coords, y=None, z=None, indices=None, *, handle_nan=HandleNaN.allow, out=None, **kwargs) # noqa: E501 +# shapely 2.2(?): enforce keyword-only arguments after 'z' +# points(coords, y=None, z=None, *, indices=None, handle_nan=HandleNaN.allow, out=None, **kwargs) # noqa: E501 + + +@deprecate_positional(["indices"], category=DeprecationWarning) +@multithreading_enabled +def points( + coords, + y=None, + z=None, + indices=None, + *, + handle_nan=HandleNaN.allow, + out=None, + **kwargs, +): + """Create an array of points. + + Parameters + ---------- + coords : array_like + An array of coordinate tuples (2- or 3-dimensional) or, if ``y`` is + provided, an array of x coordinates. + y : array_like, optional + An array of y coordinates. + z : array_like, optional + An array of z coordinates. + indices : array_like, optional + Indices into the target array where input coordinates belong. If + provided, the coords should be 2D with shape (N, 2) or (N, 3) and + indices should be an array of shape (N,) with integers in increasing + order. Missing indices result in a ValueError unless ``out`` is + provided, in which case the original value in ``out`` is kept. + handle_nan : shapely.HandleNaN or {'allow', 'skip', 'error'}, default 'allow' + Specifies what to do when a NaN or Inf is encountered in the coordinates: + + - 'allow': the geometries are created with NaN or Inf coordinates. + Note that this can result in unexpected behaviour in subsequent + operations, and generally it is discouraged to have non-finite + coordinate values. One can use this option if you know all + coordinates are finite and want to avoid the overhead of checking + for this. + - 'skip': if any of x, y or z values are NaN or Inf, an empty point + will be created. + - 'error': if any NaN or Inf is detected in the coordinates, a ValueError + is raised. This option ensures that the created geometries have all + finite coordinate values. + + .. versionadded:: 2.1.0 + out : ndarray, optional + An array (with dtype object) to output the geometries into. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + Ignored if ``indices`` is provided. + + Examples + -------- + >>> import shapely + >>> shapely.points([[0, 1], [4, 5]]).tolist() + [, ] + >>> shapely.points([0, 1, 2]) + + + Notes + ----- + - GEOS 3.10, 3.11 and 3.12 automatically converts POINT (nan nan) to POINT EMPTY. + - GEOS 3.10 and 3.11 will transform a 3D point to 2D if its Z coordinate is NaN. + - Usage of the ``y`` and ``z`` arguments will prevents lazy evaluation in + ``dask``. Instead provide the coordinates as an array with shape + ``(..., 2)`` or ``(..., 3)`` using only the ``coords`` argument. + + """ + coords = _xyz_to_coords(coords, y, z) + if isinstance(handle_nan, str): + handle_nan = HandleNaN.get_value(handle_nan) + if indices is None: + return lib.points(coords, np.intc(handle_nan), out=out, **kwargs) + else: + return simple_geometries_1d( + coords, indices, GeometryType.POINT, handle_nan=handle_nan, out=out + ) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# linestrings(coords, y=None, z=None, indices=None, out=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'indices' arg +# linestrings(coords, y=None, z=None, indices=None, *, handle_nan=HandleNaN.allow, out=None, **kwargs) # noqa: E501 +# shapely 2.2(?): enforce keyword-only arguments after 'z' +# linestrings(coords, y=None, z=None, *, indices=None, handle_nan=HandleNaN.allow, out=None, **kwargs) # noqa: E501 + + +@deprecate_positional(["indices"], category=DeprecationWarning) +@multithreading_enabled +def linestrings( + coords, + y=None, + z=None, + indices=None, + *, + handle_nan=HandleNaN.allow, + out=None, + **kwargs, +): + """Create an array of linestrings. + + This function will raise an exception if a linestring contains less than + two points. + + Parameters + ---------- + coords : array_like + An array of lists of coordinate tuples (2- or 3-dimensional) or, if ``y`` + is provided, an array of lists of x coordinates. + y : array_like, optional + An array of y coordinates. + z : array_like, optional + An array of z coordinates. + indices : array_like, optional + Indices into the target array where input coordinates belong. If + provided, the coords should be 2D with shape (N, 2) or (N, 3) and + indices should be an array of shape (N,) with integers in increasing + order. Missing indices result in a ValueError unless ``out`` is + provided, in which case the original value in ``out`` is kept. + handle_nan : shapely.HandleNaN or {'allow', 'skip', 'error'}, default 'allow' + Specifies what to do when a NaN or Inf is encountered in the coordinates: + + - 'allow': the geometries are created with NaN or Inf coordinates. + Note that this can result in unexpected behaviour in subsequent + operations, and generally it is discouraged to have non-finite + coordinate values. One can use this option if you know all + coordinates are finite and want to avoid the overhead of checking + for this. + - 'skip': the coordinate pairs where any of x, y or z values are + NaN or Inf are ignored. If this results in ignoring all coordinates + for one geometry, an empty geometry is created. + - 'error': if any NaN or Inf is detected in the coordinates, a ValueError + is raised. This option ensures that the created geometries have all + finite coordinate values. + + .. versionadded:: 2.1.0 + + out : ndarray, optional + An array (with dtype object) to output the geometries into. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + Ignored if ``indices`` is provided. + + Examples + -------- + >>> import shapely + >>> shapely.linestrings([[[0, 1], [4, 5]], [[2, 3], [5, 6]]]).tolist() + [, ] + >>> shapely.linestrings( + ... [[0, 1], [4, 5], [2, 3], [5, 6], [7, 8]], + ... indices=[0, 0, 1, 1, 1] + ... ).tolist() + [, ] + + Notes + ----- + - Usage of the ``y`` and ``z`` arguments will prevents lazy evaluation in + ``dask``. Instead provide the coordinates as a ``(..., 2)`` or + ``(..., 3)`` array using only ``coords``. + + """ + coords = _xyz_to_coords(coords, y, z) + if isinstance(handle_nan, str): + handle_nan = HandleNaN.get_value(handle_nan) + if indices is None: + return lib.linestrings(coords, np.intc(handle_nan), out=out, **kwargs) + else: + return simple_geometries_1d( + coords, indices, GeometryType.LINESTRING, handle_nan=handle_nan, out=out + ) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# linearrings(coords, y=None, z=None, indices=None, out=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'indices' arg +# linearrings(coords, y=None, z=None, indices=None, *, handle_nan=HandleNaN.allow, out=None, **kwargs) # noqa: E501 +# shapely 2.2(?): enforce keyword-only arguments after 'z' +# linearrings(coords, y=None, z=None, *, indices=None, handle_nan=HandleNaN.allow, out=None, **kwargs) # noqa: E501 + + +@deprecate_positional(["indices"], category=DeprecationWarning) +@multithreading_enabled +def linearrings( + coords, + y=None, + z=None, + indices=None, + *, + handle_nan=HandleNaN.allow, + out=None, + **kwargs, +): + """Create an array of linearrings. + + If the provided coords do not constitute a closed linestring, or if there + are only 3 provided coords, the first + coordinate is duplicated at the end to close the ring. This function will + raise an exception if a linearring contains less than three points or if + the terminal coordinates contain NaN (not-a-number). + + Parameters + ---------- + coords : array_like + An array of lists of coordinate tuples (2- or 3-dimensional) or, if ``y`` + is provided, an array of lists of x coordinates + y : array_like, optional + An array of y coordinates. + z : array_like, optional + An array of z coordinates. + indices : array_like, optional + Indices into the target array where input coordinates belong. If + provided, the coords should be 2D with shape (N, 2) or (N, 3) and + indices should be an array of shape (N,) with integers in increasing + order. Missing indices result in a ValueError unless ``out`` is + provided, in which case the original value in ``out`` is kept. + handle_nan : shapely.HandleNaN or {'allow', 'skip', 'error'}, default 'allow' + Specifies what to do when a NaN or Inf is encountered in the coordinates: + + - 'allow': the geometries are created with NaN or Inf coordinates. + Note that this can result in unexpected behaviour in subsequent + operations, and generally it is discouraged to have non-finite + coordinate values. One can use this option if you know all + coordinates are finite and want to avoid the overhead of checking + for this. + - 'skip': the coordinate pairs where any of x, y or z values are + NaN or Inf are ignored. If this results in ignoring all coordinates + for one geometry, an empty geometry is created. + - 'error': if any NaN or Inf is detected in the coordinates, a ValueError + is raised. This option ensures that the created geometries have all + finite coordinate values. + + .. versionadded:: 2.1.0 + + out : ndarray, optional + An array (with dtype object) to output the geometries into. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + Ignored if ``indices`` is provided. + + See Also + -------- + linestrings + + Examples + -------- + >>> import shapely + >>> shapely.linearrings([[0, 0], [0, 1], [1, 1], [0, 0]]) + + >>> shapely.linearrings([[0, 0], [0, 1], [1, 1]]) + + + Notes + ----- + - Usage of the ``y`` and ``z`` arguments will prevents lazy evaluation in + ``dask``. Instead provide the coordinates as a ``(..., 2)`` or + ``(..., 3)`` array using only ``coords``. + + """ + coords = _xyz_to_coords(coords, y, z) + if isinstance(handle_nan, str): + handle_nan = HandleNaN.get_value(handle_nan) + if indices is None: + return lib.linearrings(coords, np.intc(handle_nan), out=out, **kwargs) + else: + return simple_geometries_1d( + coords, indices, GeometryType.LINEARRING, handle_nan=handle_nan, out=out + ) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# polygons(geometries, holes=None, indices=None, out=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'indices' arg +# polygons(geometries, holes=None, indices=None, *, out=None, **kwargs) +# shapely 2.2(?): enforce keyword-only arguments after 'holes' +# polygons(geometries, holes=None, *, indices=None, out=None, **kwargs) + + +@deprecate_positional(["indices"], category=DeprecationWarning) +@multithreading_enabled +def polygons(geometries, holes=None, indices=None, *, out=None, **kwargs): + """Create an array of polygons. + + Parameters + ---------- + geometries : array_like + An array of linearrings or coordinates (see linearrings). + Unless ``indices`` are given (see description below), this + include the outer shells only. The ``holes`` argument should be used + to create polygons with holes. + holes : array_like, optional + An array of lists of linearrings that constitute holes for each shell. + Not to be used in combination with ``indices``. + indices : array_like, optional + Indices into the target array where input geometries belong. If + provided, the holes are expected to be present inside ``geometries``; + the first geometry for each index is the outer shell + and all subsequent geometries in that index are the holes. + Both geometries and indices should be 1D and have matching sizes. + Indices should be in increasing order. Missing indices result in a + ValueError unless ``out`` is provided, in which case the original value + in ``out`` is kept. + out : ndarray, optional + An array (with dtype object) to output the geometries into. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + Ignored if ``indices`` is provided. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``indices`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + Examples + -------- + >>> import shapely + + Polygons are constructed from rings: + + >>> ring_1 = shapely.linearrings([[0, 0], [0, 10], [10, 10], [10, 0]]) + >>> ring_2 = shapely.linearrings([[2, 6], [2, 7], [3, 7], [3, 6]]) + >>> shapely.polygons([ring_1, ring_2])[0] + + >>> shapely.polygons([ring_1, ring_2])[1] + + + Or from coordinates directly: + + >>> shapely.polygons([[0, 0], [0, 10], [10, 10], [10, 0]]) + + + Adding holes can be done using the ``holes`` keyword argument: + + >>> shapely.polygons(ring_1, holes=[ring_2]) + + + Or using the ``indices`` argument: + + >>> shapely.polygons([ring_1, ring_2], indices=[0, 1])[0] + + >>> shapely.polygons([ring_1, ring_2], indices=[0, 1])[1] + + >>> shapely.polygons([ring_1, ring_2], indices=[0, 0])[0] + + + Missing input values (``None``) are skipped and may result in an + empty polygon: + + >>> shapely.polygons(None) + + >>> shapely.polygons(ring_1, holes=[None]) + + >>> shapely.polygons([ring_1, None], indices=[0, 0])[0] + + + """ + geometries = np.asarray(geometries) + if not isinstance(geometries, Geometry) and np.issubdtype( + geometries.dtype, np.number + ): + geometries = linearrings(geometries) + + if indices is not None: + if holes is not None: + raise TypeError("Cannot specify separate holes array when using indices.") + return collections_1d(geometries, indices, GeometryType.POLYGON, out=out) + + if holes is None: + # no holes provided: initialize an empty holes array matching shells + shape = geometries.shape + (0,) if isinstance(geometries, np.ndarray) else (0,) + holes = np.empty(shape, dtype=object) + else: + holes = np.asarray(holes) + # convert holes coordinates into linearrings + if np.issubdtype(holes.dtype, np.number): + holes = linearrings(holes) + + return lib.polygons(geometries, holes, out=out, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# box(xmin, ymin, xmax, ymax, ccw=True, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'ccw' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'ymax' +# box(xmin, ymin, xmax, ymax, *, ccw=True, **kwargs) + + +@deprecate_positional(["ccw"], category=DeprecationWarning) +@multithreading_enabled +def box(xmin, ymin, xmax, ymax, ccw=True, **kwargs): + """Create box polygons. + + Parameters + ---------- + xmin : float or array_like + Float or array of minimum x coordinates. + ymin : float or array_like + Float or array of minimum y coordinates. + xmax : float or array_like + Float or array of maximum x coordinates. + ymax : float or array_like + Float or array of maximum y coordinates. + ccw : bool, default True + If True, box will be created in counterclockwise direction starting + from bottom right coordinate (xmax, ymin). + If False, box will be created in clockwise direction starting from + bottom left coordinate (xmin, ymin). + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``ccw`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + Examples + -------- + >>> import shapely + >>> shapely.box(0, 0, 1, 1) + + >>> shapely.box(0, 0, 1, 1, ccw=False) + + + """ + return lib.box(xmin, ymin, xmax, ymax, ccw, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# multipoints(geometries, indices=None, out=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'indices' arg +# multipoints(geometries, indices=None, *, out=None, **kwargs) +# shapely 2.2(?): enforce keyword-only arguments after 'indices' +# multipoints(geometries, *, indices=None, out=None, **kwargs) + + +@deprecate_positional(["indices"], category=DeprecationWarning) +@multithreading_enabled +def multipoints(geometries, indices=None, *, out=None, **kwargs): + """Create multipoints from arrays of points. + + Parameters + ---------- + geometries : array_like + An array of points or coordinates (see points). + indices : array_like, optional + Indices into the target array where input geometries belong. If + provided, both geometries and indices should be 1D and have matching + sizes. Indices should be in increasing order. Missing indices result + in a ValueError unless ``out`` is provided, in which case the original + value in ``out`` is kept. + out : ndarray, optional + An array (with dtype object) to output the geometries into. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + Ignored if ``indices`` is provided. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``indices`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + Examples + -------- + >>> import shapely + + Multipoints are constructed from points: + + >>> point_1 = shapely.points([1, 1]) + >>> point_2 = shapely.points([2, 2]) + >>> shapely.multipoints([point_1, point_2]) + + >>> shapely.multipoints([[point_1, point_2], [point_2, None]]).tolist() + [, ] + + Or from coordinates directly: + + >>> shapely.multipoints([[0, 0], [2, 2], [3, 3]]) + + + Multiple multipoints of different sizes can be constructed efficiently using the + ``indices`` keyword argument: + + >>> shapely.multipoints([point_1, point_2, point_2], indices=[0, 0, 1]).tolist() + [, ] + + Missing input values (``None``) are skipped and may result in an + empty multipoint: + + >>> shapely.multipoints([None]) + + >>> shapely.multipoints([point_1, None], indices=[0, 0]).tolist() + [] + >>> shapely.multipoints([point_1, None], indices=[0, 1]).tolist() + [, ] + + """ + typ = GeometryType.MULTIPOINT + geometries = np.asarray(geometries) + if not isinstance(geometries, Geometry) and np.issubdtype( + geometries.dtype, np.number + ): + geometries = points(geometries) + if indices is None: + return lib.create_collection(geometries, np.intc(typ), out=out, **kwargs) + else: + return collections_1d(geometries, indices, typ, out=out) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# multilinestrings(geometries, indices=None, out=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'indices' arg +# multilinestrings(geometries, indices=None, *, out=None, **kwargs) +# shapely 2.2(?): enforce keyword-only arguments after 'indices' +# multilinestrings(geometries, *, indices=None, out=None, **kwargs) + + +@deprecate_positional(["indices"], category=DeprecationWarning) +@multithreading_enabled +def multilinestrings(geometries, indices=None, *, out=None, **kwargs): + """Create multilinestrings from arrays of linestrings. + + Parameters + ---------- + geometries : array_like + An array of linestrings or coordinates (see linestrings). + indices : array_like, optional + Indices into the target array where input geometries belong. If + provided, both geometries and indices should be 1D and have matching + sizes. Indices should be in increasing order. Missing indices result + in a ValueError unless ``out`` is provided, in which case the original + value in ``out`` is kept. + out : ndarray, optional + An array (with dtype object) to output the geometries into. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + Ignored if ``indices`` is provided. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``indices`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + multipoints + + """ + typ = GeometryType.MULTILINESTRING + geometries = np.asarray(geometries) + if not isinstance(geometries, Geometry) and np.issubdtype( + geometries.dtype, np.number + ): + geometries = linestrings(geometries) + + if indices is None: + return lib.create_collection(geometries, np.intc(typ), out=out, **kwargs) + else: + return collections_1d(geometries, indices, typ, out=out) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# multipolygons(geometries, indices=None, out=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'indices' arg +# multipolygons(geometries, indices=None, *, out=None, **kwargs) +# shapely 2.2(?): enforce keyword-only arguments after 'indices' +# multipolygons(geometries, *, indices=None, out=None, **kwargs) + + +@deprecate_positional(["indices"], category=DeprecationWarning) +@multithreading_enabled +def multipolygons(geometries, indices=None, *, out=None, **kwargs): + """Create multipolygons from arrays of polygons. + + Parameters + ---------- + geometries : array_like + An array of polygons or coordinates (see polygons). + indices : array_like, optional + Indices into the target array where input geometries belong. If + provided, both geometries and indices should be 1D and have matching + sizes. Indices should be in increasing order. Missing indices result + in a ValueError unless ``out`` is provided, in which case the original + value in ``out`` is kept. + out : ndarray, optional + An array (with dtype object) to output the geometries into. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + Ignored if ``indices`` is provided. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``indices`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + multipoints + + """ + typ = GeometryType.MULTIPOLYGON + geometries = np.asarray(geometries) + if not isinstance(geometries, Geometry) and np.issubdtype( + geometries.dtype, np.number + ): + geometries = polygons(geometries) + if indices is None: + return lib.create_collection(geometries, np.intc(typ), out=out, **kwargs) + else: + return collections_1d(geometries, indices, typ, out=out) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# geometrycollections(geometries, indices=None, out=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'indices' arg +# geometrycollections(geometries, indices=None, *, out=None, **kwargs) +# shapely 2.2(?): enforce keyword-only arguments after 'indices' +# geometrycollections(geometries, *, indices=None, out=None, **kwargs) + + +@deprecate_positional(["indices"], category=DeprecationWarning) +@multithreading_enabled +def geometrycollections(geometries, indices=None, out=None, **kwargs): + """Create geometrycollections from arrays of geometries. + + Parameters + ---------- + geometries : array_like + An array of geometries. + indices : array_like, optional + Indices into the target array where input geometries belong. If + provided, both geometries and indices should be 1D and have matching + sizes. Indices should be in increasing order. Missing indices result + in a ValueError unless ``out`` is provided, in which case the original + value in ``out`` is kept. + out : ndarray, optional + An array (with dtype object) to output the geometries into. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + Ignored if ``indices`` is provided. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``indices`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + multipoints + + """ + typ = GeometryType.GEOMETRYCOLLECTION + if indices is None: + return lib.create_collection(geometries, np.intc(typ), out=out, **kwargs) + else: + return collections_1d(geometries, indices, typ, out=out) + + +def prepare(geometry, **kwargs): + """Prepare a geometry, improving performance of other operations. + + A prepared geometry is a normal geometry with added information such as an + index on the line segments. This improves the performance of the following + operations: contains, contains_properly, covered_by, covers, crosses, + disjoint, intersects, overlaps, touches, and within. + + Note that if a prepared geometry is modified, the newly created Geometry + object is not prepared. In that case, ``prepare`` should be called again. + + This function does not recompute previously prepared geometries; + it is efficient to call this function on an array that partially contains + prepared geometries. + + This function does not return any values; geometries are modified in place. + + Parameters + ---------- + geometry : Geometry or array_like + Geometries are changed in place + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_prepared : Identify whether a geometry is prepared already. + destroy_prepared : Destroy the prepared part of a geometry. + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> poly = shapely.buffer(Point(1.0, 1.0), 1) + >>> shapely.prepare(poly) + >>> shapely.contains_properly(poly, [Point(0.0, 0.0), Point(0.5, 0.5)]).tolist() + [False, True] + + """ + lib.prepare(geometry, **kwargs) + + +def destroy_prepared(geometry, **kwargs): + """Destroy the prepared part of a geometry, freeing up memory. + + Note that the prepared geometry will always be cleaned up if the geometry itself + is dereferenced. This function needs only be called in very specific circumstances, + such as freeing up memory without losing the geometries, or benchmarking. + + Parameters + ---------- + geometry : Geometry or array_like + Geometries are changed in-place + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + prepare + + """ + lib.destroy_prepared(geometry, **kwargs) + + +def empty(shape, geom_type=None, order="C"): + """Create a geometry array prefilled with None or with empty geometries. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty array, e.g., ``(2, 3)`` or ``2``. + geom_type : shapely.GeometryType, optional + The desired geometry type in case the array should be prefilled + with empty geometries. Default ``None``. + order : {'C', 'F'}, optional, default: 'C' + Whether to store multi-dimensional data in row-major + (C-style) or column-major (Fortran-style) order in + memory. + + Examples + -------- + >>> import shapely + >>> shapely.empty((2, 3)).tolist() + [[None, None, None], [None, None, None]] + >>> shapely.empty(2, geom_type=shapely.GeometryType.POINT).tolist() + [, ] + + """ + if geom_type is None: + return np.empty(shape, dtype=object, order=order) + + geom_type = GeometryType(geom_type) # cast int to GeometryType + if geom_type is GeometryType.MISSING: + return np.empty(shape, dtype=object, order=order) + + fill_value = from_wkt(geom_type.name + " EMPTY") + return np.full(shape, fill_value, dtype=object, order=order) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/decorators.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..840577eb6ca57d5c3c060127707c9a1a936d1ae3 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/decorators.py @@ -0,0 +1,183 @@ +"""Decorators for Shapely functions.""" + +import os +import warnings +from collections.abc import Callable, Iterable +from functools import lru_cache, wraps +from inspect import unwrap + +import numpy as np + +from shapely import lib +from shapely.errors import UnsupportedGEOSVersionError + + +class requires_geos: + """Decorator to require a minimum GEOS version.""" + + def __init__(self, version): + """Create a decorator that requires a minimum GEOS version.""" + if version.count(".") != 2: + raise ValueError("Version must be .. format") + self.version = tuple(int(x) for x in version.split(".")) + + def __call__(self, func): + """Return the wrapped function.""" + is_compatible = lib.geos_version >= self.version + is_doc_build = os.environ.get("SPHINX_DOC_BUILD") == "1" # set in docs/conf.py + if is_compatible and not is_doc_build: + return func # return directly, do not change the docstring + + msg = "'{}' requires at least GEOS {}.{}.{}.".format( + func.__name__, *self.version + ) + if is_compatible: + + @wraps(func) + def wrapped(*args, **kwargs): + return func(*args, **kwargs) + + else: + + @wraps(func) + def wrapped(*args, **kwargs): + raise UnsupportedGEOSVersionError(msg) + + doc = wrapped.__doc__ + if doc: + # Insert the message at the first double newline + position = doc.find("\n\n") + 2 + # Figure out the indentation level + indent = 0 + while True: + if doc[position + indent] == " ": + indent += 1 + else: + break + wrapped.__doc__ = doc.replace( + "\n\n", "\n\n{}.. note:: {}\n\n".format(" " * indent, msg), 1 + ) + + return wrapped + + +def multithreading_enabled(func): + """Enable multithreading. + + To do this, the writable flags of object type ndarrays are set to False. + + NB: multithreading also requires the GIL to be released, which is done in + the C extension (ufuncs.c). + """ + + @wraps(func) + def wrapped(*args, **kwargs): + array_args = [ + arg for arg in args if isinstance(arg, np.ndarray) and arg.dtype == object + ] + [ + arg + for name, arg in kwargs.items() + if name not in {"where", "out"} + and isinstance(arg, np.ndarray) + and arg.dtype == object + ] + old_flags = [arr.flags.writeable for arr in array_args] + try: + for arr in array_args: + arr.flags.writeable = False + return func(*args, **kwargs) + finally: + for arr, old_flag in zip(array_args, old_flags): + arr.flags.writeable = old_flag + + return wrapped + + +def deprecate_positional( + should_be_kwargs: Iterable[str], + category: type[Warning] = DeprecationWarning, +): + """Show warning if positional arguments are used that should be keyword. + + Parameters + ---------- + should_be_kwargs : Iterable[str] + Names of parameters that should be passed as keyword arguments. + category : type[Warning], optional (default: DeprecationWarning) + Warning category to use for deprecation warnings. + + Returns + ------- + callable + Decorator function that adds positional argument deprecation warnings. + + Examples + -------- + >>> from shapely.decorators import deprecate_positional + >>> @deprecate_positional(['b', 'c']) + ... def example(a, b, c=None): + ... return a, b, c + ... + >>> example(1, 2) # doctest: +SKIP + DeprecationWarning: positional argument `b` for `example` is deprecated. ... + (1, 2, None) + >>> example(1, b=2) # No warnings + (1, 2, None) + """ + + def decorator(func: Callable): + code = unwrap(func).__code__ + + # positional parameters are the first co_argcount names + pos_names = code.co_varnames[: code.co_argcount] + # build a name -> index map + name_to_idx = {name: idx for idx, name in enumerate(pos_names)} + # pick out only those names we care about + deprecate_positions = [ + (name_to_idx[name], name) + for name in should_be_kwargs + if name in name_to_idx + ] + + # early exit if there are no deprecated positional args + if not deprecate_positions: + return func + + # earliest position where a warning could occur + warn_from = min(deprecate_positions)[0] + + @lru_cache(10) + def make_msg(n_args: int): + used = [name for idx, name in deprecate_positions if idx < n_args] + + if len(used) == 1: + args_txt = f"`{used[0]}`" + plr = "" + isare = "is" + else: + plr = "s" + isare = "are" + if len(used) == 2: + args_txt = " and ".join(f"`{u}`" for u in used) + else: + args_txt = ", ".join(f"`{u}`" for u in used[:-1]) + args_txt += f", and `{used[-1]}`" + + return ( + f"positional argument{plr} {args_txt} for `{func.__name__}` " + f"{isare} deprecated. Please use keyword argument{plr} instead." + ) + + @wraps(func) + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + + n = len(args) + if n > warn_from: + warnings.warn(make_msg(n), category=category, stacklevel=2) + + return result + + return wrapper + + return decorator diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/errors.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc665cced416f9fa0bc2d323c21e7687dc7ab6f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/errors.py @@ -0,0 +1,79 @@ +"""Shapely errors.""" + +import threading + +from shapely.lib import GEOSException, ShapelyError, _setup_signal_checks # noqa: F401 + + +def setup_signal_checks(interval=10000): + """Enable Python signal checks in the ufunc inner loops. + + Doing so allows termination (using CTRL+C) of operations on large arrays of + vectors. + + Parameters + ---------- + interval : int, default 10000 + Check for interrupts every x iterations. The higher the number, the + slower shapely will respond to a signal. However, at low values there + will be a negative effect on performance. The default of 10000 does not + have any measureable effects on performance. + + Notes + ----- + For more information on signals consult the Python docs: + + https://docs.python.org/3/library/signal.html + + """ + if interval <= 0: + raise ValueError("Signal checks interval must be greater than zero.") + + _setup_signal_checks(interval, threading.main_thread().ident) + + +class UnsupportedGEOSVersionError(ShapelyError): + """Raised when the GEOS library version does not support a certain operation.""" + + +class DimensionError(ShapelyError): + """An error in the number of coordinate dimensions.""" + + +class TopologicalError(ShapelyError): + """A geometry is invalid or topologically incorrect.""" + + +class ShapelyDeprecationWarning(FutureWarning): + """Warning for features that will be removed or changed in a future release.""" + + +class EmptyPartError(ShapelyError): + """An error signifying an empty part was encountered when creating a multi-part.""" + + +class GeometryTypeError(ShapelyError): + """An error raised when the geometry has an unrecognized or inappropriate type.""" + + +def __getattr__(name): + import warnings + + # Alias Shapely 1.8 error classes to ShapelyError with deprecation warning + if name in [ + "ReadingError", + "WKBReadingError", + "WKTReadingError", + "PredicateError", + "InvalidGeometryError", + ]: + warnings.warn( + f"{name} is deprecated and will be removed in a future version. " + "Use ShapelyError instead (functions previously raising {name} " + "will now raise a ShapelyError instead).", + FutureWarning, + stacklevel=2, + ) + return ShapelyError + + raise AttributeError(f"module 'shapely.errors' has no attribute '{name}'") diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47d2a8b7f68bf83c2e03ea14fe7da0821f778b60 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__init__.py @@ -0,0 +1,27 @@ +"""Geometry classes and factories.""" + +from shapely.geometry.base import CAP_STYLE, JOIN_STYLE +from shapely.geometry.collection import GeometryCollection +from shapely.geometry.geo import box, mapping, shape +from shapely.geometry.linestring import LineString +from shapely.geometry.multilinestring import MultiLineString +from shapely.geometry.multipoint import MultiPoint +from shapely.geometry.multipolygon import MultiPolygon +from shapely.geometry.point import Point +from shapely.geometry.polygon import LinearRing, Polygon + +__all__ = [ + "CAP_STYLE", + "JOIN_STYLE", + "GeometryCollection", + "LineString", + "LinearRing", + "MultiLineString", + "MultiPoint", + "MultiPolygon", + "Point", + "Polygon", + "box", + "mapping", + "shape", +] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db05596ca57f3fe9c87b1e8679b7f459e1b4dd5c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/base.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42deeeba2ea702566039921c21638e3c78cf49af Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/base.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/collection.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/collection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f75845b133180365f45e7046693214f637459f05 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/collection.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/geo.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/geo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4752bd491b1d49b0a57c95fc2a0a8ffefd0c3e19 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/geo.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/linestring.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/linestring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a82cd8307b381d0023975f9e3d42615a5b5d0fc4 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/linestring.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multilinestring.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multilinestring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c4ffc618fb604985ce53514b650f51fcc35c784 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multilinestring.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multipoint.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multipoint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e65cab40103bc3947b76d72740a4bc2dcf44801 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multipoint.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multipolygon.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multipolygon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e84397aec247abc47de7335dd3bbed6ee4b7577b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/multipolygon.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/point.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/point.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cda76561b5b631c6def8df7e6153127e16c8a26c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/point.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/polygon.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/polygon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40a87b2345722115c0bb37eef3366de831e10c62 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/__pycache__/polygon.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/base.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/base.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3ed13d38eeddc476d59932aa117c7c3a80456b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/base.py @@ -0,0 +1,1138 @@ +"""Base geometry class and utilities. + +Note: a third, z, coordinate value may be used when constructing +geometry objects, but has no effect on geometric analysis. All +operations are performed in the x-y plane. Thus, geometries with +different z values may intersect or be equal. +""" + +import re +from warnings import warn + +import numpy as np + +import shapely +from shapely._geometry_helpers import _geom_factory +from shapely.constructive import BufferCapStyle, BufferJoinStyle +from shapely.coords import CoordinateSequence +from shapely.decorators import deprecate_positional +from shapely.errors import GeometryTypeError, GEOSException, ShapelyDeprecationWarning + +GEOMETRY_TYPES = [ + "Point", + "LineString", + "LinearRing", + "Polygon", + "MultiPoint", + "MultiLineString", + "MultiPolygon", + "GeometryCollection", +] + +_geos_ge_312 = shapely.geos_version >= (3, 12, 0) + + +def geom_factory(g, parent=None): + """Create a Shapely geometry instance from a pointer to a GEOS geometry. + + .. warning:: + The GEOS library used to create the the GEOS geometry pointer + and the GEOS library used by Shapely must be exactly the same, or + unexpected results or segfaults may occur. + + .. deprecated:: 2.0 + Deprecated in Shapely 2.0, and will be removed in a future version. + """ + warn( + "The 'geom_factory' function is deprecated in Shapely 2.0, and will be " + "removed in a future version", + FutureWarning, + stacklevel=2, + ) + return _geom_factory(g) + + +def dump_coords(geom): + """Dump coordinates of a geometry in the same order as data packing.""" + if not isinstance(geom, BaseGeometry): + raise ValueError( + "Must be instance of a geometry class; found " + geom.__class__.__name__ + ) + elif geom.geom_type in ("Point", "LineString", "LinearRing"): + return geom.coords[:] + elif geom.geom_type == "Polygon": + return geom.exterior.coords[:] + [i.coords[:] for i in geom.interiors] + elif geom.geom_type.startswith("Multi") or geom.geom_type == "GeometryCollection": + # Recursive call + return [dump_coords(part) for part in geom.geoms] + else: + raise GeometryTypeError("Unhandled geometry type: " + repr(geom.geom_type)) + + +def _maybe_unpack(result): + if result.ndim == 0: + # convert numpy 0-d array / scalar to python scalar + return result.item() + else: + # >=1 dim array + return result + + +class CAP_STYLE: + """Buffer cap styles.""" + + round = BufferCapStyle.round + flat = BufferCapStyle.flat + square = BufferCapStyle.square + + +class JOIN_STYLE: + """Buffer join styles.""" + + round = BufferJoinStyle.round + mitre = BufferJoinStyle.mitre + bevel = BufferJoinStyle.bevel + + +class BaseGeometry(shapely.Geometry): + """Provides GEOS spatial predicates and topological operations.""" + + __slots__ = [] + + def __new__(self): + """Directly calling the base class 'BaseGeometry()' is deprecated. + + This will raise an error in the future. To create an empty geometry, + use one of the subclasses instead, for example 'GeometryCollection()' + """ + warn( + "Directly calling the base class 'BaseGeometry()' is deprecated, and " + "will raise an error in the future. To create an empty geometry, " + "use one of the subclasses instead, for example 'GeometryCollection()'.", + ShapelyDeprecationWarning, + stacklevel=2, + ) + return shapely.from_wkt("GEOMETRYCOLLECTION EMPTY") + + @property + def _ndim(self): + return shapely.get_coordinate_dimension(self) + + def __bool__(self): + """Return True if the geometry is not empty, else False.""" + return self.is_empty is False + + def __nonzero__(self): + """Return True if the geometry is not empty, else False.""" + return self.__bool__() + + def __format__(self, format_spec): + """Format a geometry using a format specification.""" + # bypass regexp for simple cases + if format_spec == "": + return shapely.to_wkt(self, rounding_precision=-1) + elif format_spec == "x": + return shapely.to_wkb(self, hex=True).lower() + elif format_spec == "X": + return shapely.to_wkb(self, hex=True) + + # fmt: off + format_spec_regexp = ( + "(?:0?\\.(?P[0-9]+))?" + "(?P[fFgGxX]?)" + ) + # fmt: on + match = re.fullmatch(format_spec_regexp, format_spec) + if match is None: + raise ValueError(f"invalid format specifier: {format_spec}") + + prec, fmt_code = match.groups() + + if prec: + prec = int(prec) + else: + # GEOS has a default rounding_precision -1 + prec = -1 + + if not fmt_code: + fmt_code = "g" + + if fmt_code in ("g", "G"): + res = shapely.to_wkt(self, rounding_precision=prec, trim=True) + elif fmt_code in ("f", "F"): + res = shapely.to_wkt(self, rounding_precision=prec, trim=False) + elif fmt_code in ("x", "X"): + raise ValueError("hex representation does not specify precision") + else: + raise NotImplementedError(f"unhandled fmt_code: {fmt_code}") + + if fmt_code.isupper(): + return res.upper() + else: + return res + + def __repr__(self): + """Return a string representation of the geometry.""" + try: + wkt = super().__str__() + except (GEOSException, ValueError): + # we never want a repr() to fail; that can be very confusing + return f"" + + # the total length is limited to 80 characters including brackets + max_length = 78 + if len(wkt) > max_length: + return f"<{wkt[: max_length - 3]}...>" + + return f"<{wkt}>" + + def __str__(self): + """Return a string representation of the geometry.""" + return self.wkt + + def __reduce__(self): + """Pickle support.""" + return (shapely.from_wkb, (shapely.to_wkb(self, include_srid=True),)) + + # Operators + # --------- + + def __and__(self, other): + """Return the intersection of the geometries.""" + return self.intersection(other) + + def __or__(self, other): + """Return the union of the geometries.""" + return self.union(other) + + def __sub__(self, other): + """Return the difference of the geometries.""" + return self.difference(other) + + def __xor__(self, other): + """Return the symmetric difference of the geometries.""" + return self.symmetric_difference(other) + + # Coordinate access + # ----------------- + + @property + def coords(self): + """Access to geometry's coordinates (CoordinateSequence).""" + has_z = self.has_z + has_m = self.has_m if _geos_ge_312 else False + coords_array = shapely.get_coordinates(self, include_z=has_z, include_m=has_m) + return CoordinateSequence(coords_array) + + @property + def xy(self): + """Separate arrays of X and Y coordinate values.""" + raise NotImplementedError + + # Python feature protocol + + @property + def __geo_interface__(self): + """Dictionary representation of the geometry.""" + raise NotImplementedError + + # Type of geometry and its representations + # ---------------------------------------- + + def geometryType(self): + """Get the geometry type (deprecated). + + .. deprecated:: 2.0 + Use the :py:attr:`geom_type` attribute instead. + """ + warn( + "The 'GeometryType()' method is deprecated, and will be removed in " + "the future. You can use the 'geom_type' attribute instead.", + ShapelyDeprecationWarning, + stacklevel=2, + ) + return self.geom_type + + @property + def type(self): + """Get the geometry type (deprecated). + + .. deprecated:: 2.0 + Use the :py:attr:`geom_type` attribute instead. + """ + warn( + "The 'type' attribute is deprecated, and will be removed in " + "the future. You can use the 'geom_type' attribute instead.", + ShapelyDeprecationWarning, + stacklevel=2, + ) + return self.geom_type + + @property + def wkt(self): + """WKT representation of the geometry.""" + # TODO(shapely-2.0) keep default of not trimming? + return shapely.to_wkt(self, rounding_precision=-1) + + @property + def wkb(self): + """WKB representation of the geometry.""" + return shapely.to_wkb(self) + + @property + def wkb_hex(self): + """WKB hex representation of the geometry.""" + return shapely.to_wkb(self, hex=True) + + def svg(self, scale_factor=1.0, **kwargs): + """Raise NotImplementedError.""" + raise NotImplementedError + + def _repr_svg_(self): + """SVG representation for iPython notebook.""" + svg_top = ( + '" + else: + # Establish SVG canvas that will fit all the data + small space + xmin, ymin, xmax, ymax = self.bounds + if xmin == xmax and ymin == ymax: + # This is a point; buffer using an arbitrary size + xmin, ymin, xmax, ymax = self.buffer(1).bounds + else: + # Expand bounds by a fraction of the data ranges + expand = 0.04 # or 4%, same as R plots + widest_part = max([xmax - xmin, ymax - ymin]) + expand_amount = widest_part * expand + xmin -= expand_amount + ymin -= expand_amount + xmax += expand_amount + ymax += expand_amount + dx = xmax - xmin + dy = ymax - ymin + width = min([max([100.0, dx]), 300]) + height = min([max([100.0, dy]), 300]) + try: + scale_factor = max([dx, dy]) / max([width, height]) + except ZeroDivisionError: + scale_factor = 1.0 + view_box = f"{xmin} {ymin} {dx} {dy}" + transform = f"matrix(1,0,0,-1,0,{ymax + ymin})" + return ( + f'{svg_top}width="{width}" height="{height}" viewBox="{view_box}" ' + 'preserveAspectRatio="xMinYMin meet">' + f'{self.svg(scale_factor)}' + ) + + @property + def geom_type(self): + """Name of the geometry's type, such as 'Point'.""" + return GEOMETRY_TYPES[shapely.get_type_id(self)] + + # Real-valued properties and methods + # ---------------------------------- + + @property + def area(self): + """Unitless area of the geometry (float).""" + return float(shapely.area(self)) + + def distance(self, other): + """Unitless distance to other geometry (float).""" + return _maybe_unpack(shapely.distance(self, other)) + + def hausdorff_distance(self, other): + """Unitless hausdorff distance to other geometry (float).""" + return _maybe_unpack(shapely.hausdorff_distance(self, other)) + + @property + def length(self): + """Unitless length of the geometry (float).""" + return float(shapely.length(self)) + + @property + def minimum_clearance(self): + """Unitless distance a node can be moved to produce an invalid geometry (float).""" # noqa: E501 + return float(shapely.minimum_clearance(self)) + + # Topological properties + # ---------------------- + + @property + def boundary(self): + """Return a lower dimension geometry that bounds the object. + + The boundary of a polygon is a line, the boundary of a line is a + collection of points. The boundary of a point is an empty (null) + collection. + """ + return shapely.boundary(self) + + @property + def bounds(self): + """Return minimum bounding region (minx, miny, maxx, maxy).""" + return tuple(shapely.bounds(self).tolist()) + + @property + def centroid(self): + """Return the geometric center of the object.""" + return shapely.centroid(self) + + def point_on_surface(self): + """Return a point guaranteed to be within the object, cheaply. + + Alias of `representative_point`. + """ + return shapely.point_on_surface(self) + + def representative_point(self): + """Return a point guaranteed to be within the object, cheaply. + + Alias of `point_on_surface`. + """ + return shapely.point_on_surface(self) + + @property + def convex_hull(self): + """Return the convex hull of the geometry. + + Imagine an elastic band stretched around the geometry: that's a convex + hull, more or less. + + The convex hull of a three member multipoint, for example, is a + triangular polygon. + """ + return shapely.convex_hull(self) + + @property + def envelope(self): + """A figure that envelopes the geometry.""" + return shapely.envelope(self) + + @property + def oriented_envelope(self): + """Return the oriented envelope (minimum rotated rectangle) of a geometry. + + The oriented envelope encloses an input geometry, such that the resulting + rectangle has minimum area. + + Unlike envelope this rectangle is not constrained to be parallel to the + coordinate axes. If the convex hull of the object is a degenerate (line + or point) this degenerate is returned. + + The starting point of the rectangle is not fixed. You can use + :func:`~shapely.normalize` to reorganize the rectangle to + :ref:`strict canonical form ` so the starting point is + always the lower left point. + + Alias of `minimum_rotated_rectangle`. + """ + return shapely.oriented_envelope(self) + + @property + def minimum_rotated_rectangle(self): + """Return the oriented envelope (minimum rotated rectangle) of the geometry. + + The oriented envelope encloses an input geometry, such that the resulting + rectangle has minimum area. + + Unlike `envelope` this rectangle is not constrained to be parallel to the + coordinate axes. If the convex hull of the object is a degenerate (line + or point) this degenerate is returned. + + The starting point of the rectangle is not fixed. You can use + :func:`~shapely.normalize` to reorganize the rectangle to + :ref:`strict canonical form ` so the starting point is + always the lower left point. + + Alias of `oriented_envelope`. + """ + return shapely.oriented_envelope(self) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # buffer(self, geometry, distance, quad_segs=16, cap_style="round", ...) + # shapely 2.1: shows deprecation warning about positional 'cap_style', etc. + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'quad_segs' + # buffer(self, geometry, distance, quad_segs=16, *, cap_style="round", ...) + @deprecate_positional( + ["cap_style", "join_style", "mitre_limit", "single_sided"], + category=DeprecationWarning, + ) + def buffer( + self, + distance, + quad_segs=16, + cap_style="round", + join_style="round", + mitre_limit=5.0, + single_sided=False, + **kwargs, + ): + """Get a geometry that represents all points within a distance of this geometry. + + A positive distance produces a dilation, a negative distance an + erosion. A very small or zero distance may sometimes be used to + "tidy" a polygon. + + Parameters + ---------- + distance : float + The distance to buffer around the object. + quad_segs : int, optional + Sets the number of line segments used to approximate an + angle fillet. + cap_style : shapely.BufferCapStyle or {'round', 'square', 'flat'}, default 'round' + Specifies the shape of buffered line endings. BufferCapStyle.round + ('round') results in circular line endings (see ``quad_segs``). Both + BufferCapStyle.square ('square') and BufferCapStyle.flat ('flat') + result in rectangular line endings, only BufferCapStyle.flat + ('flat') will end at the original vertex, while + BufferCapStyle.square ('square') involves adding the buffer width. + join_style : shapely.BufferJoinStyle or {'round', 'mitre', 'bevel'}, default 'round' + Specifies the shape of buffered line midpoints. + BufferJoinStyle.ROUND ('round') results in rounded shapes. + BufferJoinStyle.bevel ('bevel') results in a beveled edge that + touches the original vertex. BufferJoinStyle.mitre ('mitre') results + in a single vertex that is beveled depending on the ``mitre_limit`` + parameter. + mitre_limit : float, optional + The mitre limit ratio is used for very sharp corners. The + mitre ratio is the ratio of the distance from the corner to + the end of the mitred offset corner. When two line segments + meet at a sharp angle, a miter join will extend the original + geometry. To prevent unreasonable geometry, the mitre limit + allows controlling the maximum length of the join corner. + Corners with a ratio which exceed the limit will be beveled. + single_sided : bool, optional + The side used is determined by the sign of the buffer + distance: + + a positive distance indicates the left-hand side + a negative distance indicates the right-hand side + + The single-sided buffer of point geometries is the same as + the regular buffer. The End Cap Style for single-sided + buffers is always ignored, and forced to the equivalent of + CAP_FLAT. + quadsegs, resolution : int, optional + Deprecated aliases for `quad_segs`. + **kwargs : dict, optional + For backwards compatibility of renamed parameters. If an unsupported + kwarg is passed, a `ValueError` will be raised. + + Returns + ------- + Geometry + + Notes + ----- + The return value is a strictly two-dimensional geometry. All + Z coordinates of the original geometry will be ignored. + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``quad_segs``, ``cap_style``, + ``join_style``, ``mitre_limit`` or ``single_sided`` are + specified as positional arguments. In a future release, these will + need to be specified as keyword arguments. + + Examples + -------- + >>> from shapely import BufferCapStyle + >>> from shapely.wkt import loads + >>> g = loads('POINT (0.0 0.0)') + + 16-gon approx of a unit radius circle: + + >>> g.buffer(1.0).area + 3.1365484905459398 + + 128-gon approximation: + + >>> g.buffer(1.0, 128).area + 3.1415138011443013 + + triangle approximation: + + >>> g.buffer(1.0, 3).area + 3.0 + >>> list(g.buffer(1.0, cap_style=BufferCapStyle.square).exterior.coords) + [(1.0, 1.0), (1.0, -1.0), (-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] + >>> g.buffer(1.0, cap_style=BufferCapStyle.square).area + 4.0 + + """ # noqa: E501 + quadsegs = kwargs.pop("quadsegs", None) + if quadsegs is not None: + warn( + "The `quadsegs` argument is deprecated. Use `quad_segs` instead.", + FutureWarning, + stacklevel=2, + ) + quad_segs = quadsegs + + resolution = kwargs.pop("resolution", None) + if resolution is not None: + warn( + "The 'resolution' argument is deprecated. Use 'quad_segs' instead", + DeprecationWarning, + stacklevel=2, + ) + quad_segs = resolution + if kwargs: + kwarg = list(kwargs.keys())[0] # noqa + raise TypeError(f"buffer() got an unexpected keyword argument '{kwarg}'") + + if mitre_limit == 0.0: + raise ValueError("Cannot compute offset from zero-length line segment") + elif not np.isfinite(distance).all(): + raise ValueError("buffer distance must be finite") + + return shapely.buffer( + self, + distance, + quad_segs=quad_segs, + cap_style=cap_style, + join_style=join_style, + mitre_limit=mitre_limit, + single_sided=single_sided, + ) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # simplify(self, tolerance, preserve_topology=True) + # shapely 2.1: shows deprecation warning about positional 'preserve_topology' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'tolerance' + # simplify(self, tolerance, *, preserve_topology=True) + + @deprecate_positional(["preserve_topology"], category=DeprecationWarning) + def simplify(self, tolerance, preserve_topology=True): + """Return a simplified geometry produced by the Douglas-Peucker algorithm. + + Coordinates of the simplified geometry will be no more than the + tolerance distance from the original. Unless the topology preserving + option is used, the algorithm may produce self-intersecting or + otherwise invalid geometries. + """ + return shapely.simplify(self, tolerance, preserve_topology=preserve_topology) + + def normalize(self): + """Convert geometry to normal form (or canonical form). + + This method orders the coordinates, rings of a polygon and parts of + multi geometries consistently. Typically useful for testing purposes + (for example in combination with `equals_exact`). + + Examples + -------- + >>> from shapely import MultiLineString + >>> line = MultiLineString([[(0, 0), (1, 1)], [(3, 3), (2, 2)]]) + >>> line.normalize() + + + """ + return shapely.normalize(self) + + # Overlay operations + # --------------------------- + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # difference(self, other, grid_size=None) + # shapely 2.1: shows deprecation warning about positional 'grid_size' arg + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # difference(self, other, *, grid_size=None) + + @deprecate_positional(["grid_size"], category=DeprecationWarning) + def difference(self, other, grid_size=None): + """Return the difference of the geometries. + + Refer to `shapely.difference` for full documentation. + """ + return shapely.difference(self, other, grid_size=grid_size) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # intersection(self, other, grid_size=None) + # shapely 2.1: shows deprecation warning about positional 'grid_size' arg + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # intersection(self, other, *, grid_size=None) + + @deprecate_positional(["grid_size"], category=DeprecationWarning) + def intersection(self, other, grid_size=None): + """Return the intersection of the geometries. + + Refer to `shapely.intersection` for full documentation. + """ + return shapely.intersection(self, other, grid_size=grid_size) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # symmetric_difference(self, other, grid_size=None) + # shapely 2.1: shows deprecation warning about positional 'grid_size' arg + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # symmetric_difference(self, other, *, grid_size=None) + + @deprecate_positional(["grid_size"], category=DeprecationWarning) + def symmetric_difference(self, other, grid_size=None): + """Return the symmetric difference of the geometries. + + Refer to `shapely.symmetric_difference` for full documentation. + """ + return shapely.symmetric_difference(self, other, grid_size=grid_size) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # union(self, other, grid_size=None) + # shapely 2.1: shows deprecation warning about positional 'grid_size' arg + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # union(self, other, *, grid_size=None) + + @deprecate_positional(["grid_size"], category=DeprecationWarning) + def union(self, other, grid_size=None): + """Return the union of the geometries. + + Refer to `shapely.union` for full documentation. + """ + return shapely.union(self, other, grid_size=grid_size) + + # Unary predicates + # ---------------- + + @property + def has_z(self): + """True if the geometry's coordinate sequence(s) have z values.""" + return bool(shapely.has_z(self)) + + @property + def has_m(self): + """True if the geometry's coordinate sequence(s) have m values.""" + return bool(shapely.has_m(self)) + + @property + def is_empty(self): + """True if the set of points in this geometry is empty, else False.""" + return bool(shapely.is_empty(self)) + + @property + def is_ring(self): + """True if the geometry is a closed ring, else False.""" + return bool(shapely.is_ring(self)) + + @property + def is_closed(self): + """True if the geometry is closed, else False. + + Applicable only to linear geometries. + """ + if self.geom_type == "LinearRing": + return True + return bool(shapely.is_closed(self)) + + @property + def is_simple(self): + """True if the geometry is simple. + + Simple means that any self-intersections are only at boundary points. + """ + return bool(shapely.is_simple(self)) + + @property + def is_valid(self): + """True if the geometry is valid. + + The definition depends on sub-class. + """ + return bool(shapely.is_valid(self)) + + # Binary predicates + # ----------------- + + def relate(self, other): + """Return the DE-9IM intersection matrix for the two geometries (string).""" + return shapely.relate(self, other) + + def covers(self, other): + """Return True if the geometry covers the other, else False.""" + return _maybe_unpack(shapely.covers(self, other)) + + def covered_by(self, other): + """Return True if the geometry is covered by the other, else False.""" + return _maybe_unpack(shapely.covered_by(self, other)) + + def contains(self, other): + """Return True if the geometry contains the other, else False.""" + return _maybe_unpack(shapely.contains(self, other)) + + def contains_properly(self, other): + """Return True if the geometry completely contains the other. + + There should be no common boundary points. + + Refer to `shapely.contains_properly` for full documentation. + """ + return _maybe_unpack(shapely.contains_properly(self, other)) + + def crosses(self, other): + """Return True if the geometries cross, else False.""" + return _maybe_unpack(shapely.crosses(self, other)) + + def disjoint(self, other): + """Return True if geometries are disjoint, else False.""" + return _maybe_unpack(shapely.disjoint(self, other)) + + def equals(self, other): + """Return True if geometries are equal, else False. + + This method considers point-set equality (or topological + equality), and is equivalent to (self.within(other) & + self.contains(other)). + + Examples + -------- + >>> from shapely import LineString + >>> LineString( + ... [(0, 0), (2, 2)] + ... ).equals( + ... LineString([(0, 0), (1, 1), (2, 2)]) + ... ) + True + + Returns + ------- + bool + + """ + return _maybe_unpack(shapely.equals(self, other)) + + def intersects(self, other): + """Return True if geometries intersect, else False.""" + return _maybe_unpack(shapely.intersects(self, other)) + + def overlaps(self, other): + """Return True if geometries overlap, else False.""" + return _maybe_unpack(shapely.overlaps(self, other)) + + def touches(self, other): + """Return True if geometries touch, else False.""" + return _maybe_unpack(shapely.touches(self, other)) + + def within(self, other): + """Return True if geometry is within the other, else False.""" + return _maybe_unpack(shapely.within(self, other)) + + def dwithin(self, other, distance): + """Return True if geometry is within a given distance from the other. + + Refer to `shapely.dwithin` for full documentation. + """ + return _maybe_unpack(shapely.dwithin(self, other, distance)) + + def equals_exact(self, other, tolerance=0.0, *, normalize=False): + """Return True if the geometries are equivalent within the tolerance. + + Refer to :func:`~shapely.equals_exact` for full documentation. + + Parameters + ---------- + other : BaseGeometry + The other geometry object in this comparison. + tolerance : float, optional (default: 0.) + Absolute tolerance in the same units as coordinates. + normalize : bool, optional (default: False) + If True, normalize the two geometries so that the coordinates are + in the same order. + + .. versionadded:: 2.1.0 + + Examples + -------- + >>> from shapely import LineString + >>> LineString( + ... [(0, 0), (2, 2)] + ... ).equals_exact( + ... LineString([(0, 0), (1, 1), (2, 2)]), + ... 1e-6 + ... ) + False + + Returns + ------- + bool + + """ + return _maybe_unpack( + shapely.equals_exact(self, other, tolerance, normalize=normalize) + ) + + def relate_pattern(self, other, pattern): + """Return True if the DE-9IM relationship code satisfies the pattern.""" + return _maybe_unpack(shapely.relate_pattern(self, other, pattern)) + + # Linear referencing + # ------------------ + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # line_locate_point(self, other, normalized=False) + # shapely 2.1: shows deprecation warning about positional 'normalized' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # line_locate_point(self, other, *, normalized=False) + + @deprecate_positional(["normalized"], category=DeprecationWarning) + def line_locate_point(self, other, normalized=False): + """Return the distance of this geometry to a point nearest the specified point. + + If the normalized arg is True, return the distance normalized to the + length of the linear geometry. + + Alias of `project`. + """ + return _maybe_unpack( + shapely.line_locate_point(self, other, normalized=normalized) + ) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # project(self, other, normalized=False) + # shapely 2.1: shows deprecation warning about positional 'normalized' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # project(self, other, *, normalized=False) + + @deprecate_positional(["normalized"], category=DeprecationWarning) + def project(self, other, normalized=False): + """Return the distance of geometry to a point nearest the specified point. + + If the normalized arg is True, return the distance normalized to the + length of the linear geometry. + + Alias of `line_locate_point`. + """ + return _maybe_unpack( + shapely.line_locate_point(self, other, normalized=normalized) + ) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # line_interpolate_point(self, distance, normalized=False) + # shapely 2.1: shows deprecation warning about positional 'normalized' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'distance' + # line_interpolate_point(self, distance, *, normalized=False) + + @deprecate_positional(["normalized"], category=DeprecationWarning) + def line_interpolate_point(self, distance, normalized=False): + """Return a point at the specified distance along a linear geometry. + + Negative length values are taken as measured in the reverse + direction from the end of the geometry. Out-of-range index + values are handled by clamping them to the valid range of values. + If the normalized arg is True, the distance will be interpreted as a + fraction of the geometry's length. + + Alias of `interpolate`. + """ + return shapely.line_interpolate_point(self, distance, normalized=normalized) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # interpolate(self, distance, normalized=False) + # shapely 2.1: shows deprecation warning about positional 'normalized' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'distance' + # interpolate(self, distance, *, normalized=False) + + @deprecate_positional(["normalized"], category=DeprecationWarning) + def interpolate(self, distance, normalized=False): + """Return a point at the specified distance along a linear geometry. + + Negative length values are taken as measured in the reverse + direction from the end of the geometry. Out-of-range index + values are handled by clamping them to the valid range of values. + If the normalized arg is True, the distance will be interpreted as a + fraction of the geometry's length. + + Alias of `line_interpolate_point`. + """ + return shapely.line_interpolate_point(self, distance, normalized=normalized) + + def segmentize(self, max_segment_length): + """Add vertices to line segments based on maximum segment length. + + Additional vertices will be added to every line segment in an input geometry + so that segments are no longer than the provided maximum segment length. New + vertices will evenly subdivide each segment. + + Only linear components of input geometries are densified; other geometries + are returned unmodified. + + Parameters + ---------- + max_segment_length : float or array_like + Additional vertices will be added so that all line segments are no + longer this value. Must be greater than 0. + + Examples + -------- + >>> from shapely import LineString, Polygon + >>> LineString([(0, 0), (0, 10)]).segmentize(max_segment_length=5) + + >>> Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]).segmentize(max_segment_length=5) + + + """ # noqa: E501 + return shapely.segmentize(self, max_segment_length) + + def reverse(self): + """Return a copy of this geometry with the order of coordinates reversed. + + If the geometry is a polygon with interior rings, the interior rings are also + reversed. + + Points are unchanged. + + See Also + -------- + is_ccw : Checks if a geometry is clockwise. + + Examples + -------- + >>> from shapely import LineString, Polygon + >>> LineString([(0, 0), (1, 2)]).reverse() + + >>> Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]).reverse() + + + """ + return shapely.reverse(self) + + +class BaseMultipartGeometry(BaseGeometry): + """Base class for collections of multiple geometries.""" + + __slots__ = [] + + @property + def coords(self): + """Not implemented. + + Sub-geometries may have coordinate sequences, but multi-part geometries + do not. + """ + raise NotImplementedError( + "Sub-geometries may have coordinate sequences, " + "but multi-part geometries do not" + ) + + @property + def geoms(self): + """Access to the contained geometries.""" + return GeometrySequence(self) + + def __bool__(self): + """Return True if the geometry is not empty, else False.""" + return self.is_empty is False + + def __eq__(self, other): + """Return True if geometries are equal, else False.""" + if not isinstance(other, BaseGeometry): + return NotImplemented + return ( + type(other) is type(self) + and len(self.geoms) == len(other.geoms) + and all(a == b for a, b in zip(self.geoms, other.geoms)) + ) + + def __hash__(self): + """Return the hash value of the geometry.""" + return super().__hash__() + + def svg(self, scale_factor=1.0, color=None): + """Return a group of SVG elements for the multipart geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + color : str, optional + Hex string for stroke or fill color. Default is to use "#66cc99" + if geometry is valid, and "#ff3333" if invalid. + + """ + if self.is_empty: + return "" + if color is None: + color = "#66cc99" if self.is_valid else "#ff3333" + return "" + "".join(p.svg(scale_factor, color) for p in self.geoms) + "" + + +class GeometrySequence: + """Iterative access to members of a homogeneous multipart geometry.""" + + # Attributes + # ---------- + # _parent : object + # Parent (Shapely) geometry + _parent = None + + def __init__(self, parent): + """Initialize the sequence with a parent geometry.""" + self._parent = parent + + def _get_geom_item(self, i): + return shapely.get_geometry(self._parent, i) + + def __iter__(self): + """Iterate over the geometries in the sequence.""" + for i in range(self.__len__()): + yield self._get_geom_item(i) + + def __len__(self): + """Return the number of geometries in the sequence.""" + return shapely.get_num_geometries(self._parent) + + def __getitem__(self, key): + """Access a geometry in the sequence by index or slice.""" + m = self.__len__() + if isinstance(key, (int, np.integer)): + if key + m < 0 or key >= m: + raise IndexError("index out of range") + if key < 0: + i = m + key + else: + i = key + return self._get_geom_item(i) + elif isinstance(key, slice): + res = [] + start, stop, stride = key.indices(m) + for i in range(start, stop, stride): + res.append(self._get_geom_item(i)) + return type(self._parent)(res or None) + else: + raise TypeError("key must be an index or slice") + + +class EmptyGeometry(BaseGeometry): + """An empty geometry.""" + + def __new__(self): + """Create an empty geometry.""" + warn( + "The 'EmptyGeometry()' constructor to create an empty geometry is " + "deprecated, and will raise an error in the future. Use one of the " + "geometry subclasses instead, for example 'GeometryCollection()'.", + ShapelyDeprecationWarning, + stacklevel=2, + ) + return shapely.from_wkt("GEOMETRYCOLLECTION EMPTY") diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/collection.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/collection.py new file mode 100644 index 0000000000000000000000000000000000000000..51879a07bb37abad03c89d82cd4dc14b600a3242 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/collection.py @@ -0,0 +1,58 @@ +"""Multi-part collections of geometries.""" + +import shapely +from shapely.geometry.base import BaseGeometry, BaseMultipartGeometry + + +class GeometryCollection(BaseMultipartGeometry): + """Collection of one or more geometries that can be of different types. + + Parameters + ---------- + geoms : list + A list of shapely geometry instances, which may be of varying geometry + types. + + Attributes + ---------- + geoms : sequence + A sequence of Shapely geometry instances + + Examples + -------- + Create a GeometryCollection with a Point and a LineString + + >>> from shapely import GeometryCollection, LineString, Point + >>> p = Point(51, -1) + >>> l = LineString([(52, -1), (49, 2)]) + >>> gc = GeometryCollection([p, l]) + + """ + + __slots__ = [] + + def __new__(self, geoms=None): + """Create a new GeometryCollection.""" + if isinstance(geoms, BaseGeometry): + # TODO(shapely-2.0) do we actually want to split Multi-part geometries? + # this is needed for the split() tests + if hasattr(geoms, "geoms"): + geoms = geoms.geoms + else: + geoms = [geoms] + elif geoms is None or len(geoms) == 0: + # TODO better empty constructor + return shapely.from_wkt("GEOMETRYCOLLECTION EMPTY") + + return shapely.geometrycollections(geoms) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the geometry collection.""" + geometries = [] + for geom in self.geoms: + geometries.append(geom.__geo_interface__) + return dict(type="GeometryCollection", geometries=geometries) + + +shapely.lib.registry[7] = GeometryCollection diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/geo.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/geo.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1de81ae5a7265704cf24d27e1bf23eddb39c8e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/geo.py @@ -0,0 +1,143 @@ +"""Geometry factories based on the geo interface.""" + +import numpy as np + +from shapely.errors import GeometryTypeError +from shapely.geometry.collection import GeometryCollection +from shapely.geometry.linestring import LineString +from shapely.geometry.multilinestring import MultiLineString +from shapely.geometry.multipoint import MultiPoint +from shapely.geometry.multipolygon import MultiPolygon +from shapely.geometry.point import Point +from shapely.geometry.polygon import LinearRing, Polygon + + +def _is_coordinates_empty(coordinates): + """Identify if coordinates or subset of coordinates are empty.""" + if coordinates is None: + return True + + if isinstance(coordinates, (list, tuple, np.ndarray)): + if len(coordinates) == 0: + return True + return all(map(_is_coordinates_empty, coordinates)) + else: + return False + + +def _empty_shape_for_no_coordinates(geom_type): + """Return empty counterpart for geom_type.""" + if geom_type == "point": + return Point() + elif geom_type == "multipoint": + return MultiPoint() + elif geom_type == "linestring": + return LineString() + elif geom_type == "multilinestring": + return MultiLineString() + elif geom_type == "polygon": + return Polygon() + elif geom_type == "multipolygon": + return MultiPolygon() + else: + raise GeometryTypeError(f"Unknown geometry type: {geom_type!r}") + + +def box(minx, miny, maxx, maxy, ccw=True): + """Return a rectangular polygon with configurable normal vector.""" + coords = [(maxx, miny), (maxx, maxy), (minx, maxy), (minx, miny)] + if not ccw: + coords = coords[::-1] + return Polygon(coords) + + +def shape(context): + """Return a new, independent geometry with coordinates copied from the context. + + Changes to the original context will not be reflected in the geometry + object. + + Parameters + ---------- + context : + a GeoJSON-like dict, which provides a "type" member describing the type + of the geometry and "coordinates" member providing a list of coordinates, + or an object which implements __geo_interface__. + + Returns + ------- + Geometry object + + Examples + -------- + Create a Point from GeoJSON, and then create a copy using __geo_interface__. + + >>> from shapely.geometry import shape + >>> context = {'type': 'Point', 'coordinates': [0, 1]} + >>> geom = shape(context) + >>> geom.geom_type == 'Point' + True + >>> geom.wkt + 'POINT (0 1)' + >>> geom2 = shape(geom) + >>> geom == geom2 + True + + """ + if hasattr(context, "__geo_interface__"): + ob = context.__geo_interface__ + else: + ob = context + geom_type = ob.get("type").lower() + + if geom_type == "feature": + # GeoJSON features must have a 'geometry' field. + ob = ob["geometry"] + geom_type = ob.get("type").lower() + + if "coordinates" in ob and _is_coordinates_empty(ob["coordinates"]): + return _empty_shape_for_no_coordinates(geom_type) + elif geom_type == "point": + return Point(ob["coordinates"]) + elif geom_type == "linestring": + return LineString(ob["coordinates"]) + elif geom_type == "linearring": + return LinearRing(ob["coordinates"]) + elif geom_type == "polygon": + return Polygon(ob["coordinates"][0], ob["coordinates"][1:]) + elif geom_type == "multipoint": + return MultiPoint(ob["coordinates"]) + elif geom_type == "multilinestring": + return MultiLineString(ob["coordinates"]) + elif geom_type == "multipolygon": + return MultiPolygon([[c[0], c[1:]] for c in ob["coordinates"]]) + elif geom_type == "geometrycollection": + geoms = [shape(g) for g in ob.get("geometries", [])] + return GeometryCollection(geoms) + else: + raise GeometryTypeError(f"Unknown geometry type: {geom_type!r}") + + +def mapping(ob): + """Return a GeoJSON-like mapping. + + Input should be a Geometry or an object which implements __geo_interface__. + + Parameters + ---------- + ob : geometry or object + An object which implements __geo_interface__. + + Returns + ------- + dict + + Examples + -------- + >>> from shapely.geometry import mapping, Point + >>> pt = Point(0, 0) + >>> mapping(pt) + {'type': 'Point', 'coordinates': (0.0, 0.0)} + + """ + return ob.__geo_interface__ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/linestring.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/linestring.py new file mode 100644 index 0000000000000000000000000000000000000000..7019be2d87dea2c9f0e39846652a06197a7213f3 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/linestring.py @@ -0,0 +1,211 @@ +"""Line strings and related utilities.""" + +import numpy as np + +import shapely +from shapely.decorators import deprecate_positional +from shapely.geometry.base import JOIN_STYLE, BaseGeometry +from shapely.geometry.point import Point + +__all__ = ["LineString"] + + +class LineString(BaseGeometry): + """A geometry type composed of one or more line segments. + + A LineString is a one-dimensional feature and has a non-zero length but + zero area. It may approximate a curve and need not be straight. A LineString may + be closed. + + Parameters + ---------- + coordinates : sequence + A sequence of (x, y, [,z]) numeric coordinate pairs or triples, or + an array-like with shape (N, 2) or (N, 3). + Also can be a sequence of Point objects, or combination of both. + + Examples + -------- + Create a LineString with two segments + + >>> from shapely import LineString + >>> a = LineString([[0, 0], [1, 0], [1, 1]]) + >>> a.length + 2.0 + + """ + + __slots__ = [] + + def __new__(self, coordinates=None): + """Create a new LineString geometry.""" + if coordinates is None: + # empty geometry + # TODO better constructor + return shapely.from_wkt("LINESTRING EMPTY") + elif isinstance(coordinates, LineString): + if type(coordinates) is LineString: + # return original objects since geometries are immutable + return coordinates + else: + # LinearRing + # TODO convert LinearRing to LineString more directly + coordinates = coordinates.coords + else: + if hasattr(coordinates, "__array__"): + coordinates = np.asarray(coordinates) + if isinstance(coordinates, np.ndarray) and np.issubdtype( + coordinates.dtype, np.number + ): + pass + else: + # check coordinates on points + def _coords(o): + if isinstance(o, Point): + return o.coords[0] + else: + return [float(c) for c in o] + + coordinates = [_coords(o) for o in coordinates] + + if len(coordinates) == 0: + # empty geometry + # TODO better constructor + should shapely.linestrings handle this? + return shapely.from_wkt("LINESTRING EMPTY") + + geom = shapely.linestrings(coordinates) + if not isinstance(geom, LineString): + raise ValueError("Invalid values passed to LineString constructor") + return geom + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the LineString geometry.""" + return {"type": "LineString", "coordinates": tuple(self.coords)} + + def svg(self, scale_factor=1.0, stroke_color=None, opacity=None): + """Return SVG polyline element for the LineString geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + stroke_color : str, optional + Hex string for stroke color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.8 + + """ + if self.is_empty: + return "" + if stroke_color is None: + stroke_color = "#66cc99" if self.is_valid else "#ff3333" + if opacity is None: + opacity = 0.8 + pnt_format = " ".join(["{},{}".format(*c) for c in self.coords]) + return ( + f'' + ) + + @property + def xy(self): + """Separate arrays of X and Y coordinate values. + + Examples + -------- + >>> from shapely import LineString + >>> x, y = LineString([(0, 0), (1, 1)]).xy + >>> list(x) + [0.0, 1.0] + >>> list(y) + [0.0, 1.0] + + """ + return self.coords.xy + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # offset_curve(self, distance, quad_segs=16, ...) + # shapely 2.1: shows deprecation warning about positional 'quad_segs', etc. + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'distance' + # offset_curve(self, distance, *, quad_segs=16, ...) + + @deprecate_positional( + ["quad_segs", "join_style", "mitre_limit"], category=DeprecationWarning + ) + def offset_curve( + self, + distance, + quad_segs=16, + join_style=JOIN_STYLE.round, + mitre_limit=5.0, + ): + """Return a (Multi)LineString at a distance from the object. + + The side, left or right, is determined by the sign of the `distance` + parameter (negative for right side offset, positive for left side + offset). The resolution of the buffer around each vertex of the object + increases by increasing the `quad_segs` keyword parameter. + + The join style is for outside corners between line segments. Accepted + values are JOIN_STYLE.round (1), JOIN_STYLE.mitre (2), and + JOIN_STYLE.bevel (3). + + The mitre ratio limit is used for very sharp corners. It is the ratio + of the distance from the corner to the end of the mitred offset corner. + When two line segments meet at a sharp angle, a miter join will extend + far beyond the original geometry. To prevent unreasonable geometry, the + mitre limit allows controlling the maximum length of the join corner. + Corners with a ratio which exceed the limit will be beveled. + + Note: the behaviour regarding orientation of the resulting line + depends on the GEOS version. With GEOS < 3.11, the line retains the + same direction for a left offset (positive distance) or has reverse + direction for a right offset (negative distance), and this behaviour + was documented as such in previous Shapely versions. Starting with + GEOS 3.11, the function tries to preserve the orientation of the + original line. + """ + if mitre_limit == 0.0: + raise ValueError("Cannot compute offset from zero-length line segment") + elif not np.isfinite(distance): + raise ValueError("offset_curve distance must be finite") + return shapely.offset_curve( + self, + distance, + quad_segs=quad_segs, + join_style=join_style, + mitre_limit=mitre_limit, + ) + + def parallel_offset( + self, + distance, + side="right", + resolution=16, + join_style=JOIN_STYLE.round, + mitre_limit=5.0, + ): + """Alternative method to :meth:`offset_curve` method. + + Older alternative method to the :meth:`offset_curve` method, but uses + ``resolution`` instead of ``quad_segs`` and a ``side`` keyword + ('left' or 'right') instead of sign of the distance. This method is + kept for backwards compatibility for now, but is is recommended to + use :meth:`offset_curve` instead. + """ + if side == "right": + distance *= -1 + return self.offset_curve( + distance, + quad_segs=resolution, + join_style=join_style, + mitre_limit=mitre_limit, + ) + + +shapely.lib.registry[1] = LineString diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multilinestring.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multilinestring.py new file mode 100644 index 0000000000000000000000000000000000000000..551e77a2b9455b578e85f931c10a39d9f88f9fca --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multilinestring.py @@ -0,0 +1,95 @@ +"""Collections of linestrings and related utilities.""" + +import shapely +from shapely.errors import EmptyPartError +from shapely.geometry import linestring +from shapely.geometry.base import BaseMultipartGeometry + +__all__ = ["MultiLineString"] + + +class MultiLineString(BaseMultipartGeometry): + """A collection of one or more LineStrings. + + A MultiLineString has non-zero length and zero area. + + Parameters + ---------- + lines : sequence + A sequence LineStrings, or a sequence of line-like coordinate + sequences or array-likes (see accepted input for LineString). + + Attributes + ---------- + geoms : sequence + A sequence of LineStrings + + Examples + -------- + Construct a MultiLineString containing two LineStrings. + + >>> from shapely import MultiLineString + >>> lines = MultiLineString([[[0, 0], [1, 2]], [[4, 4], [5, 6]]]) + + """ + + __slots__ = [] + + def __new__(self, lines=None): + """Create a new MultiLineString geometry.""" + if not lines: + # allow creation of empty multilinestrings, to support unpickling + # TODO better empty constructor + return shapely.from_wkt("MULTILINESTRING EMPTY") + elif isinstance(lines, MultiLineString): + return lines + + lines = getattr(lines, "geoms", lines) + subs = [] + for item in lines: + line = linestring.LineString(item) + if line.is_empty: + raise EmptyPartError( + "Can't create MultiLineString with empty component" + ) + subs.append(line) + + if len(lines) == 0: + return shapely.from_wkt("MULTILINESTRING EMPTY") + + return shapely.multilinestrings(subs) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping interface for this MultiLineString.""" + return { + "type": "MultiLineString", + "coordinates": tuple(tuple(c for c in g.coords) for g in self.geoms), + } + + def svg(self, scale_factor=1.0, stroke_color=None, opacity=None): + """Return a group of SVG polyline elements for the LineString geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + stroke_color : str, optional + Hex string for stroke color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.8 + + """ + if self.is_empty: + return "" + if stroke_color is None: + stroke_color = "#66cc99" if self.is_valid else "#ff3333" + return ( + "" + + "".join(p.svg(scale_factor, stroke_color, opacity) for p in self.geoms) + + "" + ) + + +shapely.lib.registry[5] = MultiLineString diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multipoint.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multipoint.py new file mode 100644 index 0000000000000000000000000000000000000000..235046a3328dcdb1315c18e11b377426efeb754f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multipoint.py @@ -0,0 +1,104 @@ +"""Collections of points and related utilities.""" + +import numpy as np + +import shapely +from shapely.errors import EmptyPartError +from shapely.geometry import point +from shapely.geometry.base import BaseMultipartGeometry + +__all__ = ["MultiPoint"] + + +class MultiPoint(BaseMultipartGeometry): + """A collection of one or more Points. + + A MultiPoint has zero area and zero length. + + Parameters + ---------- + points : sequence + A sequence of Points, or a sequence of (x, y [,z]) numeric coordinate + pairs or triples, or an array-like of shape (N, 2) or (N, 3). + + Attributes + ---------- + geoms : sequence + A sequence of Points + + Examples + -------- + Construct a MultiPoint containing two Points + + >>> from shapely import MultiPoint, Point + >>> ob = MultiPoint([[0.0, 0.0], [1.0, 2.0]]) + >>> len(ob.geoms) + 2 + >>> type(ob.geoms[0]) == Point + True + + """ + + __slots__ = [] + + def __new__(self, points=None): + """Create a new MultiPoint geometry.""" + if points is None: + # allow creation of empty multipoints, to support unpickling + # TODO better empty constructor + return shapely.from_wkt("MULTIPOINT EMPTY") + elif isinstance(points, MultiPoint): + return points + elif len(points) == 0: + return shapely.from_wkt("MULTIPOINT EMPTY") + + if isinstance(points, np.ndarray) and np.issubdtype(points.dtype, np.number): + subs = shapely.points(points) + if not subs.ndim == 1: + raise ValueError("Invalid values passed to MultiPoint constructor") + if shapely.is_empty(subs).any(): + raise EmptyPartError("Can't create MultiPoint with empty component") + else: + subs = [] + for item in points: + p = point.Point(item) + if p.is_empty: + raise EmptyPartError("Can't create MultiPoint with empty component") + subs.append(p) + + return shapely.multipoints(subs) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping interface for this MultiPoint.""" + return { + "type": "MultiPoint", + "coordinates": tuple(g.coords[0] for g in self.geoms), + } + + def svg(self, scale_factor=1.0, fill_color=None, opacity=None): + """Return a group of SVG circle elements for the MultiPoint geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG circle diameters. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.6 + + """ + if self.is_empty: + return "" + if fill_color is None: + fill_color = "#66cc99" if self.is_valid else "#ff3333" + return ( + "" + + "".join(p.svg(scale_factor, fill_color, opacity) for p in self.geoms) + + "" + ) + + +shapely.lib.registry[4] = MultiPoint diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multipolygon.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multipolygon.py new file mode 100644 index 0000000000000000000000000000000000000000..073fd86665208978989456fb825c2e1be4afed12 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/multipolygon.py @@ -0,0 +1,125 @@ +"""Collections of polygons and related utilities.""" + +import shapely +from shapely.geometry import polygon +from shapely.geometry.base import BaseMultipartGeometry + +__all__ = ["MultiPolygon"] + + +class MultiPolygon(BaseMultipartGeometry): + """A collection of one or more Polygons. + + If component polygons overlap the collection is invalid and some + operations on it may fail. + + Parameters + ---------- + polygons : sequence + A sequence of Polygons, or a sequence of (shell, holes) tuples + where shell is the sequence representation of a linear ring + (see LinearRing) and holes is a sequence of such linear rings. + + Attributes + ---------- + geoms : sequence + A sequence of `Polygon` instances + + Examples + -------- + Construct a MultiPolygon from a sequence of coordinate tuples + + >>> from shapely import MultiPolygon, Polygon + >>> ob = MultiPolygon([ + ... ( + ... ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), + ... [((0.1,0.1), (0.1,0.2), (0.2,0.2), (0.2,0.1))] + ... ) + ... ]) + >>> len(ob.geoms) + 1 + >>> type(ob.geoms[0]) == Polygon + True + + """ + + __slots__ = [] + + def __new__(self, polygons=None): + """Create a new MultiPolygon geometry.""" + if polygons is None: + # allow creation of empty multipolygons, to support unpickling + # TODO better empty constructor + return shapely.from_wkt("MULTIPOLYGON EMPTY") + elif isinstance(polygons, MultiPolygon): + return polygons + + polygons = getattr(polygons, "geoms", polygons) + # remove None and empty polygons from list of Polygons + polygons = [p for p in polygons if p] + + L = len(polygons) + + # Bail immediately if we have no input points. + if L == 0: + return shapely.from_wkt("MULTIPOLYGON EMPTY") + + # This function does not accept sequences of MultiPolygons: there is + # no implicit flattening. + if any(isinstance(p, MultiPolygon) for p in polygons): + raise ValueError("Sequences of multi-polygons are not valid arguments") + + subs = [] + for i in range(L): + ob = polygons[i] + if not isinstance(ob, polygon.Polygon): + shell = ob[0] + if len(ob) > 1: + holes = ob[1] + else: + holes = None + p = polygon.Polygon(shell, holes) + else: + p = polygon.Polygon(ob) + subs.append(p) + + return shapely.multipolygons(subs) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the MultiPolygon geometry.""" + allcoords = [] + for geom in self.geoms: + coords = [] + coords.append(tuple(geom.exterior.coords)) + for hole in geom.interiors: + coords.append(tuple(hole.coords)) + allcoords.append(tuple(coords)) + return {"type": "MultiPolygon", "coordinates": allcoords} + + def svg(self, scale_factor=1.0, fill_color=None, opacity=None): + """Return group of SVG path elements for the MultiPolygon geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.6 + + """ + if self.is_empty: + return "" + if fill_color is None: + fill_color = "#66cc99" if self.is_valid else "#ff3333" + return ( + "" + + "".join(p.svg(scale_factor, fill_color, opacity) for p in self.geoms) + + "" + ) + + +shapely.lib.registry[6] = MultiPolygon diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/point.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/point.py new file mode 100644 index 0000000000000000000000000000000000000000..217410709695080fbb0f76031595df72f6083934 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/point.py @@ -0,0 +1,166 @@ +"""Points and related utilities.""" + +import numpy as np + +import shapely +from shapely.errors import DimensionError +from shapely.geometry.base import BaseGeometry + +__all__ = ["Point"] + + +class Point(BaseGeometry): + """A geometry type that represents a single coordinate. + + Each coordinate has x, y and possibly z and/or m values. + + A point is a zero-dimensional feature and has zero length and zero area. + + Parameters + ---------- + args : float, or sequence of floats + The coordinates can either be passed as a single parameter, or as + individual float values using multiple parameters: + + 1) 1 parameter: a sequence or array-like of with 2 or 3 values. + 2) 2 or 3 parameters (float): x, y, and possibly z. + + Attributes + ---------- + x, y, z, m : float + Coordinate values + + Examples + -------- + Constructing the Point using separate parameters for x and y: + + >>> from shapely import Point + >>> p = Point(1.0, -1.0) + + Constructing the Point using a list of x, y coordinates: + + >>> p = Point([1.0, -1.0]) + >>> print(p) + POINT (1 -1) + >>> p.y + -1.0 + >>> p.x + 1.0 + + """ + + __slots__ = [] + + def __new__(self, *args): + """Create a new Point geometry.""" + if len(args) == 0: + # empty geometry + # TODO better constructor + return shapely.from_wkt("POINT EMPTY") + elif len(args) > 3: + raise TypeError(f"Point() takes at most 3 arguments ({len(args)} given)") + elif len(args) == 1: + coords = args[0] + if isinstance(coords, Point): + return coords + + # Accept either (x, y) or [(x, y)] + if not hasattr(coords, "__getitem__"): # generators + coords = list(coords) + coords = np.asarray(coords).squeeze() + else: + # 2 or 3 args + coords = np.array(args).squeeze() + + if coords.ndim > 1: + raise ValueError( + f"Point() takes only scalar or 1-size vector arguments, got {args}" + ) + if not np.issubdtype(coords.dtype, np.number): + coords = [float(c) for c in coords] + geom = shapely.points(coords) + if not isinstance(geom, Point): + raise ValueError("Invalid values passed to Point constructor") + return geom + + # Coordinate getters and setters + + @property + def x(self): + """Return x coordinate.""" + return float(shapely.get_x(self)) + + @property + def y(self): + """Return y coordinate.""" + return float(shapely.get_y(self)) + + @property + def z(self): + """Return z coordinate.""" + z = shapely.get_z(self) + if np.isnan(z) and not shapely.has_z(self): + raise DimensionError("This point has no z coordinate.") + return float(z) + + @property + def m(self): + """Return m coordinate. + + .. versionadded:: 2.1.0 + Also requires GEOS 3.12.0 or later. + """ + if not shapely.has_m(self): + raise DimensionError("This point has no m coordinate.") + return float(shapely.get_m(self)) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the Point geometry.""" + coords = self.coords + return {"type": "Point", "coordinates": coords[0] if len(coords) > 0 else ()} + + def svg(self, scale_factor=1.0, fill_color=None, opacity=None): + """Return SVG circle element for the Point geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG circle diameter. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.6 + + """ + if self.is_empty: + return "" + if fill_color is None: + fill_color = "#66cc99" if self.is_valid else "#ff3333" + if opacity is None: + opacity = 0.6 + return ( + f'' + ) + + @property + def xy(self): + """Separate arrays of X and Y coordinate values. + + Examples + -------- + >>> from shapely import Point + >>> x, y = Point(0, 0).xy + >>> list(x) + [0.0] + >>> list(y) + [0.0] + + """ + return self.coords.xy + + +shapely.lib.registry[0] = Point diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/polygon.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/polygon.py new file mode 100644 index 0000000000000000000000000000000000000000..c7793e785f73e7c6b7d23a6d66206f9af02d0fa0 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geometry/polygon.py @@ -0,0 +1,345 @@ +"""Polygons and their linear ring components.""" + +import numpy as np + +import shapely +from shapely import _geometry_helpers +from shapely.algorithms.cga import signed_area # noqa +from shapely.errors import TopologicalError +from shapely.geometry.base import BaseGeometry +from shapely.geometry.linestring import LineString +from shapely.geometry.point import Point + +__all__ = ["LinearRing", "Polygon", "orient"] + + +def _unpickle_linearring(wkb): + linestring = shapely.from_wkb(wkb) + srid = shapely.get_srid(linestring) + linearring = _geometry_helpers.linestring_to_linearring(linestring) + if srid: + linearring = shapely.set_srid(linearring, srid) + return linearring + + +class LinearRing(LineString): + """Geometry type composed of one or more line segments that forms a closed loop. + + A LinearRing is a closed, one-dimensional feature. + A LinearRing that crosses itself or touches itself at a single point is + invalid and operations on it may fail. + + Parameters + ---------- + coordinates : sequence + A sequence of (x, y [,z]) numeric coordinate pairs or triples, or + an array-like with shape (N, 2) or (N, 3). + Also can be a sequence of Point objects. + + Notes + ----- + Rings are automatically closed. There is no need to specify a final + coordinate pair identical to the first. + + Examples + -------- + Construct a square ring. + + >>> from shapely import LinearRing + >>> ring = LinearRing( ((0, 0), (0, 1), (1 ,1 ), (1 , 0)) ) + >>> ring.is_closed + True + >>> list(ring.coords) + [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)] + >>> ring.length + 4.0 + + """ + + __slots__ = [] + + def __new__(self, coordinates=None): + """Create a new LinearRing geometry.""" + if coordinates is None: + # empty geometry + # TODO better way? + return shapely.from_wkt("LINEARRING EMPTY") + elif isinstance(coordinates, LineString): + if type(coordinates) is LinearRing: + # return original objects since geometries are immutable + return coordinates + elif not coordinates.is_valid: + raise TopologicalError("An input LineString must be valid.") + else: + # LineString + # TODO convert LineString to LinearRing more directly? + coordinates = coordinates.coords + + else: + if hasattr(coordinates, "__array__"): + coordinates = np.asarray(coordinates) + if isinstance(coordinates, np.ndarray) and np.issubdtype( + coordinates.dtype, np.number + ): + pass + else: + # check coordinates on points + def _coords(o): + if isinstance(o, Point): + return o.coords[0] + else: + return [float(c) for c in o] + + coordinates = np.array([_coords(o) for o in coordinates]) + if not np.issubdtype(coordinates.dtype, np.number): + # conversion of coords to 2D array failed, this might be due + # to inconsistent coordinate dimensionality + raise ValueError("Inconsistent coordinate dimensionality") + + if len(coordinates) == 0: + # empty geometry + # TODO better constructor + should shapely.linearrings handle this? + return shapely.from_wkt("LINEARRING EMPTY") + + geom = shapely.linearrings(coordinates) + if not isinstance(geom, LinearRing): + raise ValueError("Invalid values passed to LinearRing constructor") + return geom + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the LinearRing geometry.""" + return {"type": "LinearRing", "coordinates": tuple(self.coords)} + + def __reduce__(self): + """Pickle support. + + WKB doesn't differentiate between LineString and LinearRing so we + need to move the coordinate sequence into the correct geometry type + """ + return (_unpickle_linearring, (shapely.to_wkb(self, include_srid=True),)) + + @property + def is_ccw(self): + """True if the ring is oriented counter clock-wise.""" + return bool(shapely.is_ccw(self)) + + @property + def is_simple(self): + """True if the geometry is simple. + + Simple means that any self-intersections are only at boundary points. + """ + return bool(shapely.is_simple(self)) + + +shapely.lib.registry[2] = LinearRing + + +class InteriorRingSequence: + _parent = None + _ndim = None + _index = 0 + _length = 0 + + def __init__(self, parent): + self._parent = parent + self._ndim = parent._ndim + + def __iter__(self): + self._index = 0 + self._length = self.__len__() + return self + + def __next__(self): + if self._index < self._length: + ring = self._get_ring(self._index) + self._index += 1 + return ring + else: + raise StopIteration + + def __len__(self): + return shapely.get_num_interior_rings(self._parent) + + def __getitem__(self, key): + m = self.__len__() + if isinstance(key, int): + if key + m < 0 or key >= m: + raise IndexError("index out of range") + if key < 0: + i = m + key + else: + i = key + return self._get_ring(i) + elif isinstance(key, slice): + res = [] + start, stop, stride = key.indices(m) + for i in range(start, stop, stride): + res.append(self._get_ring(i)) + return res + else: + raise TypeError("key must be an index or slice") + + def _get_ring(self, i): + return shapely.get_interior_ring(self._parent, i) + + +class Polygon(BaseGeometry): + """A geometry type representing an area that is enclosed by a linear ring. + + A polygon is a two-dimensional feature and has a non-zero area. It may + have one or more negative-space "holes" which are also bounded by linear + rings. If any rings cross each other, the feature is invalid and + operations on it may fail. + + Parameters + ---------- + shell : sequence + A sequence of (x, y [,z]) numeric coordinate pairs or triples, or + an array-like with shape (N, 2) or (N, 3). + Also can be a sequence of Point objects. + holes : sequence + A sequence of objects which satisfy the same requirements as the + shell parameters above + + Attributes + ---------- + exterior : LinearRing + The ring which bounds the positive space of the polygon. + interiors : sequence + A sequence of rings which bound all existing holes. + + Examples + -------- + Create a square polygon with no holes + + >>> from shapely import Polygon + >>> coords = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) + >>> polygon = Polygon(coords) + >>> polygon.area + 1.0 + + """ + + __slots__ = [] + + def __new__(self, shell=None, holes=None): + """Create a new Polygon geometry.""" + if shell is None: + # empty geometry + # TODO better way? + return shapely.from_wkt("POLYGON EMPTY") + elif isinstance(shell, Polygon): + # return original objects since geometries are immutable + return shell + else: + shell = LinearRing(shell) + + if holes is not None: + if len(holes) == 0: + # shapely constructor cannot handle holes=[] + holes = None + else: + holes = [LinearRing(ring) for ring in holes] + + geom = shapely.polygons(shell, holes=holes) + if not isinstance(geom, Polygon): + raise ValueError("Invalid values passed to Polygon constructor") + return geom + + @property + def exterior(self): + """Return the exterior ring of the polygon.""" + return shapely.get_exterior_ring(self) + + @property + def interiors(self): + """Return the sequence of interior rings of the polygon.""" + if self.is_empty: + return [] + return InteriorRingSequence(self) + + @property + def coords(self): + """Not implemented for polygons.""" + raise NotImplementedError( + "Component rings have coordinate sequences, but the polygon does not" + ) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the Polygon geometry.""" + if self.exterior == LinearRing(): + coords = [] + else: + coords = [tuple(self.exterior.coords)] + for hole in self.interiors: + coords.append(tuple(hole.coords)) + return {"type": "Polygon", "coordinates": tuple(coords)} + + def svg(self, scale_factor=1.0, fill_color=None, opacity=None): + """Return SVG path element for the Polygon geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.6 + + """ + if self.is_empty: + return "" + if fill_color is None: + fill_color = "#66cc99" if self.is_valid else "#ff3333" + if opacity is None: + opacity = 0.6 + exterior_coords = [["{},{}".format(*c) for c in self.exterior.coords]] + interior_coords = [ + ["{},{}".format(*c) for c in interior.coords] for interior in self.interiors + ] + path = " ".join( + [ + "M {} L {} z".format(coords[0], " L ".join(coords[1:])) + for coords in exterior_coords + interior_coords + ] + ) + return ( + f'' + ) + + @classmethod + def from_bounds(cls, xmin, ymin, xmax, ymax): + """Construct a `Polygon()` from spatial bounds.""" + return cls([(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]) + + +shapely.lib.registry[3] = Polygon + + +def orient(polygon, sign=1.0): + """Return an oriented polygon. + + It is recommended to use :func:`shapely.orient_polygons` instead. + + Parameters + ---------- + polygon : shapely.Polygon + sign : float, default 1. + The sign of the result's signed area. + A non-negative sign means that the coordinates of the geometry's exterior + rings will be oriented counter-clockwise. + + Returns + ------- + Geometry or array_like + + Refer to :func:`shapely.orient_polygons` for full documentation. + + """ + return shapely.orient_polygons(polygon, exterior_cw=sign < 0.0) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geos.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geos.py new file mode 100644 index 0000000000000000000000000000000000000000..3667365ef44c46a736ee98676265c8cec71bcbe4 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/geos.py @@ -0,0 +1,17 @@ +"""Proxies for libgeos, GEOS-specific exceptions, and utilities.""" + +import warnings + +import shapely + +warnings.warn( + "The 'shapely.geos' module is deprecated, and will be removed in a future version. " + "All attributes of 'shapely.geos' are available directly from the top-level " + "'shapely' namespace (since shapely 2.0.0).", + DeprecationWarning, + stacklevel=2, +) + +geos_version_string = shapely.geos_capi_version_string +geos_version = shapely.geos_version +geos_capi_version = shapely.geos_capi_version diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/io.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/io.py new file mode 100644 index 0000000000000000000000000000000000000000..38c46bb2f0fd1345b4b79cbb355e39e87fd28790 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/io.py @@ -0,0 +1,408 @@ +"""Input/output functions for Shapely geometries.""" + +import numpy as np + +from shapely import geos_version, lib +from shapely._enum import ParamEnum + +# include ragged array functions here for reference documentation purpose +from shapely._ragged_array import from_ragged_array, to_ragged_array +from shapely.decorators import requires_geos +from shapely.errors import UnsupportedGEOSVersionError + +__all__ = [ + "from_geojson", + "from_ragged_array", + "from_wkb", + "from_wkt", + "to_geojson", + "to_ragged_array", + "to_wkb", + "to_wkt", +] + + +# Allowed options for handling WKB/WKT decoding errors +# Note: cannot use standard constructor since "raise" is a keyword +DecodingErrorOptions = ParamEnum( + "DecodingErrorOptions", {"ignore": 0, "warn": 1, "raise": 2, "fix": 3} +) + +WKBFlavorOptions = ParamEnum("WKBFlavorOptions", {"extended": 1, "iso": 2}) + + +def to_wkt( + geometry, + rounding_precision=6, + trim=True, + output_dimension=None, + old_3d=False, + **kwargs, +): + """Convert to the Well-Known Text (WKT) representation of a Geometry. + + The Well-known Text format is defined in the `OGC Simple Features + Specification for SQL `__. + + The following limitations apply to WKT serialization: + + - only simple empty geometries can be 3D, empty collections are always 2D + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to convert to WKT. + rounding_precision : int, default 6 + The rounding precision when writing the WKT string. Set to a value of + -1 to indicate the full precision. + trim : bool, default True + If True, trim unnecessary decimals (trailing zeros). If False, + use fixed-precision number formatting. + output_dimension : int, default None + The output dimension for the WKT string. Supported values are 2, 3 and + 4 for GEOS 3.12+. Default None will automatically choose 3 or 4, + depending on the version of GEOS. + Specifying 3 means that up to 3 dimensions will be written but 2D + geometries will still be represented as 2D in the WKT string. + old_3d : bool, default False + Enable old style 3D/4D WKT generation. By default, new style 3D/4D WKT + (ie. "POINT Z (10 20 30)") is returned, but with ``old_3d=True`` + the WKT will be formatted in the style "POINT (10 20 30)". + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> shapely.to_wkt(Point(0, 0)) + 'POINT (0 0)' + >>> shapely.to_wkt(Point(0, 0), rounding_precision=3, trim=False) + 'POINT (0.000 0.000)' + >>> shapely.to_wkt(Point(0, 0), rounding_precision=-1, trim=False) + 'POINT (0.0000000000000000 0.0000000000000000)' + >>> shapely.to_wkt(Point(1, 2, 3), trim=True) + 'POINT Z (1 2 3)' + >>> shapely.to_wkt(Point(1, 2, 3), trim=True, output_dimension=2) + 'POINT (1 2)' + >>> shapely.to_wkt(Point(1, 2, 3), trim=True, old_3d=True) + 'POINT (1 2 3)' + + Notes + ----- + The defaults differ from the default of some GEOS versions. To mimic this for + versions before GEOS 3.12, use:: + + shapely.to_wkt(geometry, rounding_precision=-1, trim=False, output_dimension=2) + + """ + if not np.isscalar(rounding_precision): + raise TypeError("rounding_precision only accepts scalar values") + if not np.isscalar(trim): + raise TypeError("trim only accepts scalar values") + if output_dimension is None: + output_dimension = 3 if geos_version < (3, 12, 0) else 4 + elif not np.isscalar(output_dimension): + raise TypeError("output_dimension only accepts scalar values") + if not np.isscalar(old_3d): + raise TypeError("old_3d only accepts scalar values") + + return lib.to_wkt( + geometry, + np.intc(rounding_precision), + np.bool_(trim), + np.intc(output_dimension), + np.bool_(old_3d), + **kwargs, + ) + + +def to_wkb( + geometry, + hex=False, + output_dimension=None, + byte_order=-1, + include_srid=False, + flavor="extended", + **kwargs, +): + r"""Convert to the Well-Known Binary (WKB) representation of a Geometry. + + The Well-Known Binary format is defined in the `OGC Simple Features + Specification for SQL `__. + + The following limitations apply to WKB serialization: + + - linearrings will be converted to linestrings + - a point with only NaN coordinates is converted to an empty point + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to convert to WKB. + hex : bool, default False + If true, export the WKB as a hexadecimal string. The default is to + return a binary bytes object. + output_dimension : int, default None + The output dimension for the WKB. Supported values are 2, 3 and 4 for + GEOS 3.12+. Default None will automatically choose 3 or 4, depending on + the version of GEOS. + Specifying 3 means that up to 3 dimensions will be written but 2D + geometries will still be represented as 2D in the WKB representation. + byte_order : int, default -1 + Defaults to native machine byte order (-1). Use 0 to force big endian + and 1 for little endian. + include_srid : bool, default False + If True, the SRID is be included in WKB (this is an extension + to the OGC WKB specification). Not allowed when flavor is "iso". + flavor : {"iso", "extended"}, default "extended" + Which flavor of WKB will be returned. The flavor determines how + extra dimensionality is encoded with the type number, and whether + SRID can be included in the WKB. ISO flavor is "more standard" for + 3D output, and does not support SRID embedding. + Both flavors are equivalent when ``output_dimension=2`` (or with 2D + geometries) and ``include_srid=False``. + The `from_wkb` function can read both flavors. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> point = Point(1, 1) + >>> shapely.to_wkb(point, byte_order=1) + b'\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?' + >>> shapely.to_wkb(point, hex=True, byte_order=1) + '0101000000000000000000F03F000000000000F03F' + + """ + if not np.isscalar(hex): + raise TypeError("hex only accepts scalar values") + if output_dimension is None: + output_dimension = 3 if geos_version < (3, 12, 0) else 4 + elif not np.isscalar(output_dimension): + raise TypeError("output_dimension only accepts scalar values") + if not np.isscalar(byte_order): + raise TypeError("byte_order only accepts scalar values") + if not np.isscalar(include_srid): + raise TypeError("include_srid only accepts scalar values") + if not np.isscalar(flavor): + raise TypeError("flavor only accepts scalar values") + if lib.geos_version < (3, 10, 0) and flavor == "iso": + raise UnsupportedGEOSVersionError( + 'The "iso" option requires at least GEOS 3.10.0' + ) + if flavor == "iso" and include_srid: + raise ValueError('flavor="iso" and include_srid=True cannot be used together') + flavor = WKBFlavorOptions.get_value(flavor) + + return lib.to_wkb( + geometry, + np.bool_(hex), + np.intc(output_dimension), + np.intc(byte_order), + np.bool_(include_srid), + np.intc(flavor), + **kwargs, + ) + + +@requires_geos("3.10.0") +def to_geojson(geometry, indent=None, **kwargs): + """Convert to the GeoJSON representation of a Geometry. + + The GeoJSON format is defined in the `RFC 7946 `__. + NaN (not-a-number) coordinates will be written as 'null'. + + The following are currently unsupported: + + - Geometries of type LINEARRING: these are output as 'null'. + - Three-dimensional geometries: the third dimension is ignored. + + Parameters + ---------- + geometry : str, bytes or array_like + Geometry or geometries to convert to GeoJSON. + indent : int, optional + If indent is a non-negative integer, then GeoJSON will be formatted. + An indent level of 0 will only insert newlines. None (the default) + selects the most compact representation. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> point = Point(1, 1) + >>> shapely.to_geojson(point) + '{"type":"Point","coordinates":[1.0,1.0]}' + >>> print(shapely.to_geojson(point, indent=2)) + { + "type": "Point", + "coordinates": [ + 1.0, + 1.0 + ] + } + + """ + # GEOS Tickets: + # - handle linearrings: https://trac.osgeo.org/geos/ticket/1140 + # - support 3D: https://trac.osgeo.org/geos/ticket/1141 + if indent is None: + indent = -1 + elif not np.isscalar(indent): + raise TypeError("indent only accepts scalar values") + elif indent < 0: + raise ValueError("indent cannot be negative") + + return lib.to_geojson(geometry, np.intc(indent), **kwargs) + + +def from_wkt(geometry, on_invalid="raise", **kwargs): + """Create geometries from the Well-Known Text (WKT) representation. + + The Well-known Text format is defined in the `OGC Simple Features + Specification for SQL `__. + + Parameters + ---------- + geometry : str or array_like + The WKT string(s) to convert. + on_invalid : {"raise", "warn", "ignore", "fix"}, default "raise" + Indicates what to do when an invalid WKT string is encountered. Note + that the validations involved are very basic, e.g. the minimum number of + points for the geometry type. For a thorough check, use + :func:`is_valid` after conversion to geometries. Valid options are: + + - raise: an exception will be raised if any input geometry is invalid. + - warn: a warning will be raised and invalid WKT geometries will be + returned as ``None``. + - ignore: invalid geometries will be returned as ``None`` without a + warning. + - fix: an effort is made to fix invalid input geometries (currently just + unclosed rings). If this is not possible, they are returned as + ``None`` without a warning. Requires GEOS >= 3.11. + + .. versionadded:: 2.1.0 + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> shapely.from_wkt('POINT (0 0)') + + + """ + if not np.isscalar(on_invalid): + raise TypeError("on_invalid only accepts scalar values") + + invalid_handler = np.uint8(DecodingErrorOptions.get_value(on_invalid)) + + return lib.from_wkt(geometry, invalid_handler, **kwargs) + + +def from_wkb(geometry, on_invalid="raise", **kwargs): + r"""Create geometries from the Well-Known Binary (WKB) representation. + + The Well-Known Binary format is defined in the `OGC Simple Features + Specification for SQL `__. + + Parameters + ---------- + geometry : str or array_like + The WKB byte object(s) to convert. + on_invalid : {"raise", "warn", "ignore", "fix"}, default "raise" + Indicates what to do when an invalid WKB is encountered. Note that the + validations involved are very basic, e.g. the minimum number of points + for the geometry type. For a thorough check, use :func:`is_valid` after + conversion to geometries. Valid options are: + + - raise: an exception will be raised if any input geometry is invalid. + - warn: a warning will be raised and invalid WKT geometries will be + returned as ``None``. + - ignore: invalid geometries will be returned as ``None`` without a + warning. + - fix: an effort is made to fix invalid input geometries (currently just + unclosed rings). If this is not possible, they are returned as + ``None`` without a warning. Requires GEOS >= 3.11. + + .. versionadded:: 2.1.0 + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> shapely.from_wkb(b'\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?') + + + """ # noqa: E501 + if not np.isscalar(on_invalid): + raise TypeError("on_invalid only accepts scalar values") + + invalid_handler = np.uint8(DecodingErrorOptions.get_value(on_invalid)) + + # ensure the input has object dtype, to avoid numpy inferring it as a + # fixed-length string dtype (which removes trailing null bytes upon access + # of array elements) + geometry = np.asarray(geometry, dtype=object) + return lib.from_wkb(geometry, invalid_handler, **kwargs) + + +@requires_geos("3.10.1") +def from_geojson(geometry, on_invalid="raise", **kwargs): + """Create geometries from GeoJSON representations (strings). + + If a GeoJSON is a FeatureCollection, it is read as a single geometry + (with type GEOMETRYCOLLECTION). This may be unpacked using + :meth:`shapely.get_parts`. Properties are not read. + + The GeoJSON format is defined in `RFC 7946 `__. + + The following are currently unsupported: + + - Three-dimensional geometries: the third dimension is ignored. + - Geometries having 'null' in the coordinates. + + Parameters + ---------- + geometry : str, bytes or array_like + The GeoJSON string or byte object(s) to convert. + on_invalid : {"raise", "warn", "ignore"}, default "raise" + - raise: an exception will be raised if an input GeoJSON is invalid. + - warn: a warning will be raised and invalid input geometries will be + returned as ``None``. + - ignore: invalid input geometries will be returned as ``None`` without + a warning. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_parts + + Examples + -------- + >>> import shapely + >>> shapely.from_geojson('{"type": "Point","coordinates": [1, 2]}') + + + """ + # GEOS Tickets: + # - support 3D: https://trac.osgeo.org/geos/ticket/1141 + # - handle null coordinates: https://trac.osgeo.org/geos/ticket/1142 + if not np.isscalar(on_invalid): + raise TypeError("on_invalid only accepts scalar values") + + invalid_handler = np.uint8(DecodingErrorOptions.get_value(on_invalid)) + + # ensure the input has object dtype, to avoid numpy inferring it as a + # fixed-length string dtype (which removes trailing null bytes upon access + # of array elements) + geometry = np.asarray(geometry, dtype=object) + + return lib.from_geojson(geometry, invalid_handler, **kwargs) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/linear.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..38c58c882b63d2e7134044568576e68cd55c07af --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/linear.py @@ -0,0 +1,236 @@ +"""Linear geometry functions.""" + +from shapely import lib +from shapely.decorators import deprecate_positional, multithreading_enabled +from shapely.errors import UnsupportedGEOSVersionError + +__all__ = [ + "line_interpolate_point", + "line_locate_point", + "line_merge", + "shared_paths", + "shortest_line", +] + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# line_interpolate_point(line, distance, normalized=False, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'normalized' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'normalized' +# line_interpolate_point(line, distance, *, normalized=False, **kwargs) + + +@deprecate_positional(["normalized"], category=DeprecationWarning) +@multithreading_enabled +def line_interpolate_point(line, distance, normalized=False, **kwargs): + """Return a point interpolated at given distance on a line. + + Parameters + ---------- + line : Geometry or array_like + For multilinestrings or geometrycollections, the first geometry is taken + and the rest is ignored. This function raises a TypeError for non-linear + geometries. For empty linear geometries, empty points are returned. + distance : float or array_like + Negative values measure distance from the end of the line. Out-of-range + values will be clipped to the line endings. + normalized : bool, default False + If True, the distance is a fraction of the total + line length instead of the absolute distance. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line = LineString([(0, 2), (0, 10)]) + >>> shapely.line_interpolate_point(line, 2) + + >>> shapely.line_interpolate_point(line, 100) + + >>> shapely.line_interpolate_point(line, -2) + + >>> shapely.line_interpolate_point(line, [0.25, -0.25], normalized=True).tolist() + [, ] + >>> shapely.line_interpolate_point(LineString(), 1) + + + """ + if normalized: + return lib.line_interpolate_point_normalized(line, distance) + else: + return lib.line_interpolate_point(line, distance) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# line_locate_point(line, other, normalized=False, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'normalized' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'normalized' +# line_locate_point(line, other, *, normalized=False, **kwargs) + + +@deprecate_positional(["normalized"], category=DeprecationWarning) +@multithreading_enabled +def line_locate_point(line, other, normalized=False, **kwargs): + """Return the distance to the line origin of given point. + + If given point does not intersect with the line, the point will first be + projected onto the line after which the distance is taken. + + Parameters + ---------- + line : Geometry or array_like + Line or lines to calculate the distance to. + other : Geometry or array_like + Point or points to calculate the distance from. + normalized : bool, default False + If True, the distance is a fraction of the total line length instead of + the absolute distance. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> line = LineString([(0, 2), (0, 10)]) + >>> point = Point(4, 4) + >>> shapely.line_locate_point(line, point) + 2.0 + >>> shapely.line_locate_point(line, point, normalized=True) + 0.25 + >>> shapely.line_locate_point(line, Point(0, 18)) + 8.0 + >>> shapely.line_locate_point(LineString(), point) + nan + + """ + if normalized: + return lib.line_locate_point_normalized(line, other) + else: + return lib.line_locate_point(line, other) + + +@multithreading_enabled +def line_merge(line, directed=False, **kwargs): + """Return (Multi)LineStrings formed by combining the lines in a MultiLineString. + + Lines are joined together at their endpoints in case two lines are + intersecting. Lines are not joined when 3 or more lines are intersecting at + the endpoints. Line elements that cannot be joined are kept as is in the + resulting MultiLineString. + + The direction of each merged LineString will be that of the majority of the + LineStrings from which it was derived. Except if ``directed=True`` is + specified, then the operation will not change the order of points within + lines and so only lines which can be joined with no change in direction + are merged. + + Parameters + ---------- + line : Geometry or array_like + Linear geometry or geometries to merge. + directed : bool, default False + Only combine lines if possible without changing point order. + Requires GEOS >= 3.11.0 + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import MultiLineString + >>> shapely.line_merge(MultiLineString([[(0, 2), (0, 10)], [(0, 10), (5, 10)]])) + + >>> shapely.line_merge(MultiLineString([[(0, 2), (0, 10)], [(0, 11), (5, 10)]])) + + >>> shapely.line_merge(MultiLineString()) + + >>> shapely.line_merge(MultiLineString([[(0, 0), (1, 0)], [(0, 0), (3, 0)]])) + + >>> shapely.line_merge(MultiLineString([[(0, 0), (1, 0)], [(0, 0), (3, 0)]]), \ +directed=True) + + + """ + if directed: + if lib.geos_version < (3, 11, 0): + raise UnsupportedGEOSVersionError( + "'{}' requires at least GEOS {}.{}.{}.".format( + "line_merge", *(3, 11, 0) + ) + ) + return lib.line_merge_directed(line, **kwargs) + return lib.line_merge(line, **kwargs) + + +@multithreading_enabled +def shared_paths(a, b, **kwargs): + """Return the shared paths between a and b. + + Both geometries should be linestrings or arrays of linestrings. + A geometrycollection or array of geometrycollections is returned + with two elements in each geometrycollection. The first element is a + multilinestring containing shared paths with the same direction + for both inputs. The second element is a multilinestring containing + shared paths with the opposite direction for the two inputs. + + Parameters + ---------- + a, b : Geometry or array_like + Linestring or linestrings to compare. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line1 = LineString([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> line2 = LineString([(1, 0), (2, 0), (2, 1), (1, 1), (1, 0)]) + >>> shapely.shared_paths(line1, line2).wkt + 'GEOMETRYCOLLECTION (MULTILINESTRING EMPTY, MULTILINESTRING ((1 0, 1 1)))' + >>> line3 = LineString([(1, 1), (0, 1)]) + >>> shapely.shared_paths(line1, line3).wkt + 'GEOMETRYCOLLECTION (MULTILINESTRING ((1 1, 0 1)), MULTILINESTRING EMPTY)' + + """ + return lib.shared_paths(a, b, **kwargs) + + +@multithreading_enabled +def shortest_line(a, b, **kwargs): + """Return the shortest line between two geometries. + + The resulting line consists of two points, representing the nearest + points between the geometry pair. The line always starts in the first + geometry `a` and ends in the second geometry `b`. The endpoints of the + line will not necessarily be existing vertices of the input geometries + `a` and `b`, but can also be a point along a line segment. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to compare. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line1 = LineString([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> line2 = LineString([(0, 3), (3, 0), (5, 3)]) + >>> shapely.shortest_line(line1, line2) + + + """ + return lib.shortest_line(a, b, **kwargs) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/measurement.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/measurement.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4f9c96ec7b1f1b80f4a82a787d7d2b3a240563 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/measurement.py @@ -0,0 +1,355 @@ +"""Methods for measuring (between) geometries.""" + +import warnings + +import numpy as np + +from shapely import lib +from shapely.decorators import multithreading_enabled + +__all__ = [ + "area", + "bounds", + "distance", + "frechet_distance", + "hausdorff_distance", + "length", + "minimum_bounding_radius", + "minimum_clearance", + "total_bounds", +] + + +@multithreading_enabled +def area(geometry, **kwargs): + """Compute the area of a (multi)polygon. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the area. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import MultiPolygon, Polygon + >>> polygon = Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]) + >>> shapely.area(polygon) + 100.0 + >>> polygon2 = Polygon([(10, 10), (10, 20), (20, 20), (20, 10), (10, 10)]) + >>> shapely.area(MultiPolygon([polygon, polygon2])) + 200.0 + >>> shapely.area(Polygon()) + 0.0 + >>> shapely.area(None) + nan + + """ + return lib.area(geometry, **kwargs) + + +@multithreading_enabled +def distance(a, b, **kwargs): + """Compute the Cartesian distance between two geometries. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to compute the distance between. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> point = Point(0, 0) + >>> shapely.distance(Point(10, 0), point) + 10.0 + >>> shapely.distance(LineString([(1, 1), (1, -1)]), point) + 1.0 + >>> shapely.distance(Polygon([(3, 0), (5, 0), (5, 5), (3, 5), (3, 0)]), point) + 3.0 + >>> shapely.distance(Point(), point) + nan + >>> shapely.distance(None, point) + nan + + """ + return lib.distance(a, b, **kwargs) + + +@multithreading_enabled +def bounds(geometry, **kwargs): + """Compute the bounds (extent) of a geometry. + + For each geometry these 4 numbers are returned: min x, min y, max x, max y. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the bounds. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> shapely.bounds(Point(2, 3)).tolist() + [2.0, 3.0, 2.0, 3.0] + >>> shapely.bounds(LineString([(0, 0), (0, 2), (3, 2)])).tolist() + [0.0, 0.0, 3.0, 2.0] + >>> shapely.bounds(Polygon()).tolist() + [nan, nan, nan, nan] + >>> shapely.bounds(None).tolist() + [nan, nan, nan, nan] + + """ + return lib.bounds(geometry, **kwargs) + + +def total_bounds(geometry, **kwargs): + """Compute the total bounds (extent) of the geometry. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the total bounds. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Returns + ------- + numpy ndarray of [xmin, ymin, xmax, ymax] + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> shapely.total_bounds(Point(2, 3)).tolist() + [2.0, 3.0, 2.0, 3.0] + >>> shapely.total_bounds([Point(2, 3), Point(4, 5)]).tolist() + [2.0, 3.0, 4.0, 5.0] + >>> shapely.total_bounds([ + ... LineString([(0, 1), (0, 2), (3, 2)]), + ... LineString([(4, 4), (4, 6), (6, 7)]) + ... ]).tolist() + [0.0, 1.0, 6.0, 7.0] + >>> shapely.total_bounds(Polygon()).tolist() + [nan, nan, nan, nan] + >>> shapely.total_bounds([Polygon(), Point(2, 3)]).tolist() + [2.0, 3.0, 2.0, 3.0] + >>> shapely.total_bounds(None).tolist() + [nan, nan, nan, nan] + + """ + b = bounds(geometry, **kwargs) + if b.ndim == 1: + return b + + with warnings.catch_warnings(): + # ignore 'All-NaN slice encountered' warnings + warnings.simplefilter("ignore", RuntimeWarning) + return np.array( + [ + np.nanmin(b[..., 0]), + np.nanmin(b[..., 1]), + np.nanmax(b[..., 2]), + np.nanmax(b[..., 3]), + ] + ) + + +@multithreading_enabled +def length(geometry, **kwargs): + """Compute the length of a (multi)linestring or polygon perimeter. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the length. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, MultiLineString, Polygon + >>> shapely.length(LineString([(0, 0), (0, 2), (3, 2)])) + 5.0 + >>> shapely.length(MultiLineString([ + ... LineString([(0, 0), (1, 0)]), + ... LineString([(1, 0), (2, 0)]) + ... ])) + 2.0 + >>> shapely.length(Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)])) + 40.0 + >>> shapely.length(LineString()) + 0.0 + >>> shapely.length(None) + nan + + """ + return lib.length(geometry, **kwargs) + + +@multithreading_enabled +def hausdorff_distance(a, b, densify=None, **kwargs): + """Compute the discrete Hausdorff distance between two geometries. + + The Hausdorff distance is a measure of similarity: it is the greatest + distance between any point in A and the closest point in B. The discrete + distance is an approximation of this metric: only vertices are considered. + The parameter 'densify' makes this approximation less coarse by splitting + the line segments between vertices before computing the distance. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to compute the distance between. + densify : float or array_like, optional + The value of densify is required to be between 0 and 1. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line1 = LineString([(130, 0), (0, 0), (0, 150)]) + >>> line2 = LineString([(10, 10), (10, 150), (130, 10)]) + >>> shapely.hausdorff_distance(line1, line2) + 14.142135623730951 + >>> shapely.hausdorff_distance(line1, line2, densify=0.5) + 70.0 + >>> shapely.hausdorff_distance(line1, LineString()) + nan + >>> shapely.hausdorff_distance(line1, None) + nan + + """ + if densify is None: + return lib.hausdorff_distance(a, b, **kwargs) + else: + return lib.hausdorff_distance_densify(a, b, densify, **kwargs) + + +@multithreading_enabled +def frechet_distance(a, b, densify=None, **kwargs): + """Compute the discrete Fréchet distance between two geometries. + + The Fréchet distance is a measure of similarity: it is the greatest + distance between any point in A and the closest point in B. The discrete + distance is an approximation of this metric: only vertices are considered. + The parameter 'densify' makes this approximation less coarse by splitting + the line segments between vertices before computing the distance. + + Fréchet distance sweep continuously along their respective curves + and the direction of curves is significant. This makes it a better measure + of similarity than Hausdorff distance for curve or surface matching. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to compute the distance between. + densify : float or array_like, optional + The value of densify is required to be between 0 and 1. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line1 = LineString([(0, 0), (100, 0)]) + >>> line2 = LineString([(0, 0), (50, 50), (100, 0)]) + >>> shapely.frechet_distance(line1, line2) + 70.71067811865476 + >>> shapely.frechet_distance(line1, line2, densify=0.5) + 50.0 + >>> shapely.frechet_distance(line1, LineString()) + nan + >>> shapely.frechet_distance(line1, None) + nan + + """ + if densify is None: + return lib.frechet_distance(a, b, **kwargs) + return lib.frechet_distance_densify(a, b, densify, **kwargs) + + +@multithreading_enabled +def minimum_clearance(geometry, **kwargs): + """Compute the Minimum Clearance distance. + + A geometry's "minimum clearance" is the smallest distance by which + a vertex of the geometry could be moved to produce an invalid geometry. + + If no minimum clearance exists for a geometry (for example, a single + point, or an empty geometry), infinity is returned. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the minimum clearance. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> polygon = Polygon([(0, 0), (0, 10), (5, 6), (10, 10), (10, 0), (5, 4), (0, 0)]) + >>> shapely.minimum_clearance(polygon) + 2.0 + >>> shapely.minimum_clearance(Polygon()) + inf + >>> shapely.minimum_clearance(None) + nan + + See Also + -------- + minimum_clearance_line + + """ + return lib.minimum_clearance(geometry, **kwargs) + + +@multithreading_enabled +def minimum_bounding_radius(geometry, **kwargs): + """Compute the radius of the minimum bounding circle of an input geometry. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries for which to compute the minimum bounding radius. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, MultiPoint, Point, Polygon + >>> shapely.minimum_bounding_radius( + ... Polygon([(0, 5), (5, 10), (10, 5), (5, 0), (0, 5)]) + ... ) + 5.0 + >>> shapely.minimum_bounding_radius(LineString([(1, 1), (1, 10)])) + 4.5 + >>> shapely.minimum_bounding_radius(MultiPoint([(2, 2), (4, 2)])) + 1.0 + >>> shapely.minimum_bounding_radius(Point(0, 1)) + 0.0 + >>> shapely.minimum_bounding_radius(GeometryCollection()) + 0.0 + + See Also + -------- + minimum_bounding_circle + + """ + return lib.minimum_bounding_radius(geometry, **kwargs) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/ops.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ff36f72efcc18b091bc9c390196ba4c804103533 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/ops.py @@ -0,0 +1,720 @@ +"""Support for various GEOS geometry operations.""" + +import shapely +from shapely.algorithms.polylabel import polylabel # noqa +from shapely.errors import GeometryTypeError +from shapely.geometry import ( + GeometryCollection, + LineString, + MultiLineString, + MultiPoint, + Point, + Polygon, + shape, +) +from shapely.geometry.base import BaseGeometry +from shapely.prepared import prep + +__all__ = [ + "clip_by_rect", + "linemerge", + "nearest_points", + "operator", + "orient", + "polygonize", + "polygonize_full", + "shared_paths", + "snap", + "split", + "substring", + "transform", + "triangulate", + "unary_union", + "validate", + "voronoi_diagram", +] + + +class CollectionOperator: + def shapeup(self, ob): + if isinstance(ob, BaseGeometry): + return ob + else: + try: + return shape(ob) + except (ValueError, AttributeError): + return LineString(ob) + + def polygonize(self, lines): + """Create polygons from a source of lines. + + The source may be a MultiLineString, a sequence of LineString objects, + or a sequence of objects than can be adapted to LineStrings. + """ + source = getattr(lines, "geoms", None) or lines + try: + source = iter(source) + except TypeError: + source = [source] + finally: + obs = [self.shapeup(line) for line in source] + collection = shapely.polygonize(obs) + return collection.geoms + + def polygonize_full(self, lines): + """Create polygons from a source of lines. + + The polygons and leftover geometries are returned as well. + + The source may be a MultiLineString, a sequence of LineString objects, + or a sequence of objects than can be adapted to LineStrings. + + Returns a tuple of objects: (polygons, cut edges, dangles, invalid ring + lines). Each are a geometry collection. + + Dangles are edges which have one or both ends which are not incident on + another edge endpoint. Cut edges are connected at both ends but do not + form part of polygon. Invalid ring lines form rings which are invalid + (bowties, etc). + """ + source = getattr(lines, "geoms", None) or lines + try: + source = iter(source) + except TypeError: + source = [source] + finally: + obs = [self.shapeup(line) for line in source] + return shapely.polygonize_full(obs) + + def linemerge(self, lines, directed=False): + """Merge all connected lines from a source. + + The source may be a MultiLineString, a sequence of LineString objects, + or a sequence of objects than can be adapted to LineStrings. Returns a + LineString or MultiLineString when lines are not contiguous. + """ + source = None + if getattr(lines, "geom_type", None) == "MultiLineString": + source = lines + elif hasattr(lines, "geoms"): + # other Multi geometries + source = MultiLineString([ls.coords for ls in lines.geoms]) + elif hasattr(lines, "__iter__"): + try: + source = MultiLineString([ls.coords for ls in lines]) + except AttributeError: + source = MultiLineString(lines) + if source is None: + raise ValueError(f"Cannot linemerge {lines}") + return shapely.line_merge(source, directed=directed) + + def unary_union(self, geoms): + """Return the union of a sequence of geometries. + + Usually used to convert a collection into the smallest set of polygons + that cover the same area. + """ + return shapely.union_all(geoms, axis=None) + + +operator = CollectionOperator() +polygonize = operator.polygonize +polygonize_full = operator.polygonize_full +linemerge = operator.linemerge +unary_union = operator.unary_union + + +def triangulate(geom, tolerance=0.0, edges=False): + """Create the Delaunay triangulation and return a list of geometries. + + The source may be any geometry type. All vertices of the geometry will be + used as the points of the triangulation. + + From the GEOS documentation: + tolerance is the snapping tolerance used to improve the robustness of + the triangulation computation. A tolerance of 0.0 specifies that no + snapping will take place. + + If edges is False, a list of Polygons (triangles) will be returned. + Otherwise the list of LineString edges is returned. + + """ + collection = shapely.delaunay_triangles(geom, tolerance=tolerance, only_edges=edges) + return list(collection.geoms) + + +def voronoi_diagram(geom, envelope=None, tolerance=0.0, edges=False): + """Construct a Voronoi Diagram [1] from the given geometry. + + Returns a list of geometries. + + Parameters + ---------- + geom: geometry + the input geometry whose vertices will be used to calculate + the final diagram. + envelope: geometry, None + clipping envelope for the returned diagram, automatically + determined if None. The diagram will be clipped to the larger + of this envelope or an envelope surrounding the sites. + tolerance: float, 0.0 + sets the snapping tolerance used to improve the robustness + of the computation. A tolerance of 0.0 specifies that no + snapping will take place. + edges: bool, False + If False, return regions as polygons. Else, return only + edges e.g. LineStrings. + + GEOS documentation can be found at [2] + + Returns + ------- + GeometryCollection + geometries representing the Voronoi regions. + + Notes + ----- + The tolerance `argument` can be finicky and is known to cause the + algorithm to fail in several cases. If you're using `tolerance` + and getting a failure, try removing it. The test cases in + tests/test_voronoi_diagram.py show more details. + + + References + ---------- + [1] https://en.wikipedia.org/wiki/Voronoi_diagram + [2] https://geos.osgeo.org/doxygen/geos__c_8h_source.html (line 730) + + """ + try: + result = shapely.voronoi_polygons( + geom, tolerance=tolerance, extend_to=envelope, only_edges=edges + ) + except shapely.GEOSException as err: + errstr = "Could not create Voronoi Diagram with the specified inputs " + errstr += f"({err!s})." + if tolerance: + errstr += " Try running again with default tolerance value." + raise ValueError(errstr) from err + + if result.geom_type != "GeometryCollection": + return GeometryCollection([result]) + return result + + +def validate(geom): + """Return True if the geometry is valid.""" + return shapely.is_valid_reason(geom) + + +def transform(func, geom): + """Apply `func` to all coordinates of `geom`. + + Returns a new geometry of the same type from the transformed coordinates. + + `func` maps x, y, and optionally z to output xp, yp, zp. The input + parameters may iterable types like lists or arrays or single values. + The output shall be of the same type. Scalars in, scalars out. + Lists in, lists out. + + For example, here is an identity function applicable to both types + of input. + + def id_func(x, y, z=None): + return tuple(filter(None, [x, y, z])) + + g2 = transform(id_func, g1) + + Using pyproj >= 2.1, this example will accurately project Shapely geometries: + + import pyproj + + wgs84 = pyproj.CRS('EPSG:4326') + utm = pyproj.CRS('EPSG:32618') + + project = pyproj.Transformer.from_crs(wgs84, utm, always_xy=True).transform + + g2 = transform(project, g1) + + Note that the always_xy kwarg is required here as Shapely geometries only support + X,Y coordinate ordering. + + Lambda expressions such as the one in + + g2 = transform(lambda x, y, z=None: (x+1.0, y+1.0), g1) + + also satisfy the requirements for `func`. + """ + if geom.is_empty: + return geom + if geom.geom_type in ("Point", "LineString", "LinearRing", "Polygon"): + # First we try to apply func to x, y, z sequences. When func is + # optimized for sequences, this is the fastest, though zipping + # the results up to go back into the geometry constructors adds + # extra cost. + try: + if geom.geom_type in ("Point", "LineString", "LinearRing"): + return type(geom)(zip(*func(*zip(*geom.coords)))) + elif geom.geom_type == "Polygon": + shell = type(geom.exterior)(zip(*func(*zip(*geom.exterior.coords)))) + holes = [ + type(ring)(zip(*func(*zip(*ring.coords)))) + for ring in geom.interiors + ] + return type(geom)(shell, holes) + + # A func that assumes x, y, z are single values will likely raise a + # TypeError, in which case we'll try again. + except TypeError: + if geom.geom_type in ("Point", "LineString", "LinearRing"): + return type(geom)([func(*c) for c in geom.coords]) + elif geom.geom_type == "Polygon": + shell = type(geom.exterior)([func(*c) for c in geom.exterior.coords]) + holes = [ + type(ring)([func(*c) for c in ring.coords]) + for ring in geom.interiors + ] + return type(geom)(shell, holes) + + elif geom.geom_type.startswith("Multi") or geom.geom_type == "GeometryCollection": + return type(geom)([transform(func, part) for part in geom.geoms]) + else: + raise GeometryTypeError(f"Type {geom.geom_type!r} not recognized") + + +def nearest_points(g1, g2): + """Return the calculated nearest points in the input geometries. + + The points are returned in the same order as the input geometries. + """ + seq = shapely.shortest_line(g1, g2) + if seq is None: + if g1.is_empty: + raise ValueError("The first input geometry is empty") + else: + raise ValueError("The second input geometry is empty") + + p1 = shapely.get_point(seq, 0) + p2 = shapely.get_point(seq, 1) + return (p1, p2) + + +def snap(g1, g2, tolerance): + """Snaps an input geometry (g1) to reference (g2) geometry's vertices. + + Parameters + ---------- + g1 : geometry + The first geometry + g2 : geometry + The second geometry + tolerance : float + The snapping tolerance + + Refer to :func:`shapely.snap` for full documentation. + + """ + return shapely.snap(g1, g2, tolerance) + + +def shared_paths(g1, g2): + """Find paths shared between the two given lineal geometries. + + Returns a GeometryCollection with two elements: + - First element is a MultiLineString containing shared paths with the + same direction for both inputs. + - Second element is a MultiLineString containing shared paths with the + opposite direction for the two inputs. + + Parameters + ---------- + g1 : geometry + The first geometry + g2 : geometry + The second geometry + + """ + if not isinstance(g1, LineString): + raise GeometryTypeError("First geometry must be a LineString") + if not isinstance(g2, LineString): + raise GeometryTypeError("Second geometry must be a LineString") + return shapely.shared_paths(g1, g2) + + +class SplitOp: + @staticmethod + def _split_polygon_with_line(poly, splitter): + """Split a Polygon with a LineString.""" + if not isinstance(poly, Polygon): + raise GeometryTypeError("First argument must be a Polygon") + if not isinstance(splitter, (LineString, MultiLineString)): + raise GeometryTypeError("Second argument must be a (Multi)LineString") + + union = poly.boundary.union(splitter) + + # greatly improves split performance for big geometries with many + # holes (the following contains checks) with minimal overhead + # for common cases + poly = prep(poly) + + # some polygonized geometries may be holes, we do not want them + # that's why we test if the original polygon (poly) contains + # an inner point of polygonized geometry (pg) + return [ + pg for pg in polygonize(union) if poly.contains(pg.representative_point()) + ] + + @staticmethod + def _split_line_with_line(line, splitter): + """Split a LineString with another (Multi)LineString or (Multi)Polygon.""" + # if splitter is a polygon, pick it's boundary + if splitter.geom_type in ("Polygon", "MultiPolygon"): + splitter = splitter.boundary + + if not isinstance(line, LineString): + raise GeometryTypeError("First argument must be a LineString") + if not isinstance(splitter, LineString) and not isinstance( + splitter, MultiLineString + ): + raise GeometryTypeError( + "Second argument must be either a LineString or a MultiLineString" + ) + + # | s\l | Interior | Boundary | Exterior | + # |----------|----------|----------|----------| + # | Interior | 0 or F | * | * | At least one of these two must be 0 # noqa: E501 + # | Boundary | 0 or F | * | * | So either '0********' or '[0F]**0*****' # noqa: E501 + # | Exterior | * | * | * | No overlapping interiors ('1********') # noqa: E501 + relation = splitter.relate(line) + if relation[0] == "1": + # The lines overlap at some segment (linear intersection of interiors) + raise ValueError("Input geometry segment overlaps with the splitter.") + elif relation[0] == "0" or relation[3] == "0": + # The splitter crosses or touches the line's interior + # --> return multilinestring from the split + return line.difference(splitter) + else: + # The splitter does not cross or touch the line's interior + # --> return collection with identity line + return [line] + + @staticmethod + def _split_line_with_point(line, splitter): + """Split a LineString with a Point.""" + if not isinstance(line, LineString): + raise GeometryTypeError("First argument must be a LineString") + if not isinstance(splitter, Point): + raise GeometryTypeError("Second argument must be a Point") + + # check if point is in the interior of the line + if not line.relate_pattern(splitter, "0********"): + # point not on line interior --> return collection with single identity line + # (REASONING: Returning a list with the input line reference and creating a + # GeometryCollection at the general split function prevents unnecessary + # copying of linestrings in multipoint splitting function) + return [line] + elif line.coords[0] == splitter.coords[0]: + # if line is a closed ring the previous test doesn't behave as desired + return [line] + + # point is on line, get the distance from the first point on line + distance_on_line = line.project(splitter) + coords = list(line.coords) + # split the line at the point and create two new lines + current_position = 0.0 + for i in range(len(coords) - 1): + point1 = coords[i] + point2 = coords[i + 1] + dx = point1[0] - point2[0] + dy = point1[1] - point2[1] + segment_length = (dx**2 + dy**2) ** 0.5 + current_position += segment_length + if distance_on_line == current_position: + # splitter is exactly on a vertex + return [LineString(coords[: i + 2]), LineString(coords[i + 1 :])] + elif distance_on_line < current_position: + # splitter is between two vertices + return [ + LineString(coords[: i + 1] + [splitter.coords[0]]), + LineString([splitter.coords[0]] + coords[i + 1 :]), + ] + return [line] + + @staticmethod + def _split_line_with_multipoint(line, splitter): + """Split a LineString with a MultiPoint.""" + if not isinstance(line, LineString): + raise GeometryTypeError("First argument must be a LineString") + if not isinstance(splitter, MultiPoint): + raise GeometryTypeError("Second argument must be a MultiPoint") + + chunks = [line] + for pt in splitter.geoms: + new_chunks = [] + for chunk in filter(lambda x: not x.is_empty, chunks): + # add the newly split 2 lines or the same line if not split + new_chunks.extend(SplitOp._split_line_with_point(chunk, pt)) + chunks = new_chunks + + return chunks + + @staticmethod + def split(geom, splitter): + """Split a geometry by another geometry and return a collection of geometries. + + This function is the theoretical opposite of the union of + the split geometry parts. If the splitter does not split the geometry, a + collection with a single geometry equal to the input geometry is + returned. + + The function supports: + - Splitting a (Multi)LineString by a (Multi)Point or (Multi)LineString + or (Multi)Polygon + - Splitting a (Multi)Polygon by a LineString + + It may be convenient to snap the splitter with low tolerance to the + geometry. For example in the case of splitting a line by a point, the + point must be exactly on the line, for the line to be correctly split. + When splitting a line by a polygon, the boundary of the polygon is used + for the operation. When splitting a line by another line, a ValueError + is raised if the two overlap at some segment. + + Parameters + ---------- + geom : geometry + The geometry to be split + splitter : geometry + The geometry that will split the input geom + + Examples + -------- + >>> import shapely.ops + >>> from shapely import Point, LineString + >>> pt = Point((1, 1)) + >>> line = LineString([(0,0), (2,2)]) + >>> result = shapely.ops.split(line, pt) + >>> result.wkt + 'GEOMETRYCOLLECTION (LINESTRING (0 0, 1 1), LINESTRING (1 1, 2 2))' + + """ + if geom.geom_type in ("MultiLineString", "MultiPolygon"): + return GeometryCollection( + [i for part in geom.geoms for i in SplitOp.split(part, splitter).geoms] + ) + + elif geom.geom_type == "LineString": + if splitter.geom_type in ( + "LineString", + "MultiLineString", + "Polygon", + "MultiPolygon", + ): + split_func = SplitOp._split_line_with_line + elif splitter.geom_type == "Point": + split_func = SplitOp._split_line_with_point + elif splitter.geom_type == "MultiPoint": + split_func = SplitOp._split_line_with_multipoint + else: + raise GeometryTypeError( + f"Splitting a LineString with a {splitter.geom_type} is " + "not supported" + ) + + elif geom.geom_type == "Polygon": + if splitter.geom_type in ("LineString", "MultiLineString"): + split_func = SplitOp._split_polygon_with_line + else: + raise GeometryTypeError( + f"Splitting a Polygon with a {splitter.geom_type} is not supported" + ) + + else: + raise GeometryTypeError( + f"Splitting {geom.geom_type} geometry is not supported" + ) + + return GeometryCollection(split_func(geom, splitter)) + + +split = SplitOp.split + + +def substring(geom, start_dist, end_dist, normalized=False): + """Return a line segment between specified distances along a LineString. + + Negative distance values are taken as measured in the reverse + direction from the end of the geometry. Out-of-range index + values are handled by clamping them to the valid range of values. + + If the start distance equals the end distance, a Point is returned. + + If the start distance is actually beyond the end distance, then the + reversed substring is returned such that the start distance is + at the first coordinate. + + Parameters + ---------- + geom : LineString + The geometry to get a substring of. + start_dist : float + The distance along `geom` of the start of the substring. + end_dist : float + The distance along `geom` of the end of the substring. + normalized : bool, False + Whether the distance parameters are interpreted as a + fraction of the geometry's length. + + Returns + ------- + Union[Point, LineString] + The substring between `start_dist` and `end_dist` or a Point + if they are at the same location. + + Raises + ------ + TypeError + If `geom` is not a LineString. + + Examples + -------- + >>> from shapely.geometry import LineString + >>> from shapely.ops import substring + >>> ls = LineString((i, 0) for i in range(6)) + >>> ls.wkt + 'LINESTRING (0 0, 1 0, 2 0, 3 0, 4 0, 5 0)' + >>> substring(ls, start_dist=1, end_dist=3).wkt + 'LINESTRING (1 0, 2 0, 3 0)' + >>> substring(ls, start_dist=3, end_dist=1).wkt + 'LINESTRING (3 0, 2 0, 1 0)' + >>> substring(ls, start_dist=1, end_dist=-3).wkt + 'LINESTRING (1 0, 2 0)' + >>> substring(ls, start_dist=0.2, end_dist=-0.6, normalized=True).wkt + 'LINESTRING (1 0, 2 0)' + + Returning a `Point` when `start_dist` and `end_dist` are at the + same location. + + >>> substring(ls, 2.5, -2.5).wkt + 'POINT (2.5 0)' + + """ + if not isinstance(geom, LineString): + raise GeometryTypeError( + "Can only calculate a substring of LineString geometries. " + f"A {geom.geom_type} was provided." + ) + + # Filter out cases in which to return a point + if start_dist == end_dist: + return geom.interpolate(start_dist, normalized=normalized) + elif not normalized and start_dist >= geom.length and end_dist >= geom.length: + return geom.interpolate(geom.length, normalized=normalized) + elif not normalized and -start_dist >= geom.length and -end_dist >= geom.length: + return geom.interpolate(0, normalized=normalized) + elif normalized and start_dist >= 1 and end_dist >= 1: + return geom.interpolate(1, normalized=normalized) + elif normalized and -start_dist >= 1 and -end_dist >= 1: + return geom.interpolate(0, normalized=normalized) + + if normalized: + start_dist *= geom.length + end_dist *= geom.length + + # Filter out cases where distances meet at a middle point from opposite ends. + if start_dist < 0 < end_dist and abs(start_dist) + end_dist == geom.length: + return geom.interpolate(end_dist) + elif end_dist < 0 < start_dist and abs(end_dist) + start_dist == geom.length: + return geom.interpolate(start_dist) + + start_point = geom.interpolate(start_dist) + end_point = geom.interpolate(end_dist) + + if start_dist < 0: + start_dist = geom.length + start_dist # Values may still be negative, + if end_dist < 0: # but only in the out-of-range + end_dist = geom.length + end_dist # sense, not the wrap-around sense. + + reverse = start_dist > end_dist + if reverse: + start_dist, end_dist = end_dist, start_dist + + start_dist = max(start_dist, 0) # to avoid duplicating the first vertex + + if reverse: + vertex_list = [tuple(*end_point.coords)] + else: + vertex_list = [tuple(*start_point.coords)] + + coords = list(geom.coords) + current_distance = 0 + for p1, p2 in zip(coords, coords[1:]): # noqa + if start_dist < current_distance < end_dist: + vertex_list.append(p1) + elif current_distance >= end_dist: + break + + current_distance += ((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2) ** 0.5 + + if reverse: + vertex_list.append(tuple(*start_point.coords)) + # reverse direction result + vertex_list = reversed(vertex_list) + else: + vertex_list.append(tuple(*end_point.coords)) + + return LineString(vertex_list) + + +def clip_by_rect(geom, xmin, ymin, xmax, ymax): + """Return the portion of a geometry within a rectangle. + + The geometry is clipped in a fast but possibly dirty way. The output is + not guaranteed to be valid. No exceptions will be raised for topological + errors. + + Parameters + ---------- + geom : geometry + The geometry to be clipped + xmin : float + Minimum x value of the rectangle + ymin : float + Minimum y value of the rectangle + xmax : float + Maximum x value of the rectangle + ymax : float + Maximum y value of the rectangle + + Notes + ----- + New in 1.7. + + """ + if geom.is_empty: + return geom + return shapely.clip_by_rect(geom, xmin, ymin, xmax, ymax) + + +def orient(geom, sign=1.0): + """Return a properly oriented copy of the given geometry. + + The signed area of the result will have the given sign. A sign of + 1.0 means that the coordinates of the product's exterior rings will + be oriented counter-clockwise. + + It is recommended to use :func:`shapely.orient_polygons` instead. + + Parameters + ---------- + geom : Geometry + The original geometry. May be a Polygon, MultiPolygon, or + GeometryCollection. + sign : float, optional. + The sign of the result's signed area. + + Returns + ------- + Geometry + + """ + return shapely.orient_polygons(geom, exterior_cw=sign < 0) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/plotting.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f824093e37fa8538fe55bca23c76e973b55125 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/plotting.py @@ -0,0 +1,222 @@ +"""Plot single geometries using Matplotlib. + +Note: this module is experimental, and mainly targeting (interactive) +exploration, debugging and illustration purposes. + +""" + +import numpy as np + +import shapely + + +def _default_ax(): + import matplotlib.pyplot as plt + + ax = plt.gca() + ax.grid(True) + ax.set_aspect("equal") + return ax + + +def _path_from_polygon(polygon): + from matplotlib.path import Path + + from shapely.ops import orient + + if isinstance(polygon, shapely.MultiPolygon): + return Path.make_compound_path( + *[_path_from_polygon(poly) for poly in polygon.geoms] + ) + else: + polygon = orient(polygon) + return Path.make_compound_path( + Path(np.asarray(polygon.exterior.coords)[:, :2]), + *[Path(np.asarray(ring.coords)[:, :2]) for ring in polygon.interiors], + ) + + +def patch_from_polygon(polygon, **kwargs): + """Get a Matplotlib patch from a (Multi)Polygon. + + Note: this function is experimental, and mainly targeting (interactive) + exploration, debugging and illustration purposes. + + Parameters + ---------- + polygon : shapely.Polygon or shapely.MultiPolygon + The polygon to convert to a Matplotlib Patch. + **kwargs + Additional keyword arguments passed to the matplotlib Patch. + + Returns + ------- + Matplotlib artist (PathPatch) + + """ + from matplotlib.patches import PathPatch + + return PathPatch(_path_from_polygon(polygon), **kwargs) + + +def plot_polygon( + polygon, + ax=None, + add_points=True, + color=None, + facecolor=None, + edgecolor=None, + linewidth=None, + **kwargs, +): + """Plot a (Multi)Polygon. + + Note: this function is experimental, and mainly targeting (interactive) + exploration, debugging and illustration purposes. + + Parameters + ---------- + polygon : shapely.Polygon or shapely.MultiPolygon + The polygon to plot. + ax : matplotlib Axes, default None + The axes on which to draw the plot. If not specified, will get the + current active axes or create a new figure. + add_points : bool, default True + If True, also plot the coordinates (vertices) as points. + color : matplotlib color specification + Color for both the polygon fill (face) and boundary (edge). By default, + the fill is using an alpha of 0.3. You can specify `facecolor` and + `edgecolor` separately for greater control. + facecolor : matplotlib color specification + Color for the polygon fill. + edgecolor : matplotlib color specification + Color for the polygon boundary. + linewidth : float + The line width for the polygon boundary. + **kwargs + Additional keyword arguments passed to the matplotlib Patch. + + Returns + ------- + Matplotlib artist (PathPatch), if `add_points` is false. + A tuple of Matplotlib artists (PathPatch, Line2D), if `add_points` is true. + + """ + from matplotlib import colors + + if ax is None: + ax = _default_ax() + + if color is None: + color = "C0" + color = colors.to_rgba(color) + + if facecolor is None: + facecolor = list(color) + facecolor[-1] = 0.3 + facecolor = tuple(facecolor) + + if edgecolor is None: + edgecolor = color + + patch = patch_from_polygon( + polygon, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, **kwargs + ) + ax.add_patch(patch) + ax.autoscale_view() + + if add_points: + line = plot_points(polygon, ax=ax, color=color) + return patch, line + + return patch + + +def plot_line(line, ax=None, add_points=True, color=None, linewidth=2, **kwargs): + """Plot a (Multi)LineString/LinearRing. + + Note: this function is experimental, and mainly targeting (interactive) + exploration, debugging and illustration purposes. + + Parameters + ---------- + line : shapely.LineString or shapely.LinearRing + The line to plot. + ax : matplotlib Axes, default None + The axes on which to draw the plot. If not specified, will get the + current active axes or create a new figure. + add_points : bool, default True + If True, also plot the coordinates (vertices) as points. + color : matplotlib color specification + Color for the line (edgecolor under the hood) and points. + linewidth : float, default 2 + The line width for the polygon boundary. + **kwargs + Additional keyword arguments passed to the matplotlib Patch. + + Returns + ------- + Matplotlib artist (PathPatch) + + """ + from matplotlib.patches import PathPatch + from matplotlib.path import Path + + if ax is None: + ax = _default_ax() + + if color is None: + color = "C0" + + if isinstance(line, shapely.MultiLineString): + path = Path.make_compound_path( + *[Path(np.asarray(mline.coords)[:, :2]) for mline in line.geoms] + ) + else: + path = Path(np.asarray(line.coords)[:, :2]) + + patch = PathPatch( + path, facecolor="none", edgecolor=color, linewidth=linewidth, **kwargs + ) + ax.add_patch(patch) + ax.autoscale_view() + + if add_points: + line = plot_points(line, ax=ax, color=color) + return patch, line + + return patch + + +def plot_points(geom, ax=None, color=None, marker="o", **kwargs): + """Plot a Point/MultiPoint or the vertices of any other geometry type. + + Parameters + ---------- + geom : shapely.Geometry + Any shapely Geometry object, from which all vertices are extracted + and plotted. + ax : matplotlib Axes, default None + The axes on which to draw the plot. If not specified, will get the + current active axes or create a new figure. + color : matplotlib color specification + Color for the filled points. You can use `markeredgecolor` and + `markerfacecolor` to have different edge and fill colors. + marker : str, default "o" + The matplotlib marker for the points. + **kwargs + Additional keyword arguments passed to matplotlib `plot` (Line2D). + + Returns + ------- + Matplotlib artist (Line2D) + + """ + if ax is None: + ax = _default_ax() + + coords = shapely.get_coordinates(geom) + (line,) = ax.plot( + coords[:, 0], coords[:, 1], linestyle="", marker=marker, color=color, **kwargs + ) + return line diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/predicates.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/predicates.py new file mode 100644 index 0000000000000000000000000000000000000000..6055f30c4b0f27e7e8c76a3055d0c2199a960aeb --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/predicates.py @@ -0,0 +1,1350 @@ +"""Predicates for spatial analysis.""" + +import warnings + +import numpy as np + +from shapely import lib +from shapely.decorators import multithreading_enabled, requires_geos + +__all__ = [ + "contains", + "contains_properly", + "contains_xy", + "covered_by", + "covers", + "crosses", + "disjoint", + "dwithin", + "equals", + "equals_exact", + "equals_identical", + "has_m", + "has_z", + "intersects", + "intersects_xy", + "is_ccw", + "is_closed", + "is_empty", + "is_geometry", + "is_missing", + "is_prepared", + "is_ring", + "is_simple", + "is_valid", + "is_valid_input", + "is_valid_reason", + "overlaps", + "relate", + "relate_pattern", + "touches", + "within", +] + + +@multithreading_enabled +def has_z(geometry, **kwargs): + """Return True if a geometry has Z coordinates. + + Note that for GEOS < 3.12 this function returns False if the (first) Z coordinate + equals NaN. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to check for Z coordinates. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_coordinate_dimension, has_m + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> shapely.has_z(Point(0, 0)) + False + >>> shapely.has_z(Point(0, 0, 0)) + True + >>> shapely.has_z(Point()) + False + + """ + return lib.has_z(geometry, **kwargs) + + +@multithreading_enabled +@requires_geos("3.12.0") +def has_m(geometry, **kwargs): + """Return True if a geometry has M coordinates. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to check for M coordinates. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + get_coordinate_dimension, has_z + + Examples + -------- + >>> import shapely + >>> shapely.has_m(shapely.from_wkt("POINT (0 0)")) + False + >>> shapely.has_m(shapely.from_wkt("POINT Z (0 0 0)")) + False + >>> shapely.has_m(shapely.from_wkt("POINT M (0 0 0)")) + True + >>> shapely.has_m(shapely.from_wkt("POINT ZM (0 0 0 0)")) + True + + """ + return lib.has_m(geometry, **kwargs) + + +@multithreading_enabled +def is_ccw(geometry, **kwargs): + """Return True if a linestring or linearring is counterclockwise. + + Note that there are no checks on whether lines are actually closed and + not self-intersecting, while this is a requirement for is_ccw. The recommended + usage of this function for linestrings is ``is_ccw(g) & is_simple(g)`` and for + linearrings ``is_ccw(g) & is_valid(g)``. + + Parameters + ---------- + geometry : Geometry or array_like + This function will return False for non-linear geometries and for + lines with fewer than 4 points (including the closing point). + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_simple : Checks if a linestring is closed and simple. + is_valid : Checks additionally if the geometry is simple. + + Examples + -------- + >>> import shapely + >>> from shapely import LinearRing, LineString, Point + >>> shapely.is_ccw(LinearRing([(0, 0), (0, 1), (1, 1), (0, 0)])) + False + >>> shapely.is_ccw(LinearRing([(0, 0), (1, 1), (0, 1), (0, 0)])) + True + >>> shapely.is_ccw(LineString([(0, 0), (1, 1), (0, 1)])) + False + >>> shapely.is_ccw(Point(0, 0)) + False + + """ + return lib.is_ccw(geometry, **kwargs) + + +@multithreading_enabled +def is_closed(geometry, **kwargs): + """Return True if a linestring's first and last points are equal. + + Parameters + ---------- + geometry : Geometry or array_like + This function will return False for non-linestrings. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_ring : Checks additionally if the geometry is simple. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.is_closed(LineString([(0, 0), (1, 1)])) + False + >>> shapely.is_closed(LineString([(0, 0), (0, 1), (1, 1), (0, 0)])) + True + >>> shapely.is_closed(Point(0, 0)) + False + + """ + return lib.is_closed(geometry, **kwargs) + + +@multithreading_enabled +def is_empty(geometry, **kwargs): + """Return True if a geometry is an empty point, polygon, etc. + + Parameters + ---------- + geometry : Geometry or array_like + Any geometry type is accepted. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_missing : checks if the object is a geometry + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> shapely.is_empty(Point()) + True + >>> shapely.is_empty(Point(0, 0)) + False + >>> shapely.is_empty(None) + False + + """ + return lib.is_empty(geometry, **kwargs) + + +@multithreading_enabled +def is_geometry(geometry, **kwargs): + """Return True if the object is a geometry. + + Parameters + ---------- + geometry : any object or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_missing : check if an object is missing (None) + is_valid_input : check if an object is a geometry or None + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, Point + >>> shapely.is_geometry(Point(0, 0)) + True + >>> shapely.is_geometry(GeometryCollection()) + True + >>> shapely.is_geometry(None) + False + >>> shapely.is_geometry("text") + False + + """ + return lib.is_geometry(geometry, **kwargs) + + +@multithreading_enabled +def is_missing(geometry, **kwargs): + """Return True if the object is not a geometry (None). + + Parameters + ---------- + geometry : any object or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_geometry : check if an object is a geometry + is_valid_input : check if an object is a geometry or None + is_empty : checks if the object is an empty geometry + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, Point + >>> shapely.is_missing(Point(0, 0)) + False + >>> shapely.is_missing(GeometryCollection()) + False + >>> shapely.is_missing(None) + True + >>> shapely.is_missing("text") + False + + """ + return lib.is_missing(geometry, **kwargs) + + +@multithreading_enabled +def is_prepared(geometry, **kwargs): + """Return True if a Geometry is prepared. + + Note that it is not necessary to check if a geometry is already prepared + before preparing it. It is more efficient to call ``prepare`` directly + because it will skip geometries that are already prepared. + + This function will return False for missing geometries (None). + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_valid_input : check if an object is a geometry or None + prepare : prepare a geometry + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> geometry = Point(0, 0) + >>> shapely.is_prepared(Point(0, 0)) + False + >>> shapely.prepare(geometry) + >>> shapely.is_prepared(geometry) + True + >>> shapely.is_prepared(None) + False + + """ + return lib.is_prepared(geometry, **kwargs) + + +@multithreading_enabled +def is_valid_input(geometry, **kwargs): + """Return True if the object is a geometry or None. + + Parameters + ---------- + geometry : any object or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_geometry : checks if an object is a geometry + is_missing : checks if an object is None + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, Point + >>> shapely.is_valid_input(Point(0, 0)) + True + >>> shapely.is_valid_input(GeometryCollection()) + True + >>> shapely.is_valid_input(None) + True + >>> shapely.is_valid_input(1.0) + False + >>> shapely.is_valid_input("text") + False + + """ + return lib.is_valid_input(geometry, **kwargs) + + +@multithreading_enabled +def is_ring(geometry, **kwargs): + """Return True if a linestring is closed and simple. + + This function will return False for non-linestrings. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_closed : Checks only if the geometry is closed. + is_simple : Checks only if the geometry is simple. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> shapely.is_ring(Point(0, 0)) + False + >>> geom = LineString([(0, 0), (1, 1)]) + >>> shapely.is_closed(geom), shapely.is_simple(geom), shapely.is_ring(geom) + (False, True, False) + >>> geom = LineString([(0, 0), (0, 1), (1, 1), (0, 0)]) + >>> shapely.is_closed(geom), shapely.is_simple(geom), shapely.is_ring(geom) + (True, True, True) + >>> geom = LineString([(0, 0), (1, 1), (0, 1), (1, 0), (0, 0)]) + >>> shapely.is_closed(geom), shapely.is_simple(geom), shapely.is_ring(geom) + (True, False, False) + + """ + return lib.is_ring(geometry, **kwargs) + + +@multithreading_enabled +def is_simple(geometry, **kwargs): + """Return True if the geometry is simple. + + A simple geometry has no anomalous geometric points, such as + self-intersections or self tangency. + + Note that polygons and linearrings are assumed to be simple. Use is_valid + to check these kind of geometries for self-intersections. + + This function will return False for geometrycollections. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_ring : Checks additionally if the geometry is closed. + is_valid : Checks whether a geometry is well formed. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Polygon + >>> shapely.is_simple(Polygon([(1, 1), (2, 1), (2, 2), (1, 1)])) + True + >>> shapely.is_simple(LineString([(0, 0), (1, 1), (0, 1), (1, 0), (0, 0)])) + False + >>> shapely.is_simple(None) + False + + """ + return lib.is_simple(geometry, **kwargs) + + +@multithreading_enabled +def is_valid(geometry, **kwargs): + """Return True if a geometry is well formed. + + Returns False for missing values. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to check. Any geometry type is accepted. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_valid_reason : Returns the reason in case of invalid. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, Polygon + >>> shapely.is_valid(LineString([(0, 0), (1, 1)])) + True + >>> shapely.is_valid(Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)])) + False + >>> shapely.is_valid(GeometryCollection()) + True + >>> shapely.is_valid(None) + False + + """ + # GEOS is valid will emit warnings for invalid geometries. Suppress them. + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = lib.is_valid(geometry, **kwargs) + return result + + +def is_valid_reason(geometry, **kwargs): + """Return a string stating if a geometry is valid and if not, why. + + Returns None for missing values. + + Parameters + ---------- + geometry : Geometry or array_like + Geometry or geometries to check. Any geometry type is accepted. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + is_valid : returns True or False + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Polygon + >>> shapely.is_valid_reason(LineString([(0, 0), (1, 1)])) + 'Valid Geometry' + >>> shapely.is_valid_reason(Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)])) + 'Self-intersection[1 2]' + >>> shapely.is_valid_reason(None) is None + True + + """ + return lib.is_valid_reason(geometry, **kwargs) + + +@multithreading_enabled +def crosses(a, b, **kwargs): + """Return True if A and B spatially cross. + + A crosses B if they have some but not all interior points in common, + the intersection is one dimension less than the maximum dimension of A or B, + and the intersection is not equal to either A or B. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, MultiPoint, Point, Polygon + >>> line = LineString([(0, 0), (1, 1)]) + >>> # A contains B: + >>> shapely.crosses(line, Point(0.5, 0.5)) + False + >>> # A and B intersect at a point but do not share all points: + >>> shapely.crosses(line, MultiPoint([(0, 1), (0.5, 0.5)])) + True + >>> shapely.crosses(line, LineString([(0, 1), (1, 0)])) + True + >>> # A is contained by B; their intersection is a line (same dimension): + >>> shapely.crosses(line, LineString([(0, 0), (2, 2)])) + False + >>> area = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> # A contains B: + >>> shapely.crosses(area, line) + False + >>> # A and B intersect with a line (lower dimension) but do not share all points: + >>> shapely.crosses(area, LineString([(0, 0), (2, 2)])) + True + >>> # A contains B: + >>> shapely.crosses(area, Point(0.5, 0.5)) + False + >>> # A contains some but not all points of B; they intersect at a point: + >>> shapely.crosses(area, MultiPoint([(2, 2), (0.5, 0.5)])) + True + + """ + return lib.crosses(a, b, **kwargs) + + +@multithreading_enabled +def contains(a, b, **kwargs): + """Return True if geometry B is completely inside geometry A. + + A contains B if no points of B lie in the exterior of A and at least one + point of the interior of B lies in the interior of A. + + Note: following this definition, a geometry does not contain its boundary, + but it does contain itself. See ``contains_properly`` for a version where + a geometry does not contain itself. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + within : ``contains(A, B) == within(B, A)`` + contains_properly : contains with no common boundary points + prepare : improve performance by preparing ``a`` (the first argument) + contains_xy : variant for checking against a Point with x, y coordinates + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.contains(line, Point(0, 0)) + False + >>> shapely.contains(line, Point(0.5, 0.5)) + True + >>> area = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> shapely.contains(area, Point(0, 0)) + False + >>> shapely.contains(area, line) + True + >>> shapely.contains(area, LineString([(0, 0), (2, 2)])) + False + >>> polygon_with_hole = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]] + ... ) + >>> shapely.contains(polygon_with_hole, Point(1, 1)) + True + >>> shapely.contains(polygon_with_hole, Point(2, 2)) + False + >>> shapely.contains(polygon_with_hole, LineString([(1, 1), (5, 5)])) + False + >>> shapely.contains(area, area) + True + >>> shapely.contains(area, None) + False + + """ + return lib.contains(a, b, **kwargs) + + +@multithreading_enabled +def contains_properly(a, b, **kwargs): + """Return True if geometry B is completely inside geometry A, with no common + boundary points. + + A contains B properly if B intersects the interior of A but not the + boundary (or exterior). This means that a geometry A does not + "contain properly" itself, which contrasts with the ``contains`` function, + where common points on the boundary are allowed. + + Note: this function will prepare the geometries under the hood if needed. + You can prepare the geometries in advance to avoid repeated preparation + when calling this function multiple times. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + contains : contains which allows common boundary points + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> area1 = Polygon([(0, 0), (3, 0), (3, 3), (0, 3), (0, 0)]) + >>> area2 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> area3 = Polygon([(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)]) + + ``area1`` and ``area2`` have a common border: + + >>> shapely.contains(area1, area2) + True + >>> shapely.contains_properly(area1, area2) + False + + ``area3`` is completely inside ``area1`` with no common border: + + >>> shapely.contains(area1, area3) + True + >>> shapely.contains_properly(area1, area3) + True + + """ # noqa: D205 + return lib.contains_properly(a, b, **kwargs) + + +@multithreading_enabled +def covered_by(a, b, **kwargs): + """Return True if no point in geometry A is outside geometry B. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + covers : ``covered_by(A, B) == covers(B, A)`` + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.covered_by(Point(0, 0), line) + True + >>> shapely.covered_by(Point(0.5, 0.5), line) + True + >>> area = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> shapely.covered_by(Point(0, 0), area) + True + >>> shapely.covered_by(line, area) + True + >>> shapely.covered_by(LineString([(0, 0), (2, 2)]), area) + False + >>> polygon_with_hole = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]] + ... ) + >>> shapely.covered_by(Point(1, 1), polygon_with_hole) + True + >>> shapely.covered_by(Point(2, 2), polygon_with_hole) + True + >>> shapely.covered_by(LineString([(1, 1), (5, 5)]), polygon_with_hole) + False + >>> shapely.covered_by(area, area) + True + >>> shapely.covered_by(None, area) + False + + """ + return lib.covered_by(a, b, **kwargs) + + +@multithreading_enabled +def covers(a, b, **kwargs): + """Return True if no point in geometry B is outside geometry A. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + covered_by : ``covers(A, B) == covered_by(B, A)`` + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.covers(line, Point(0, 0)) + True + >>> shapely.covers(line, Point(0.5, 0.5)) + True + >>> area = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> shapely.covers(area, Point(0, 0)) + True + >>> shapely.covers(area, line) + True + >>> shapely.covers(area, LineString([(0, 0), (2, 2)])) + False + >>> polygon_with_hole = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]] + ... ) + >>> shapely.covers(polygon_with_hole, Point(1, 1)) + True + >>> shapely.covers(polygon_with_hole, Point(2, 2)) + True + >>> shapely.covers(polygon_with_hole, LineString([(1, 1), (5, 5)])) + False + >>> shapely.covers(area, area) + True + >>> shapely.covers(area, None) + False + + """ + return lib.covers(a, b, **kwargs) + + +@multithreading_enabled +def disjoint(a, b, **kwargs): + """Return True if A and B do not share any point in space. + + Disjoint implies that overlaps, touches, within, and intersects are False. + Note missing (None) values are never disjoint. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + intersects : ``disjoint(A, B) == ~intersects(A, B)`` + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, Point + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.disjoint(line, Point(0, 0)) + False + >>> shapely.disjoint(line, Point(0, 1)) + True + >>> shapely.disjoint(line, LineString([(0, 2), (2, 0)])) + False + >>> empty = GeometryCollection() + >>> shapely.disjoint(line, empty) + True + >>> shapely.disjoint(empty, empty) + True + >>> shapely.disjoint(empty, None) + False + >>> shapely.disjoint(None, None) + False + + """ + return lib.disjoint(a, b, **kwargs) + + +@multithreading_enabled +def equals(a, b, **kwargs): + """Return True if A and B are spatially equal. + + If A is within B and B is within A, A and B are considered equal. The + ordering of points can be different. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + equals_exact : Check if A and B are structurally equal given a specified + tolerance. + + Examples + -------- + >>> import shapely + >>> from shapely import GeometryCollection, LineString, Polygon + >>> line = LineString([(0, 0), (5, 5), (10, 10)]) + >>> shapely.equals(line, LineString([(0, 0), (10, 10)])) + True + >>> shapely.equals(Polygon(), GeometryCollection()) + True + >>> shapely.equals(None, None) + False + + """ + return lib.equals(a, b, **kwargs) + + +@multithreading_enabled +def intersects(a, b, **kwargs): + """Return True if A and B share any portion of space. + + Intersects implies that overlaps, touches, covers, or within are True. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + disjoint : ``intersects(A, B) == ~disjoint(A, B)`` + prepare : improve performance by preparing ``a`` (the first argument) + intersects_xy : variant for checking against a Point with x, y coordinates + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.intersects(line, Point(0, 0)) + True + >>> shapely.intersects(line, Point(0, 1)) + False + >>> shapely.intersects(line, LineString([(0, 2), (2, 0)])) + True + >>> shapely.intersects(None, None) + False + + """ + return lib.intersects(a, b, **kwargs) + + +@multithreading_enabled +def overlaps(a, b, **kwargs): + """Return True if A and B spatially overlap. + + A and B overlap if they have some but not all points/space in + common, have the same dimension, and the intersection of the + interiors of the two geometries has the same dimension as the + geometries themselves. That is, only polyons can overlap other + polygons and only lines can overlap other lines. If A covers or is + within B, overlaps won't be True. + + If either A or B are None, the output is always False. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword + arguments. + + See Also + -------- + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> poly = Polygon([(0, 0), (0, 4), (4, 4), (4, 0), (0, 0)]) + >>> # A and B share all points (are spatially equal): + >>> shapely.overlaps(poly, poly) + False + >>> # A contains B; all points of B are within A: + >>> shapely.overlaps(poly, Polygon([(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)])) + False + >>> # A partially overlaps with B: + >>> shapely.overlaps(poly, Polygon([(2, 2), (2, 6), (6, 6), (6, 2), (2, 2)])) + True + >>> line = LineString([(2, 2), (6, 6)]) + >>> # A and B are different dimensions; they cannot overlap: + >>> shapely.overlaps(poly, line) + False + >>> shapely.overlaps(poly, Point(2, 2)) + False + >>> # A and B share some but not all points: + >>> shapely.overlaps(line, LineString([(0, 0), (4, 4)])) + True + >>> # A and B intersect only at a point (lower dimension); they do not overlap + >>> shapely.overlaps(line, LineString([(6, 0), (0, 6)])) + False + >>> shapely.overlaps(poly, None) + False + >>> shapely.overlaps(None, None) + False + + """ + return lib.overlaps(a, b, **kwargs) + + +@multithreading_enabled +def touches(a, b, **kwargs): + """Return True if the only points shared between A and B are on their boundaries. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> line = LineString([(0, 2), (2, 0)]) + >>> shapely.touches(line, Point(0, 2)) + True + >>> shapely.touches(line, Point(1, 1)) + False + >>> shapely.touches(line, LineString([(0, 0), (1, 1)])) + True + >>> shapely.touches(line, LineString([(0, 0), (2, 2)])) + False + >>> area = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> shapely.touches(area, Point(0.5, 0)) + True + >>> shapely.touches(area, Point(0.5, 0.5)) + False + >>> shapely.touches(area, line) + True + >>> shapely.touches(area, Polygon([(0, 1), (1, 1), (1, 2), (0, 2), (0, 1)])) + True + + """ + return lib.touches(a, b, **kwargs) + + +@multithreading_enabled +def within(a, b, **kwargs): + """Return True if geometry A is completely inside geometry B. + + A is within B if no points of A lie in the exterior of B and at least one + point of the interior of A lies in the interior of B. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + contains : ``within(A, B) == contains(B, A)`` + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point, Polygon + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.within(Point(0, 0), line) + False + >>> shapely.within(Point(0.5, 0.5), line) + True + >>> area = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> shapely.within(Point(0, 0), area) + False + >>> shapely.within(line, area) + True + >>> shapely.within(LineString([(0, 0), (2, 2)]), area) + False + >>> polygon_with_hole = Polygon( + ... [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + ... holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]] + ... ) + >>> shapely.within(Point(1, 1), polygon_with_hole) + True + >>> shapely.within(Point(2, 2), polygon_with_hole) + False + >>> shapely.within(LineString([(1, 1), (5, 5)]), polygon_with_hole) + False + >>> shapely.within(area, area) + True + >>> shapely.within(None, area) + False + + """ + return lib.within(a, b, **kwargs) + + +@multithreading_enabled +def equals_exact(a, b, tolerance=0.0, *, normalize=False, **kwargs): + """Return True if the geometries are structurally equivalent within a given + tolerance. + + This method uses exact coordinate equality, which requires coordinates + to be equal (within specified tolerance) and in the same order for + all components (vertices, rings, or parts) of a geometry. This is in + contrast with the :func:`equals` function which uses spatial + (topological) equality and does not require all components to be in the + same order. Because of this, it is possible for :func:`equals` to + be ``True`` while :func:`equals_exact` is ``False``. + + The order of the coordinates can be normalized (by setting the `normalize` + keyword to ``True``) so that this function will return ``True`` when geometries + are structurally equivalent but differ only in the ordering of vertices. + However, this function will still return ``False`` if the order of interior + rings within a :class:`Polygon` or the order of geometries within a multi + geometry are different. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + tolerance : float or array_like (default: 0.) + The tolerance to use in the comparison. + normalize : bool, optional (default: False) + If True, normalize the two geometries so that the coordinates are + in the same order. + + .. versionadded:: 2.1.0 + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + equals : Check if `a` and `b` are spatially (topologically) equal. + + Examples + -------- + >>> import shapely + >>> from shapely import Point, Polygon + >>> point1 = Point(50, 50) + >>> point2 = Point(50.1, 50.1) + >>> shapely.equals_exact(point1, point2) + False + >>> shapely.equals_exact(point1, point2, tolerance=0.2) + True + >>> shapely.equals_exact(point1, None, tolerance=0.2) + False + + Difference between structural and spatial equality: + + >>> polygon1 = Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]) + >>> polygon2 = Polygon([(0, 0), (0, 1), (1, 1), (0, 0)]) + >>> shapely.equals_exact(polygon1, polygon2) + False + >>> shapely.equals(polygon1, polygon2) + True + + """ # noqa: D205 + if normalize: + a = lib.normalize(a) + b = lib.normalize(b) + + return lib.equals_exact(a, b, tolerance, **kwargs) + + +@multithreading_enabled +def equals_identical(a, b, **kwargs): + """Return True if the geometries are identical. + + This function verifies whether geometries are pointwise equivalent by checking + that the structure, ordering, and values of all vertices are identical + in all dimensions. + + Similarly to :func:`equals_exact`, this function uses exact coordinate + equality and requires coordinates to be in the same order for all + components (vertices, rings, or parts) of a geometry. However, in + contrast :func:`equals_exact`, this function does not allow to specify + a tolerance, but does require all dimensions to be the same + (:func:`equals_exact` ignores the Z and M dimensions), and NaN values + are considered to be equal to other NaN values. + + This function is the vectorized equivalent of scalar equality of + geometry objects (``a == b``, i.e. ``__eq__``). + + .. versionadded:: 2.1.0 + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + equals_exact : Check if geometries are structurally equal given a specified + tolerance. + equals : Check if geometries are spatially (topologically) equal. + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> shapely.equals_identical(Point(1, 2, 3), Point(1, 2, 3)) + True + >>> shapely.equals_identical(Point(1, 2, 3), Point(1, 2, 0)) + False + """ + return lib.equals_identical(a, b, **kwargs) + + +def relate(a, b, **kwargs): + """Return a string representation of the DE-9IM intersection matrix. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> point = Point(0, 0) + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.relate(point, line) + 'F0FFFF102' + + """ + return lib.relate(a, b, **kwargs) + + +@multithreading_enabled +def relate_pattern(a, b, pattern, **kwargs): + """Return True if the DE-9IM relationship code satisfies the pattern. + + This function compares the DE-9IM code string for two geometries + against a specified pattern. If the string matches the pattern then + ``True`` is returned, otherwise ``False``. The pattern specified can + be an exact match (``0``, ``1`` or ``2``), a boolean match + (uppercase ``T`` or ``F``), or a wildcard (``*``). For example, + the pattern for the ``within`` predicate is ``'T*F**F***'``. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + pattern : string + The pattern to match the DE-9IM relationship code against. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Examples + -------- + >>> import shapely + >>> from shapely import Point, Polygon + >>> point = Point(0.5, 0.5) + >>> square = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + >>> shapely.relate(point, square) + '0FFFFF212' + >>> shapely.relate_pattern(point, square, "T*F**F***") + True + + """ + return lib.relate_pattern(a, b, pattern, **kwargs) + + +@multithreading_enabled +@requires_geos("3.10.0") +def dwithin(a, b, distance, **kwargs): + """Return True if the geometries are within a given distance. + + Using this function is more efficient than computing the distance and + comparing the result. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to check. + distance : float + Negative distances always return False. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + distance : compute the actual distance between A and B + prepare : improve performance by preparing ``a`` (the first argument) + + Examples + -------- + >>> import shapely + >>> from shapely import Point + >>> point = Point(0.5, 0.5) + >>> shapely.dwithin(point, Point(2, 0.5), 2) + True + >>> shapely.dwithin(point, Point(2, 0.5), [2, 1.5, 1]).tolist() + [True, True, False] + >>> shapely.dwithin(point, Point(0.5, 0.5), 0) + True + >>> shapely.dwithin(point, None, 100) + False + + """ + return lib.dwithin(a, b, distance, **kwargs) + + +@multithreading_enabled +def contains_xy(geom, x, y=None, **kwargs): + """Return True if the Point (x, y) is completely inside geom. + + This is a special-case (and faster) variant of the `contains` function + which avoids having to create a Point object if you start from x/y + coordinates. + + Note that in the case of points, the `contains_properly` predicate is + equivalent to `contains`. + + See the docstring of `contains` for more details about the predicate. + + Parameters + ---------- + geom : Geometry or array_like + Geometry or geometries to check if they contain the point. + x, y : float or array_like + Coordinates as separate x and y arrays, or a single array of + coordinate x, y tuples. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + contains : variant taking two geometries as input + + Notes + ----- + If you compare a small number of polygons or lines with many points, + it can be beneficial to prepare the geometries in advance using + :func:`shapely.prepare`. + + Examples + -------- + >>> import shapely + >>> from shapely import Point, Polygon + >>> area = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + >>> shapely.contains(area, Point(0.5, 0.5)) + True + >>> shapely.contains_xy(area, 0.5, 0.5) + True + + """ + if y is None: + coords = np.asarray(x) + x, y = coords[:, 0], coords[:, 1] + if isinstance(geom, lib.Geometry): + lib.prepare(geom) + return lib.contains_xy(geom, x, y, **kwargs) + + +@multithreading_enabled +def intersects_xy(geom, x, y=None, **kwargs): + """Return True if geom and the Point (x, y) share any portion of space. + + This is a special-case (and faster) variant of the `intersects` function + which avoids having to create a Point object if you start from x/y + coordinates. + + See the docstring of `intersects` for more details about the predicate. + + Parameters + ---------- + geom : Geometry or array_like + Geometry or geometries to check if they intersect with the point. + x, y : float or array_like + Coordinates as separate x and y arrays, or a single array of + coordinate x, y tuples. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + intersects : variant taking two geometries as input + + Notes + ----- + If you compare a single or few geometries with many points, it can be + beneficial to prepare the geometries in advance using + :func:`shapely.prepare`. + + The `touches` predicate can be determined with this function by getting + the boundary of the geometries: ``intersects_xy(boundary(geom), x, y)``. + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> line = LineString([(0, 0), (1, 1)]) + >>> shapely.intersects(line, Point(0, 0)) + True + >>> shapely.intersects_xy(line, 0, 0) + True + + """ + if y is None: + coords = np.asarray(x) + x, y = coords[:, 0], coords[:, 1] + if isinstance(geom, lib.Geometry): + lib.prepare(geom) + return lib.intersects_xy(geom, x, y, **kwargs) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/prepared.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/prepared.py new file mode 100644 index 0000000000000000000000000000000000000000..f029f4ccd34534e19557b5a954a840e3fb9dd90d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/prepared.py @@ -0,0 +1,74 @@ +"""Support for GEOS prepared geometry operations.""" + +from pickle import PicklingError + +import shapely + + +class PreparedGeometry: + """A geometry prepared for efficient comparison to a set of other geometries. + + Examples + -------- + >>> from shapely.prepared import prep + >>> from shapely.geometry import Point, Polygon + >>> triangle = Polygon([(0.0, 0.0), (1.0, 1.0), (1.0, -1.0)]) + >>> p = prep(triangle) + >>> p.intersects(Point(0.5, 0.5)) + True + + """ + + def __init__(self, context): + """Prepare a geometry for efficient comparison to other geometries.""" + if isinstance(context, PreparedGeometry): + self.context = context.context + else: + shapely.prepare(context) + self.context = context + self.prepared = True + + def contains(self, other): + """Return True if the geometry contains the other, else False.""" + return self.context.contains(other) + + def contains_properly(self, other): + """Return True if the geometry properly contains the other, else False.""" + return self.context.contains_properly(other) + + def covers(self, other): + """Return True if the geometry covers the other, else False.""" + return self.context.covers(other) + + def crosses(self, other): + """Return True if the geometries cross, else False.""" + return self.context.crosses(other) + + def disjoint(self, other): + """Return True if geometries are disjoint, else False.""" + return self.context.disjoint(other) + + def intersects(self, other): + """Return True if geometries intersect, else False.""" + return self.context.intersects(other) + + def overlaps(self, other): + """Return True if geometries overlap, else False.""" + return self.context.overlaps(other) + + def touches(self, other): + """Return True if geometries touch, else False.""" + return self.context.touches(other) + + def within(self, other): + """Return True if geometry is within the other, else False.""" + return self.context.within(other) + + def __reduce__(self): + """Pickling is not supported.""" + raise PicklingError("Prepared geometries cannot be pickled.") + + +def prep(ob): + """Create and return a prepared geometric object.""" + return PreparedGeometry(ob) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/set_operations.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/set_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..f2d75d49d3cda1a16bc5f540ed4578baf01ebf12 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/set_operations.py @@ -0,0 +1,787 @@ +"""Set-theoretic operations on geometry objects.""" + +import warnings + +import numpy as np + +from shapely import Geometry, GeometryType, lib +from shapely.decorators import ( + deprecate_positional, + multithreading_enabled, + requires_geos, +) + +__all__ = [ + "coverage_union", + "coverage_union_all", + "difference", + "disjoint_subset_union", + "disjoint_subset_union_all", + "intersection", + "intersection_all", + "symmetric_difference", + "symmetric_difference_all", + "unary_union", + "union", + "union_all", +] + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# difference(a, b, grid_size=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'grid_size' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'b' +# difference(a, b, *, grid_size=None, **kwargs) + + +@deprecate_positional(["grid_size"], category=DeprecationWarning) +@multithreading_enabled +def difference(a, b, grid_size=None, **kwargs): + """Return the part of geometry A that does not intersect with geometry B. + + If grid_size is nonzero, input coordinates will be snapped to a precision + grid of that size and resulting coordinates will be snapped to that same + grid. If 0, this operation will use double precision coordinates. If None, + the highest precision of the inputs will be used, which may be previously + set using set_precision. Note: returned geometry does not have precision + set unless specified previously by set_precision. + + Parameters + ---------- + a : Geometry or array_like + Geometry or geometries to subtract b from. + b : Geometry or array_like + Geometry or geometries to subtract from a. + grid_size : float, optional + Precision grid size; will use the highest precision of the inputs by default. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``grid_size`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + set_precision + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line = LineString([(0, 0), (2, 2)]) + >>> shapely.difference(line, LineString([(1, 1), (3, 3)])) + + >>> shapely.difference(line, LineString()) + + >>> shapely.difference(line, None) is None + True + >>> box1 = shapely.box(0, 0, 2, 2) + >>> box2 = shapely.box(1, 1, 3, 3) + >>> shapely.difference(box1, box2).normalize() + + >>> box1 = shapely.box(0.1, 0.2, 2.1, 2.1) + >>> shapely.difference(box1, box2, grid_size=1) + + + """ + if grid_size is not None: + if not np.isscalar(grid_size): + raise ValueError("grid_size parameter only accepts scalar values") + + return lib.difference_prec(a, b, grid_size, **kwargs) + + return lib.difference(a, b, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# intersection(a, b, grid_size=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'grid_size' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'b' +# intersection(a, b, *, grid_size=None, **kwargs) + + +@deprecate_positional(["grid_size"], category=DeprecationWarning) +@multithreading_enabled +def intersection(a, b, grid_size=None, **kwargs): + """Return the geometry that is shared between input geometries. + + If grid_size is nonzero, input coordinates will be snapped to a precision + grid of that size and resulting coordinates will be snapped to that same + grid. If 0, this operation will use double precision coordinates. If None, + the highest precision of the inputs will be used, which may be previously + set using set_precision. Note: returned geometry does not have precision + set unless specified previously by set_precision. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to intersect with. + grid_size : float, optional + Precision grid size; will use the highest precision of the inputs by default. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``grid_size`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + intersection_all + set_precision + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line = LineString([(0, 0), (2, 2)]) + >>> shapely.intersection(line, LineString([(1, 1), (3, 3)])) + + >>> box1 = shapely.box(0, 0, 2, 2) + >>> box2 = shapely.box(1, 1, 3, 3) + >>> shapely.intersection(box1, box2).normalize() + + >>> box1 = shapely.box(0.1, 0.2, 2.1, 2.1) + >>> shapely.intersection(box1, box2, grid_size=1) + + + """ + if grid_size is not None: + if not np.isscalar(grid_size): + raise ValueError("grid_size parameter only accepts scalar values") + + return lib.intersection_prec(a, b, grid_size, **kwargs) + + return lib.intersection(a, b, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# intersection_all(geometries, axis=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'axis' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'geometries' +# intersection_all(geometries, *, axis=None, **kwargs) + + +@deprecate_positional(["axis"], category=DeprecationWarning) +@multithreading_enabled +def intersection_all(geometries, axis=None, **kwargs): + """Return the intersection of multiple geometries. + + This function ignores None values when other Geometry elements are present. + If all elements of the given axis are None, an empty GeometryCollection is + returned. + + Parameters + ---------- + geometries : array_like + Geometries to calculate the intersection of. + axis : int, optional + Axis along which the operation is performed. The default (None) + performs the operation over all axes, returning a scalar value. + Axis may be negative, in which case it counts from the last to the + first axis. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``axis`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + intersection + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line1 = LineString([(0, 0), (2, 2)]) + >>> line2 = LineString([(1, 1), (3, 3)]) + >>> shapely.intersection_all([line1, line2]) + + >>> shapely.intersection_all([[line1, line2, None]], axis=1).tolist() + [] + >>> shapely.intersection_all([line1, None]) + + + """ + geometries = np.asarray(geometries) + if axis is None: + geometries = geometries.ravel() + else: + geometries = np.rollaxis(geometries, axis=axis, start=geometries.ndim) + + return lib.intersection_all(geometries, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# symmetric_difference(a, b, grid_size=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'grid_size' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'b' +# symmetric_difference(a, b, *, grid_size=None, **kwargs) + + +@deprecate_positional(["grid_size"], category=DeprecationWarning) +@multithreading_enabled +def symmetric_difference(a, b, grid_size=None, **kwargs): + """Return the geometry with the portions of input geometries that do not intersect. + + If grid_size is nonzero, input coordinates will be snapped to a precision + grid of that size and resulting coordinates will be snapped to that same + grid. If 0, this operation will use double precision coordinates. If None, + the highest precision of the inputs will be used, which may be previously + set using set_precision. Note: returned geometry does not have precision + set unless specified previously by set_precision. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to evaluate symmetric difference with. + grid_size : float, optional + Precision grid size; will use the highest precision of the inputs by default. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``grid_size`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + symmetric_difference_all + set_precision + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line = LineString([(0, 0), (2, 2)]) + >>> shapely.symmetric_difference(line, LineString([(1, 1), (3, 3)])) + + >>> box1 = shapely.box(0, 0, 2, 2) + >>> box2 = shapely.box(1, 1, 3, 3) + >>> shapely.symmetric_difference(box1, box2).normalize() + + >>> box1 = shapely.box(0.1, 0.2, 2.1, 2.1) + >>> shapely.symmetric_difference(box1, box2, grid_size=1) + + + """ + if grid_size is not None: + if not np.isscalar(grid_size): + raise ValueError("grid_size parameter only accepts scalar values") + + return lib.symmetric_difference_prec(a, b, grid_size, **kwargs) + + return lib.symmetric_difference(a, b, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# symmetric_difference_all(geometries, axis=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'axis' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'geometries' +# symmetric_difference_all(geometries, *, axis=None, **kwargs) + + +@deprecate_positional(["axis"], category=DeprecationWarning) +@multithreading_enabled +def symmetric_difference_all(geometries, axis=None, **kwargs): + """Return the symmetric difference of multiple geometries. + + This function ignores None values when other Geometry elements are present. + If all elements of the given axis are None an empty GeometryCollection is + returned. + + .. deprecated:: 2.1.0 + + This function behaves incorrectly and will be removed in a future + version. See https://github.com/shapely/shapely/issues/2027 for more + details. + + Parameters + ---------- + geometries : array_like + Geometries to calculate the combined symmetric difference of. + axis : int, optional + Axis along which the operation is performed. The default (None) + performs the operation over all axes, returning a scalar value. + Axis may be negative, in which case it counts from the last to the + first axis. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``axis`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + symmetric_difference + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line1 = LineString([(0, 0), (2, 2)]) + >>> line2 = LineString([(1, 1), (3, 3)]) + >>> shapely.symmetric_difference_all([line1, line2]) + + >>> shapely.symmetric_difference_all([[line1, line2, None]], axis=1).tolist() + [] + >>> shapely.symmetric_difference_all([line1, None]) + + >>> shapely.symmetric_difference_all([None, None]) + + + """ + warnings.warn( + "The symmetric_difference_all function behaves incorrectly and will be " + "removed in a future version. " + "See https://github.com/shapely/shapely/issues/2027 for more details.", + DeprecationWarning, + stacklevel=2, + ) + geometries = np.asarray(geometries) + if axis is None: + geometries = geometries.ravel() + else: + geometries = np.rollaxis(geometries, axis=axis, start=geometries.ndim) + + return lib.symmetric_difference_all(geometries, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# union(a, b, grid_size=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'grid_size' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'b' +# union(a, b, *, grid_size=None, **kwargs) + + +@deprecate_positional(["grid_size"], category=DeprecationWarning) +@multithreading_enabled +def union(a, b, grid_size=None, **kwargs): + """Merge geometries into one. + + If grid_size is nonzero, input coordinates will be snapped to a precision + grid of that size and resulting coordinates will be snapped to that same + grid. If 0, this operation will use double precision coordinates. If None, + the highest precision of the inputs will be used, which may be previously + set using set_precision. Note: returned geometry does not have precision + set unless specified previously by set_precision. + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to merge (union). + grid_size : float, optional + Precision grid size; will use the highest precision of the inputs by default. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``grid_size`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + union_all + set_precision + + Examples + -------- + >>> import shapely + >>> from shapely import LineString + >>> line = LineString([(0, 0), (2, 2)]) + >>> shapely.union(line, LineString([(2, 2), (3, 3)])) + + >>> shapely.union(line, None) is None + True + >>> box1 = shapely.box(0, 0, 2, 2) + >>> box2 = shapely.box(1, 1, 3, 3) + >>> shapely.union(box1, box2).normalize() + + >>> box1 = shapely.box(0.1, 0.2, 2.1, 2.1) + >>> shapely.union(box1, box2, grid_size=1) + + + """ + if grid_size is not None: + if not np.isscalar(grid_size): + raise ValueError("grid_size parameter only accepts scalar values") + + return lib.union_prec(a, b, grid_size, **kwargs) + + return lib.union(a, b, **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# union_all(geometries, grid_size=None, axis=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'grid_size' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'geometries' +# union_all(geometries, *, grid_size=None, axis=None, **kwargs) + + +@deprecate_positional(["grid_size", "axis"], category=DeprecationWarning) +@multithreading_enabled +def union_all(geometries, grid_size=None, axis=None, **kwargs): + """Return the union of multiple geometries. + + This function ignores None values when other Geometry elements are present. + If all elements of the given axis are None an empty GeometryCollection is + returned. + + If grid_size is nonzero, input coordinates will be snapped to a precision + grid of that size and resulting coordinates will be snapped to that same + grid. If 0, this operation will use double precision coordinates. If None, + the highest precision of the inputs will be used, which may be previously + set using set_precision. Note: returned geometry does not have precision + set unless specified previously by set_precision. + + `unary_union` is an alias of `union_all`. + + Parameters + ---------- + geometries : array_like + Geometries to merge/union. + grid_size : float, optional + Precision grid size; will use the highest precision of the inputs by default. + axis : int, optional + Axis along which the operation is performed. The default (None) + performs the operation over all axes, returning a scalar value. + Axis may be negative, in which case it counts from the last to the + first axis. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``grid_size`` or ``axis`` are + specified as positional arguments. In a future release, these will + need to be specified as keyword arguments. + + See Also + -------- + union + set_precision + + Examples + -------- + >>> import shapely + >>> from shapely import LineString, Point + >>> line1 = LineString([(0, 0), (2, 2)]) + >>> line2 = LineString([(2, 2), (3, 3)]) + >>> shapely.union_all([line1, line2]) + + >>> shapely.union_all([[line1, line2, None]], axis=1).tolist() + [] + >>> box1 = shapely.box(0, 0, 2, 2) + >>> box2 = shapely.box(1, 1, 3, 3) + >>> shapely.union_all([box1, box2]).normalize() + + >>> box1 = shapely.box(0.1, 0.2, 2.1, 2.1) + >>> shapely.union_all([box1, box2], grid_size=1) + + >>> shapely.union_all([None, Point(0, 1)]) + + >>> shapely.union_all([None, None]) + + >>> shapely.union_all([]) + + + """ + # for union_all, GEOS provides an efficient route through first creating + # GeometryCollections + # first roll the aggregation axis backwards + geometries = np.asarray(geometries) + if axis is None: + geometries = geometries.ravel() + else: + geometries = np.rollaxis(geometries, axis=axis, start=geometries.ndim) + + # create_collection acts on the inner axis + collections = lib.create_collection( + geometries, np.intc(GeometryType.GEOMETRYCOLLECTION) + ) + + if grid_size is not None: + if not np.isscalar(grid_size): + raise ValueError("grid_size parameter only accepts scalar values") + + return lib.unary_union_prec(collections, grid_size, **kwargs) + + return lib.unary_union(collections, **kwargs) + + +unary_union = union_all + + +@multithreading_enabled +def coverage_union(a, b, **kwargs): + """Merge multiple polygons into one. + + This is an optimized version of union which assumes the polygons to be + non-overlapping. + If this assumption is not met, the exact result is not guaranteed + (depending on the GEOS version, it may return the input unchanged or raise + an error). + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to merge (union). + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + coverage_union_all + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> polygon_1 = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + >>> polygon_2 = Polygon([(1, 0), (1, 1), (2, 1), (2, 0), (1, 0)]) + >>> shapely.coverage_union(polygon_1, polygon_2).normalize() + + + Union with None returns same polygon + + >>> shapely.coverage_union(polygon_1, None).normalize() + + + """ + return coverage_union_all([a, b], **kwargs) + + +# Note: future plan is to change this signature over a few releases: +# shapely 2.0: +# coverage_union_all(geometries, axis=None, **kwargs) +# shapely 2.1: shows deprecation warning about positional 'axis' arg +# same signature as 2.0 +# shapely 2.2(?): enforce keyword-only arguments after 'geometries' +# coverage_union_all(geometries, *, axis=None, **kwargs) + + +@deprecate_positional(["axis"], category=DeprecationWarning) +@multithreading_enabled +def coverage_union_all(geometries, axis=None, **kwargs): + """Return the union of multiple polygons of a geometry collection. + + This is an optimized version of union which assumes the polygons + to be non-overlapping. + + This function ignores None values when other Geometry elements are present. + If all elements of the given axis are None, an empty GeometryCollection is + returned (before GEOS 3.12 this was an empty MultiPolygon). + + Parameters + ---------- + geometries : array_like + Geometries to merge/union. + axis : int, optional + Axis along which the operation is performed. The default (None) + performs the operation over all axes, returning a scalar value. + Axis may be negative, in which case it counts from the last to the + first axis. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + Notes + ----- + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``axis`` is specified as a + positional argument. This will need to be specified as a keyword + argument in a future release. + + See Also + -------- + coverage_union + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> polygon_1 = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + >>> polygon_2 = Polygon([(1, 0), (1, 1), (2, 1), (2, 0), (1, 0)]) + >>> shapely.coverage_union_all([polygon_1, polygon_2]).normalize() + + >>> shapely.coverage_union_all([polygon_1, None]).normalize() + + >>> shapely.coverage_union_all([None, None]).normalize() + + + """ + # coverage union in GEOS works over GeometryCollections + # first roll the aggregation axis backwards + geometries = np.asarray(geometries) + if axis is None: + geometries = geometries.ravel() + else: + geometries = np.rollaxis( + np.asarray(geometries), axis=axis, start=geometries.ndim + ) + # create_collection acts on the inner axis + collections = lib.create_collection( + geometries, np.intc(GeometryType.GEOMETRYCOLLECTION) + ) + return lib.coverage_union(collections, **kwargs) + + +@requires_geos("3.12.0") +@multithreading_enabled +def disjoint_subset_union(a, b, **kwargs): + """Merge multiple polygons into one using algorithm optimised for subsets. + + This is an optimized version of union which assumes inputs can be + divided into subsets that do not intersect. + + If there is only one such subset, performance can be expected to be worse than + :func:`union`. As such, it is recommeded to use ``disjoint_subset_union`` with + GeometryCollections rather than individual geometries. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + a, b : Geometry or array_like + Geometry or geometries to merge (union). + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + union + coverage_union + disjoint_subset_union_all + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> polygon_1 = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + >>> polygon_2 = Polygon([(1, 0), (1, 1), (2, 1), (2, 0), (1, 0)]) + >>> shapely.disjoint_subset_union(polygon_1, polygon_2).normalize() + + + Union with None returns same polygon: + + >>> shapely.disjoint_subset_union(polygon_1, None).normalize() + + """ + if (isinstance(a, Geometry) or a is None) and ( + isinstance(b, Geometry) or b is None + ): + pass + elif isinstance(a, Geometry) or a is None: + a = np.full_like(b, a) + elif isinstance(b, Geometry) or b is None: + b = np.full_like(a, b) + elif len(a) != len(b): + raise ValueError("Arrays a and b must have the same length") + return disjoint_subset_union_all([a, b], axis=0, **kwargs) + + +@requires_geos("3.12.0") +@multithreading_enabled +def disjoint_subset_union_all(geometries, *, axis=None, **kwargs): + """Return the union of multiple polygons. + + This is an optimized version of union which assumes inputs can be divided into + subsets that do not intersect. + + If there is only one such subset, performance can be expected to be worse than + :func:`union_all`. + + This function ignores None values when other Geometry elements are present. + If all elements of the given axis are None, an empty GeometryCollection is + returned. + + .. versionadded:: 2.1.0 + + Parameters + ---------- + geometries : array_like + Geometries to union. + axis : int, optional + Axis along which the operation is performed. The default (None) + performs the operation over all axes, returning a scalar value. + Axis may be negative, in which case it counts from the last to the + first axis. + **kwargs + See :ref:`NumPy ufunc docs ` for other keyword arguments. + + See Also + -------- + coverage_union_all + union_all + disjoint_subset_union + + Examples + -------- + >>> import shapely + >>> from shapely import Polygon + >>> polygon_1 = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + >>> polygon_2 = Polygon([(1, 0), (1, 1), (2, 1), (2, 0), (1, 0)]) + >>> shapely.disjoint_subset_union_all([polygon_1, polygon_2]).normalize() + + >>> shapely.disjoint_subset_union_all([polygon_1, None]).normalize() + + >>> shapely.disjoint_subset_union_all([None, None]).normalize() + + """ + geometries = np.asarray(geometries) + if axis is None: + geometries = geometries.ravel() + else: + geometries = np.rollaxis( + np.asarray(geometries), axis=axis, start=geometries.ndim + ) + # create_collection acts on the inner axis + collections = lib.create_collection( + geometries, np.intc(GeometryType.GEOMETRYCOLLECTION) + ) + + return lib.disjoint_subset_union(collections, **kwargs) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/speedups.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/speedups.py new file mode 100644 index 0000000000000000000000000000000000000000..7ab3d0077b04691871024041231a059bd66a029d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/speedups.py @@ -0,0 +1,39 @@ +"""Speedups for Shapely geometry operations. + +.. deprecated:: 2.0 + Deprecated in Shapely 2.0, and will be removed in a future version. + +""" + +import warnings + +__all__ = ["available", "disable", "enable", "enabled"] + + +available = True +enabled = True + + +_MSG = ( + "This function has no longer any effect, and will be removed in a " + "future release. Starting with Shapely 2.0, equivalent speedups are " + "always available" +) + + +def enable(): + """Will be removed in a future release and has no longer any effect. + + Previously, this function enabled cython-based speedups. Starting with + Shapely 2.0, equivalent speedups are available in every installation. + """ + warnings.warn(_MSG, FutureWarning, stacklevel=2) + + +def disable(): + """Will be removed in a future release and has no longer any effect. + + Previously, this function enabled cython-based speedups. Starting with + Shapely 2.0, equivalent speedups are available in every installation. + """ + warnings.warn(_MSG, FutureWarning, stacklevel=2) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/strtree.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/strtree.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d772cc5ff44e72cc38afbe64591868ca926b91 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/strtree.py @@ -0,0 +1,550 @@ +"""STRtree spatial index for efficient spatial queries.""" + +from collections.abc import Iterable +from typing import Any + +import numpy as np + +from shapely import lib +from shapely._enum import ParamEnum +from shapely.decorators import UnsupportedGEOSVersionError +from shapely.geometry.base import BaseGeometry +from shapely.predicates import is_empty, is_missing + +__all__ = ["STRtree"] + + +class BinaryPredicate(ParamEnum): + """The enumeration of GEOS binary predicates types.""" + + intersects = 1 + within = 2 + contains = 3 + overlaps = 4 + crosses = 5 + touches = 6 + covers = 7 + covered_by = 8 + contains_properly = 9 + + +class STRtree: + """A query-only R-tree spatial index. + + It is created using the Sort-Tile-Recursive (STR) [1]_ algorithm. + + The tree indexes the bounding boxes of each geometry. The tree is + constructed directly at initialization and nodes cannot be added or + removed after it has been created. + + All operations return indices of the input geometries. These indices + can be used to index into anything associated with the input geometries, + including the input geometries themselves, or custom items stored in + another object of the same length as the geometries. + + Bounding boxes limited to two dimensions and are axis-aligned (equivalent to + the ``bounds`` property of a geometry); any Z values present in geometries + are ignored for purposes of indexing within the tree. + + Any mixture of geometry types may be stored in the tree. + + Note: the tree is more efficient for querying when there are fewer + geometries that have overlapping bounding boxes and where there is greater + similarity between the outer boundary of a geometry and its bounding box. + For example, a MultiPolygon composed of widely-spaced individual Polygons + will have a large overall bounding box compared to the boundaries of its + individual Polygons, and the bounding box may also potentially overlap many + other geometries within the tree. This means that the resulting tree may be + less efficient to query than a tree constructed from individual Polygons. + + Parameters + ---------- + geoms : sequence + A sequence of geometry objects. + node_capacity : int, default 10 + The maximum number of child nodes per parent node in the tree. + + References + ---------- + .. [1] Leutenegger, Scott T.; Edgington, Jeffrey M.; Lopez, Mario A. + (February 1997). "STR: A Simple and Efficient Algorithm for + R-Tree Packing". + https://ia600900.us.archive.org/27/items/nasa_techdoc_19970016975/19970016975.pdf + + """ + + def __init__(self, geoms: Iterable[BaseGeometry], node_capacity: int = 10): + """Create a new STRtree spatial index.""" + # Keep references to geoms in a copied array so that this array is not + # modified while the tree depends on it remaining the same + self._geometries = np.array(geoms, dtype=np.object_, copy=True) + + # initialize GEOS STRtree + self._tree = lib.STRtree(self.geometries, node_capacity) + + def __len__(self): + """Return the number of geometries in the tree.""" + return self._tree.count + + def __reduce__(self): + """Pickle support.""" + return (STRtree, (self.geometries,)) + + @property + def geometries(self): + """Geometries stored in the tree in the order used to construct the tree. + + The order of this array corresponds to the tree indices returned by + other STRtree methods. + + Do not attempt to modify items in the returned array. + + Returns + ------- + ndarray of Geometry objects + + """ + return self._geometries + + def query(self, geometry, predicate=None, distance=None): + """Get the index combinations of all possibly intersecting geometries. + + Returns the integer indices of all combinations of each input geometry + and tree geometries where the bounding box of each input geometry + intersects the bounding box of a tree geometry. + + If the input geometry is a scalar, this returns an array of shape (n, ) with + the indices of the matching tree geometries. If the input geometry is an + array_like, this returns an array with shape (2,n) where the subarrays + correspond to the indices of the input geometries and indices of the + tree geometries associated with each. To generate an array of pairs of + input geometry index and tree geometry index, simply transpose the + result. + + If a predicate is provided, the tree geometries are first queried based + on the bounding box of the input geometry and then are further filtered + to those that meet the predicate when comparing the input geometry to + the tree geometry: + predicate(geometry, tree_geometry) + + The 'dwithin' predicate requires GEOS >= 3.10. + + Bounding boxes are limited to two dimensions and are axis-aligned + (equivalent to the ``bounds`` property of a geometry); any Z values + present in input geometries are ignored when querying the tree. + + Any input geometry that is None or empty will never match geometries in + the tree. + + Parameters + ---------- + geometry : Geometry or array_like + Input geometries to query the tree and filter results using the + optional predicate. + predicate : {None, 'intersects', 'within', 'contains', 'overlaps', 'crosses',\ +'touches', 'covers', 'covered_by', 'contains_properly', 'dwithin'}, optional + The predicate to use for testing geometries from the tree + that are within the input geometry's bounding box. + distance : number or array_like, optional + Distances around each input geometry within which to query the tree + for the 'dwithin' predicate. If array_like, shape must be + broadcastable to shape of geometry. Required if predicate='dwithin'. + + Returns + ------- + ndarray with shape (n,) if geometry is a scalar + Contains tree geometry indices. + + OR + + ndarray with shape (2, n) if geometry is an array_like + The first subarray contains input geometry indices. + The second subarray contains tree geometry indices. + + Examples + -------- + >>> from shapely import box, Point, STRtree + >>> import numpy as np + >>> points = [Point(0, 0), Point(1, 1), Point(2,2), Point(3, 3)] + >>> tree = STRtree(points) + + Query the tree using a scalar geometry: + + >>> indices = tree.query(box(0, 0, 1, 1)) + >>> indices.tolist() + [0, 1] + + Query using an array of geometries: + + >>> boxes = np.array([box(0, 0, 1, 1), box(2, 2, 3, 3)]) + >>> arr_indices = tree.query(boxes) + >>> arr_indices.tolist() + [[0, 0, 1, 1], [0, 1, 2, 3]] + + Or transpose to get all pairs of input and tree indices: + + >>> arr_indices.T.tolist() + [[0, 0], [0, 1], [1, 2], [1, 3]] + + Retrieve the tree geometries by results of query: + + >>> tree.geometries.take(indices).tolist() + [, ] + + Retrieve all pairs of input and tree geometries: + + >>> np.array([boxes.take(arr_indices[0]),\ +tree.geometries.take(arr_indices[1])]).T.tolist() + [[, ], + [, ], + [, ], + [, ]] + + Query using a predicate: + + >>> tree = STRtree([box(0, 0, 0.5, 0.5), box(0.5, 0.5, 1, 1), box(1, 1, 2, 2)]) + >>> tree.query(box(0, 0, 1, 1), predicate="contains").tolist() + [0, 1] + >>> tree.query(Point(0.75, 0.75), predicate="dwithin", distance=0.5).tolist() + [0, 1, 2] + + >>> tree.query(boxes, predicate="contains").tolist() + [[0, 0], [0, 1]] + >>> tree.query(boxes, predicate="dwithin", distance=0.5).tolist() + [[0, 0, 0, 1], [0, 1, 2, 2]] + + Retrieve custom items associated with tree geometries (records can + be in whatever data structure so long as geometries and custom data + can be extracted into arrays of the same length and order): + + >>> records = [ + ... {"geometry": Point(0, 0), "value": "A"}, + ... {"geometry": Point(2, 2), "value": "B"} + ... ] + >>> tree = STRtree([record["geometry"] for record in records]) + >>> items = np.array([record["value"] for record in records]) + >>> items.take(tree.query(box(0, 0, 1, 1))).tolist() + ['A'] + + + Notes + ----- + In the context of a spatial join, input geometries are the "left" + geometries that determine the order of the results, and tree geometries + are "right" geometries that are joined against the left geometries. This + effectively performs an inner join, where only those combinations of + geometries that can be joined based on overlapping bounding boxes or + optional predicate are returned. + + """ + geometry = np.asarray(geometry) + is_scalar = False + if geometry.ndim == 0: + geometry = np.expand_dims(geometry, 0) + is_scalar = True + + if predicate is None: + indices = self._tree.query(geometry, 0) + return indices[1] if is_scalar else indices + + # Requires GEOS >= 3.10 + elif predicate == "dwithin": + if lib.geos_version < (3, 10, 0): + raise UnsupportedGEOSVersionError( + "dwithin predicate requires GEOS >= 3.10" + ) + if distance is None: + raise ValueError( + "distance parameter must be provided for dwithin predicate" + ) + distance = np.asarray(distance, dtype="float64") + if distance.ndim > 1: + raise ValueError("Distance array should be one dimensional") + + try: + distance = np.broadcast_to(distance, geometry.shape) + except ValueError: + raise ValueError("Could not broadcast distance to match geometry") + + indices = self._tree.dwithin(geometry, distance) + return indices[1] if is_scalar else indices + + predicate = BinaryPredicate.get_value(predicate) + indices = self._tree.query(geometry, predicate) + return indices[1] if is_scalar else indices + + def nearest(self, geometry) -> Any | None: + """Return the index of the nearest geometry in the tree. + + This is determined for each input geometry based on distance within + two-dimensional Cartesian space. + + This distance will be 0 when input geometries intersect tree geometries. + + If there are multiple equidistant or intersected geometries in the tree, + only a single result is returned for each input geometry, based on the + order that tree geometries are visited; this order may be + nondeterministic. + + If any input geometry is None or empty, an error is raised. Any Z + values present in input geometries are ignored when finding nearest + tree geometries. + + Parameters + ---------- + geometry : Geometry or array_like + Input geometries to query the tree. + + Returns + ------- + scalar or ndarray + Indices of geometries in tree. Return value will have the same shape + as the input. + + None is returned if this index is empty. This may change in + version 2.0. + + See Also + -------- + query_nearest: returns all equidistant geometries, exclusive geometries, \ +and optional distances + + Examples + -------- + >>> from shapely import Point, STRtree + >>> tree = STRtree([Point(i, i) for i in range(10)]) + + Query the tree for nearest using a scalar geometry: + + >>> index = tree.nearest(Point(2.2, 2.2)) + >>> index + 2 + >>> tree.geometries.take(index) + + + Query the tree for nearest using an array of geometries: + + >>> indices = tree.nearest([Point(2.2, 2.2), Point(4.4, 4.4)]) + >>> indices.tolist() + [2, 4] + >>> tree.geometries.take(indices).tolist() + [, ] + + Nearest only return one object if there are multiple equidistant results: + + >>> tree = STRtree ([Point(0, 0), Point(0, 0)]) + >>> tree.nearest(Point(0, 0)) + 0 + + """ + if self._tree.count == 0: + return None + + geometry_arr = np.asarray(geometry, dtype=object) + if is_missing(geometry_arr).any() or is_empty(geometry_arr).any(): + raise ValueError( + "Cannot determine nearest geometry for empty geometry or " + "missing value (None)." + ) + # _tree.nearest returns ndarray with shape (2, 1) -> index in input + # geometries and index into tree geometries + indices = self._tree.nearest(np.atleast_1d(geometry_arr))[1] + + if geometry_arr.ndim == 0: + return indices[0] + else: + return indices + + def query_nearest( + self, + geometry, + max_distance=None, + return_distance=False, + exclusive=False, + all_matches=True, + ): + """Return the index of the nearest geometries in the tree. + + This is determined for each input geometry based on distance within + two-dimensional Cartesian space. + + This distance will be 0 when input geometries intersect tree geometries. + + If there are multiple equidistant or intersected geometries in tree and + `all_matches` is True (the default), all matching tree geometries are + returned; otherwise only the first matching tree geometry is returned. + Tree indices are returned in the order they are visited for each input + geometry and may not be in ascending index order; no meaningful order is + implied. + + The max_distance used to search for nearest items in the tree may have a + significant impact on performance by reducing the number of input + geometries that are evaluated for nearest items in the tree. Only those + input geometries with at least one tree geometry within +/- max_distance + beyond their envelope will be evaluated. However, using a large + max_distance may have a negative performance impact because many tree + geometries will be queried for each input geometry. + + The distance, if returned, will be 0 for any intersected geometries in + the tree. + + Any geometry that is None or empty in the input geometries is omitted + from the output. Any Z values present in input geometries are ignored + when finding nearest tree geometries. + + Parameters + ---------- + geometry : Geometry or array_like + Input geometries to query the tree. + max_distance : float, optional + Maximum distance within which to query for nearest items in tree. + Must be greater than 0. + return_distance : bool, default False + If True, will return distances in addition to indices. + exclusive : bool, default False + If True, the nearest tree geometries that are equal to the input + geometry will not be returned. + all_matches : bool, default True + If True, all equidistant and intersected geometries will be returned + for each input geometry. + If False, only the first nearest geometry will be returned. + + Returns + ------- + tree indices or tuple of (tree indices, distances) if geometry is a scalar + indices is an ndarray of shape (n, ) and distances (if present) an + ndarray of shape (n, ) + + OR + + indices or tuple of (indices, distances) + indices is an ndarray of shape (2,n) and distances (if present) an + ndarray of shape (n). + The first subarray of indices contains input geometry indices. + The second subarray of indices contains tree geometry indices. + + See Also + -------- + nearest: returns singular nearest geometry for each input + + Examples + -------- + >>> import numpy as np + >>> from shapely import box, Point, STRtree + >>> points = [Point(0, 0), Point(1, 1), Point(2,2), Point(3, 3)] + >>> tree = STRtree(points) + + Find the nearest tree geometries to a scalar geometry: + + >>> indices = tree.query_nearest(Point(0.25, 0.25)) + >>> indices.tolist() + [0] + + Retrieve the tree geometries by results of query: + + >>> tree.geometries.take(indices).tolist() + [] + + Find the nearest tree geometries to an array of geometries: + + >>> query_points = np.array([Point(2.25, 2.25), Point(1, 1)]) + >>> arr_indices = tree.query_nearest(query_points) + >>> arr_indices.tolist() + [[0, 1], [2, 1]] + + Or transpose to get all pairs of input and tree indices: + + >>> arr_indices.T.tolist() + [[0, 2], [1, 1]] + + Retrieve all pairs of input and tree geometries: + + >>> list(zip(query_points.take(arr_indices[0]), tree.geometries.take(arr_indices[1]))) + [(, ), (, )] + + All intersecting geometries in the tree are returned by default: + + >>> tree.query_nearest(box(1,1,3,3)).tolist() + [1, 2, 3] + + Set all_matches to False to to return a single match per input geometry: + + >>> tree.query_nearest(box(1,1,3,3), all_matches=False).tolist() + [1] + + Return the distance to each nearest tree geometry: + + >>> index, distance = tree.query_nearest(Point(0.5, 0.5), return_distance=True) + >>> index.tolist() + [0, 1] + >>> distance.round(4).tolist() + [0.7071, 0.7071] + + Return the distance for each input and nearest tree geometry for an array + of geometries: + + >>> indices, distance = tree.query_nearest([Point(0.5, 0.5), Point(1, 1)], return_distance=True) + >>> indices.tolist() + [[0, 0, 1], [0, 1, 1]] + >>> distance.round(4).tolist() + [0.7071, 0.7071, 0.0] + + Retrieve custom items associated with tree geometries (records can + be in whatever data structure so long as geometries and custom data + can be extracted into arrays of the same length and order): + + >>> records = [ + ... {"geometry": Point(0, 0), "value": "A"}, + ... {"geometry": Point(2, 2), "value": "B"} + ... ] + >>> tree = STRtree([record["geometry"] for record in records]) + >>> items = np.array([record["value"] for record in records]) + >>> items.take(tree.query_nearest(Point(0.5, 0.5))).tolist() + ['A'] + + """ # noqa: E501 + geometry = np.asarray(geometry, dtype=object) + is_scalar = False + if geometry.ndim == 0: + geometry = np.expand_dims(geometry, 0) + is_scalar = True + + if max_distance is not None: + if not np.isscalar(max_distance): + raise ValueError("max_distance parameter only accepts scalar values") + + if max_distance <= 0: + raise ValueError("max_distance must be greater than 0") + + # a distance of 0 means no max_distance is used + max_distance = max_distance or 0 + + if not np.isscalar(exclusive): + raise ValueError("exclusive parameter only accepts scalar values") + + if exclusive not in {True, False}: + raise ValueError("exclusive parameter must be boolean") + + if not np.isscalar(all_matches): + raise ValueError("all_matches parameter only accepts scalar values") + + if all_matches not in {True, False}: + raise ValueError("all_matches parameter must be boolean") + + results = self._tree.query_nearest( + geometry, max_distance, exclusive, all_matches + ) + + # output indices are shape (n, ) + if is_scalar: + if not return_distance: + return results[0][1] + + else: + return (results[0][1], results[1]) + + # output indices are shape (2, n) + if not return_distance: + return results[0] + + return results diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/testing.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..80605c45e14478bbae57a0272bc708d3e9ee7b57 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/testing.py @@ -0,0 +1,208 @@ +"""Utilities for testing with shapely geometries.""" + +from functools import partial + +import numpy as np + +import shapely + +__all__ = ["assert_geometries_equal"] + + +def _equals_exact_with_ndim(x, y, tolerance): + dimension_equals = shapely.get_coordinate_dimension( + x + ) == shapely.get_coordinate_dimension(y) + with np.errstate(invalid="ignore"): + # Suppress 'invalid value encountered in equals_exact' with nan coordinates + geometry_equals = shapely.equals_exact(x, y, tolerance=tolerance) + return dimension_equals & geometry_equals + + +def _replace_nan(arr): + return np.where(np.isnan(arr), 0.0, arr) + + +def _assert_nan_coords_same(x, y, tolerance, err_msg, verbose): + x, y = np.broadcast_arrays(x, y) + x_coords = shapely.get_coordinates(x, include_z=True) + y_coords = shapely.get_coordinates(y, include_z=True) + + # Check the shapes (condition is copied from numpy test_array_equal) + if x_coords.shape != y_coords.shape: + return False + + # Check NaN positional equality + x_id = np.isnan(x_coords) + y_id = np.isnan(y_coords) + if not (x_id == y_id).all(): + msg = build_err_msg( + [x, y], + err_msg + "\nx and y nan coordinate location mismatch:", + verbose=verbose, + ) + raise AssertionError(msg) + + # If this passed, replace NaN with a number to be able to use equals_exact + x_no_nan = shapely.transform(x, _replace_nan, include_z=True) + y_no_nan = shapely.transform(y, _replace_nan, include_z=True) + + return _equals_exact_with_ndim(x_no_nan, y_no_nan, tolerance=tolerance) + + +def _assert_none_same(x, y, err_msg, verbose): + x_id = shapely.is_missing(x) + y_id = shapely.is_missing(y) + + if not (x_id == y_id).all(): + msg = build_err_msg( + [x, y], + err_msg + "\nx and y None location mismatch:", + verbose=verbose, + ) + raise AssertionError(msg) + + # If there is a scalar, then here we know the array has the same + # flag as it everywhere, so we should return the scalar flag. + if x.ndim == 0: + return bool(x_id) + elif y.ndim == 0: + return bool(y_id) + else: + return y_id + + +def assert_geometries_equal( + x, + y, + tolerance=1e-7, + equal_none=True, + equal_nan=True, + normalize=False, + err_msg="", + verbose=True, +): + """Raise an AssertionError if two geometry array_like objects are not equal. + + Given two array_like objects, check that the shape is equal and all elements + of these objects are equal. An exception is raised at shape mismatch or + conflicting values. In contrast to the standard usage in shapely, no + assertion is raised if both objects have NaNs/Nones in the same positions. + + Parameters + ---------- + x, y : Geometry or array_like + Geometry or geometries to compare. + tolerance: float, default 1e-7 + The tolerance to use when comparing geometries. + equal_none : bool, default True + Whether to consider None elements equal to other None elements. + equal_nan : bool, default True + Whether to consider nan coordinates as equal to other nan coordinates. + normalize : bool, default False + Whether to normalize geometries prior to comparison. + err_msg : str, optional + The error message to be printed in case of failure. + verbose : bool, optional + If True, the conflicting values are appended to the error message. + + """ + __tracebackhide__ = True # Hide traceback for py.test + if normalize: + x = shapely.normalize(x) + y = shapely.normalize(y) + x = np.asarray(x) + y = np.asarray(y) + + is_scalar = x.ndim == 0 or y.ndim == 0 + + # Check the shapes (condition is copied from numpy test_array_equal) + if not (is_scalar or x.shape == y.shape): + msg = build_err_msg( + [x, y], + err_msg + f"\n(shapes {x.shape}, {y.shape} mismatch)", + verbose=verbose, + ) + raise AssertionError(msg) + + flagged = False + if equal_none: + flagged = _assert_none_same(x, y, err_msg, verbose) + + if not np.isscalar(flagged): + x, y = x[~flagged], y[~flagged] + # Only do the comparison if actual values are left + if x.size == 0: + return + elif flagged: + # no sense doing comparison if everything is flagged. + return + + is_equal = _equals_exact_with_ndim(x, y, tolerance=tolerance) + if is_scalar and not np.isscalar(is_equal): + is_equal = bool(is_equal[0]) + + if np.all(is_equal): + return + elif not equal_nan: + msg = build_err_msg( + [x, y], + err_msg + f"\nNot equal to tolerance {tolerance:g}", + verbose=verbose, + ) + raise AssertionError(msg) + + # Optionally refine failing elements if NaN should be considered equal + if not np.isscalar(is_equal): + x, y = x[~is_equal], y[~is_equal] + # Only do the NaN check if actual values are left + if x.size == 0: + return + elif is_equal: + # no sense in checking for NaN if everything is equal. + return + + is_equal = _assert_nan_coords_same(x, y, tolerance, err_msg, verbose) + if not np.all(is_equal): + msg = build_err_msg( + [x, y], + err_msg + f"\nNot equal to tolerance {tolerance:g}", + verbose=verbose, + ) + raise AssertionError(msg) + + +## BELOW A COPY FROM numpy.testing._private.utils (numpy version 1.20.2) + + +def build_err_msg( + arrays, + err_msg, + header="Geometries are not equal:", + verbose=True, + names=("x", "y"), + precision=8, +): + msg = ["\n" + header] + if err_msg: + if err_msg.find("\n") == -1 and len(err_msg) < 79 - len(header): + msg = [msg[0] + " " + err_msg] + else: + msg.append(err_msg) + if verbose: + for i, a in enumerate(arrays): + if isinstance(a, np.ndarray): + # precision argument is only needed if the objects are ndarrays + r_func = partial(np.array_repr, precision=precision) + else: + r_func = repr + + try: + r = r_func(a) + except Exception as exc: + r = f"[repr failed for <{type(a).__name__}>: {exc}]" + if r.count("\n") > 3: + r = "\n".join(r.splitlines()[:3]) + r += "..." + msg.append(f" {names[i]}: {r}") + return "\n".join(msg) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47e2ed13612ff6bb54e2b3c1f001e50eabe1d2ee Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/common.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c9340f5ffe8f3121c2850f74cdd1e2af7a58192 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/common.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_constructive.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_constructive.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d47566cf6b14cee371177543352e33488e9f4a81 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_constructive.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_coordinates.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_coordinates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dff0fe301c17edd17f4f76198a569d9e722a128f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_coordinates.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_coverage.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_coverage.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e1dcb993d155808653655b8c236e4a93a1babbc Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_coverage.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_creation.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_creation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e67837a182a57bee870b7addf0a060dc9f31334 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_creation.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_creation_indices.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_creation_indices.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07ff918ba7ad34f055b8f9d4d3ea615ff0ae16be Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_creation_indices.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_decorators.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_decorators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fa3ad007381430e765b1ecac5ea02cad1908c19 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_decorators.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_geometry.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_geometry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..607bdd72ef5dd8e947ad271a15656bea23920d5e Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_geometry.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_io.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4f2f42a054857edd7d023ee3c69741d3b0ab8ba Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_io.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_linear.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_linear.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d290e2e0704c3932df6aaed48ea2aadf1213607 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_linear.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_measurement.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_measurement.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..becef780426048fcab93683a4426bb44a308a267 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_measurement.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_misc.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_misc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d08a0a7dc02aaf56cd83f66a67af5fd566e6485 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_misc.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_plotting.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_plotting.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..990a68f26f99a027619660d5a3654712fa1c4022 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_plotting.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_predicates.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_predicates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95837dd95464393241e64a7f8c0f19fcdc8a1e72 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_predicates.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_ragged_array.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_ragged_array.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d056c85a7ef4191103479ef0d378de148ce3a842 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_ragged_array.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_set_operations.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_set_operations.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55300187d877246e11a8358b028a40545d193482 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_set_operations.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_strtree.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_strtree.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db840d8fabe7a7bdf40d144fef64f75204e9c6e5 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_strtree.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_testing.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_testing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56b5cf2a8fc55d61b1ae6e597a9e281bf4e5f338 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/__pycache__/test_testing.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/common.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/common.py new file mode 100644 index 0000000000000000000000000000000000000000..ca24b5562e9993294db577705e17675cbd6b207b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/common.py @@ -0,0 +1,285 @@ +import warnings +from contextlib import contextmanager + +import numpy as np + +import shapely + +point_polygon_testdata = ( + shapely.points(np.arange(6), np.arange(6)), + shapely.box(2, 2, 4, 4), +) +# XY +point = shapely.Point(2, 3) +line_string = shapely.LineString([(0, 0), (1, 0), (1, 1)]) +linear_ring = shapely.LinearRing([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) +polygon = shapely.Polygon([(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]) +polygon_with_hole = shapely.Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], +) +multi_point = shapely.MultiPoint([(0, 0), (1, 2)]) +multi_line_string = shapely.MultiLineString([[(0, 0), (1, 2)]]) +multi_polygon = shapely.multipolygons( + [ + [(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], + [(2.1, 2.1), (2.2, 2.1), (2.2, 2.2), (2.1, 2.2), (2.1, 2.1)], + ] +) +geometry_collection = shapely.GeometryCollection( + [shapely.Point(51, -1), shapely.LineString([(52, -1), (49, 2)])] +) +empty = shapely.from_wkt("GEOMETRYCOLLECTION EMPTY") +empty_point = shapely.from_wkt("POINT EMPTY") +empty_line_string = shapely.from_wkt("LINESTRING EMPTY") +empty_polygon = shapely.from_wkt("POLYGON EMPTY") +empty_multi_point = shapely.from_wkt("MULTIPOINT EMPTY") +empty_multi_line_string = shapely.from_wkt("MULTILINESTRING EMPTY") +empty_multi_polygon = shapely.from_wkt("MULTIPOLYGON EMPTY") +multi_point_empty = shapely.multipoints([empty_point]) +multi_line_string_empty = shapely.multilinestrings([empty_line_string]) +multi_polygon_empty = shapely.multipolygons([empty_polygon]) +geometry_collection_empty = shapely.geometrycollections([empty_line_string]) +# XYZ +point_z = shapely.Point(2, 3, 4) +line_string_z = shapely.LineString([(0, 0, 4), (1, 0, 4), (1, 1, 4)]) +linear_ring_z = shapely.LinearRing( + [(0, 0, 8), (1, 0, 7), (1, 1, 6), (0, 1, 9), (0, 0, 8)] +) +polygon_z = shapely.Polygon([(0, 0, 4), (2, 0, 4), (2, 2, 4), (0, 2, 4), (0, 0, 4)]) +polygon_with_hole_z = shapely.Polygon( + [(0, 0, 4), (0, 10, 4), (10, 10, 4), (10, 0, 4), (0, 0, 4)], + holes=[[(2, 2, 4), (2, 4, 4), (4, 4, 4), (4, 2, 4), (2, 2, 4)]], +) +multi_point_z = shapely.MultiPoint([(0, 0, 4), (1, 2, 4)]) +multi_line_string_z = shapely.MultiLineString([[(0, 0, 4), (1, 2, 4)]]) +multi_polygon_z = shapely.multipolygons( + [ + [(0, 0, 4), (1, 0, 4), (1, 1, 4), (0, 1, 4), (0, 0, 4)], + [(2.1, 2.1, 4), (2.2, 2.1, 4), (2.2, 2.2, 4), (2.1, 2.2, 4), (2.1, 2.1, 4)], + ] +) +geometry_collection_z = shapely.GeometryCollection([point_z, line_string_z]) +empty_geometry_collection_z = shapely.from_wkt("GEOMETRYCOLLECTION Z EMPTY") +empty_point_z = shapely.from_wkt("POINT Z EMPTY") +empty_line_string_z = shapely.from_wkt("LINESTRING Z EMPTY") +empty_polygon_z = shapely.from_wkt("POLYGON Z EMPTY") +empty_multi_point_z = shapely.from_wkt("MULTIPOINT Z EMPTY") +empty_multi_line_string_z = shapely.from_wkt("MULTILINESTRING Z EMPTY") +empty_multi_polygon_z = shapely.from_wkt("MULTIPOLYGON Z EMPTY") +multi_point_empty_z = shapely.multipoints([empty_point_z]) +multi_line_string_empty_z = shapely.multilinestrings([empty_line_string_z]) +multi_polygon_empty_z = shapely.multipolygons([empty_polygon_z]) +geometry_collection_empty_z = shapely.geometrycollections([empty_line_string_z]) +# XYM +point_m = shapely.from_wkt("POINT M (2 3 5)") +line_string_m = shapely.from_wkt("LINESTRING M (0 0 1, 1 0 2, 1 1 3)") +linear_ring_m = shapely.from_wkt("LINEARRING M (0 0 1, 1 0 2, 1 1 3, 0 1 2, 0 0 1)") +polygon_m = shapely.from_wkt("POLYGON M ((0 0 1, 2 0 2, 2 2 3, 0 2 2, 0 0 1))") +polygon_with_hole_m = shapely.from_wkt( + """POLYGON M ((0 0 1, 0 10 2, 10 10 3, 10 0 2, 0 0 1), + (2 2 6, 2 4 5, 4 4 4, 4 2 5, 2 2 6))""" +) +multi_point_m = shapely.from_wkt("MULTIPOINT M ((0 0 3), (1 2 5))") +multi_line_string_m = shapely.from_wkt("MULTILINESTRING M ((0 0 3, 1 2 5))") +multi_polygon_m = shapely.from_wkt( + """MULTIPOLYGON M (((0 0 1, 2 0 2, 2 2 3, 0 2 2, 0 0 1)), + ((2.1 2.1 1.1, 2.2 2.1 1.2, 2.2 2.2 1.3, 2.1 2.2 1.4, 2.1 2.1 1.1)))""" +) +geometry_collection_m = shapely.GeometryCollection([point_m, line_string_m]) +empty_geometry_collection_m = shapely.from_wkt("GEOMETRYCOLLECTION M EMPTY") +empty_point_m = shapely.from_wkt("POINT M EMPTY") +empty_line_string_m = shapely.from_wkt("LINESTRING M EMPTY") +empty_polygon_m = shapely.from_wkt("POLYGON M EMPTY") +empty_multi_point_m = shapely.from_wkt("MULTIPOINT M EMPTY") +empty_multi_line_string_m = shapely.from_wkt("MULTILINESTRING M EMPTY") +empty_multi_polygon_m = shapely.from_wkt("MULTIPOLYGON M EMPTY") +multi_point_empty_m = shapely.multipoints([empty_point_m]) +multi_line_string_empty_m = shapely.multilinestrings([empty_line_string_m]) +multi_polygon_empty_m = shapely.multipolygons([empty_polygon_m]) +geometry_collection_empty_m = shapely.geometrycollections([empty_line_string_m]) +# XYZM +point_zm = shapely.from_wkt("POINT ZM (2 3 4 5)") +line_string_zm = shapely.from_wkt("LINESTRING ZM (0 0 4 1, 1 0 4 2, 1 1 4 3)") +linear_ring_zm = shapely.from_wkt( + "LINEARRING ZM (0 0 1 8, 1 0 2 7, 1 1 3 6, 0 1 2 9, 0 0 1 8)" +) +polygon_zm = shapely.from_wkt( + "POLYGON ZM ((0 0 4 1, 2 0 4 2, 2 2 4 3, 0 2 4 2, 0 0 4 1))" +) +polygon_with_hole_zm = shapely.from_wkt( + """POLYGON ZM ((0 0 4 1, 0 10 4 2, 10 10 4 3, 10 0 4 2, 0 0 4 1), + (2 2 4 6, 2 4 4 5, 4 4 4 4, 4 2 4 5, 2 2 4 6))""" +) +multi_point_zm = shapely.from_wkt("MULTIPOINT ZM ((0 0 4 3), (1 2 4 5))") +multi_line_string_zm = shapely.from_wkt("MULTILINESTRING ZM ((0 0 4 3, 1 2 4 5))") +multi_polygon_zm = shapely.from_wkt( + """MULTIPOLYGON ZM (((0 0 4 1, 2 0 4 2, 2 2 4 3, 0 2 4 2, 0 0 4 1)), + ((2.1 2.1 4 1.1, 2.2 2.1 4 1.2, 2.2 2.2 4 1.3, 2.1 2.2 4 1.4, 2.1 2.1 4 1.1)))""" +) +geometry_collection_zm = shapely.GeometryCollection([point_zm, line_string_zm]) +empty_geometry_collection_zm = shapely.from_wkt("GEOMETRYCOLLECTION ZM EMPTY") +empty_point_zm = shapely.from_wkt("POINT ZM EMPTY") +empty_line_string_zm = shapely.from_wkt("LINESTRING ZM EMPTY") +empty_polygon_zm = shapely.from_wkt("POLYGON ZM EMPTY") +empty_multi_point_zm = shapely.from_wkt("MULTIPOINT ZM EMPTY") +empty_multi_line_string_zm = shapely.from_wkt("MULTILINESTRING ZM EMPTY") +empty_multi_polygon_zm = shapely.from_wkt("MULTIPOLYGON ZM EMPTY") +multi_point_empty_zm = shapely.multipoints([empty_point_zm]) +multi_line_string_empty_zm = shapely.multilinestrings([empty_line_string_zm]) +multi_polygon_empty_zm = shapely.multipolygons([empty_polygon_zm]) +geometry_collection_empty_zm = shapely.geometrycollections([empty_line_string_zm]) + +all_types = ( + point, + line_string, + linear_ring, + polygon, + polygon_with_hole, + multi_point, + multi_line_string, + multi_polygon, + geometry_collection, + empty, + empty_point, + empty_line_string, + empty_polygon, + empty_multi_point, + empty_multi_line_string, + empty_multi_polygon, + multi_point_empty, + multi_line_string_empty, + multi_polygon_empty, + geometry_collection_empty, +) + +all_types_z = ( + point_z, + line_string_z, + linear_ring_z, + polygon_z, + polygon_with_hole_z, + multi_point_z, + multi_line_string_z, + multi_polygon_z, + geometry_collection_z, + empty_geometry_collection_z, + empty_point_z, + empty_line_string_z, + empty_polygon_z, + empty_multi_point_z, + empty_multi_line_string_z, + empty_multi_polygon_z, + multi_point_empty_z, + multi_line_string_empty_z, + multi_polygon_empty_z, + geometry_collection_empty_z, +) +all_types_m = ( + point_m, + line_string_m, + linear_ring_m, + polygon_m, + polygon_with_hole_m, + multi_point_m, + multi_line_string_m, + multi_polygon_m, + geometry_collection_m, + empty_geometry_collection_m, + empty_point_m, + empty_line_string_m, + empty_polygon_m, + empty_multi_point_m, + empty_multi_line_string_m, + empty_multi_polygon_m, + multi_point_empty_m, + multi_line_string_empty_m, + multi_polygon_empty_m, + geometry_collection_empty_m, +) +all_types_zm = ( + point_zm, + line_string_zm, + linear_ring_zm, + polygon_zm, + polygon_with_hole_zm, + multi_point_zm, + multi_line_string_zm, + multi_polygon_zm, + geometry_collection_zm, + empty_geometry_collection_zm, + empty_point_zm, + empty_line_string_zm, + empty_polygon_zm, + empty_multi_point_zm, + empty_multi_line_string_zm, + empty_multi_polygon_zm, + multi_point_empty_zm, + multi_line_string_empty_zm, + multi_polygon_empty_zm, + geometry_collection_empty_zm, +) + + +@contextmanager +def ignore_invalid(condition=True): + if condition: + with np.errstate(invalid="ignore"): + yield + else: + yield + + +with ignore_invalid(): + line_string_nan = shapely.LineString([(np.nan, np.nan), (np.nan, np.nan)]) + + +@contextmanager +def ignore_warnings(geos_version, category): + if shapely.geos_version < geos_version: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=category) + yield + else: + yield + + +def equal_geometries_abnormally_yield_unequal(geom): + """Older GEOS versions have various issues with "equals".""" + if geom.is_empty and shapely.get_num_geometries(geom) > 0: + if shapely.geos_version < (3, 10, 0) and geom.geom_type == "GeometryCollection": + return True + if shapely.geos_version < (3, 13, 0) and geom.geom_type.startswith("Multi"): + return True + return False + + +class ArrayLike: + """ + Simple numpy Array like class that implements the + ufunc protocol. + """ + + def __init__(self, array): + self._array = np.asarray(array) + + def __len__(self): + return len(self._array) + + def __getitem(self, key): + return self._array[key] + + def __iter__(self): + return self._array.__iter__() + + def __array__(self): + return np.asarray(self._array) + + def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + if method == "__call__": + inputs = [ + arg._array if isinstance(arg, self.__class__) else arg for arg in inputs + ] + return self.__class__(ufunc(*inputs, **kwargs)) + else: + return NotImplemented diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdd919eea8d4fd1b654f1d7e231d0d6d7560f162 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_collection.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_collection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5d372dda6536d337534063b8d2fdb3a01166eff Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_collection.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_coords.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_coords.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5c5957efb6827268092a56c627b432d272ccefb Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_coords.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_decimal.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_decimal.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d60a091d6ab18421f21cdbbb1d178b19c1535adf Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_decimal.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_emptiness.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_emptiness.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5403051002fd8b045f6a40f4ef16cc69dd43cf6 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_emptiness.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_equality.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_equality.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a56e428a9fe2ca387bb76541fab99d6d0d7f2e57 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_equality.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_format.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_format.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62b8f9a355429564ae7d4a5b762d0a6826992ee3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_format.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_geometry_base.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_geometry_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82fc2c249450e09846b936d2dcdb1a16447f645b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_geometry_base.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_hash.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_hash.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ba2b6e728ac3265d6f2f40cab7f9e160d266729 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_hash.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_linestring.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_linestring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..813de1f4ec33e39298ec0797d73fd37758a9e822 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_linestring.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multi.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae360e90c454ea0fb70ddb556f0c039f63cd2570 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multi.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multilinestring.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multilinestring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1530494908d1435a09222f5806f26550b103adac Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multilinestring.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multipoint.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multipoint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a9ec26bb802a5524e6d8f86e84fc71d18f84549 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multipoint.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multipolygon.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multipolygon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aebe1f88924dddcdffa0f28cc23a43d2c72177c6 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_multipolygon.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_point.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_point.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebd5042948e5e637794119e50ee18a3e5ba6aa95 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_point.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_polygon.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_polygon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f09d66f4961ac24fb32fd9cb950d4ab57905b104 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/__pycache__/test_polygon.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_collection.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..68dc3408602e5724911b9bb58d732b395db0d036 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_collection.py @@ -0,0 +1,95 @@ +import numpy as np +import pytest + +import shapely +from shapely import GeometryCollection, LineString, Point, wkt +from shapely.geometry import shape + + +@pytest.fixture() +def geometrycollection_geojson(): + return { + "type": "GeometryCollection", + "geometries": [ + {"type": "Point", "coordinates": (0, 3, 0)}, + {"type": "LineString", "coordinates": ((2, 0), (1, 0))}, + ], + } + + +@pytest.mark.parametrize( + "geom", + [ + GeometryCollection(), + GeometryCollection([]), + shape({"type": "GeometryCollection", "geometries": []}), + wkt.loads("GEOMETRYCOLLECTION EMPTY"), + ], +) +def test_empty(geom): + assert geom.geom_type == "GeometryCollection" + assert geom.is_empty + assert len(geom.geoms) == 0 + assert list(geom.geoms) == [] + + +def test_empty_subgeoms(): + geom = GeometryCollection([Point(), LineString()]) + assert geom.geom_type == "GeometryCollection" + assert geom.is_empty + assert len(geom.geoms) == 2 + parts = list(geom.geoms) + if shapely.geos_version < (3, 9, 0): + # the accessed empty 2D point has a 3D coordseq on GEOS 3.8 + parts[0] = shapely.force_2d(parts[0]) + assert parts == [Point(), LineString()] + + +def test_child_with_deleted_parent(): + # test that we can remove a collection while keeping + # children around + a = LineString([(0, 0), (1, 1), (1, 2), (2, 2)]) + b = LineString([(0, 0), (1, 1), (2, 1), (2, 2)]) + collection = a.intersection(b) + + child = collection.geoms[0] + # delete parent of child + del collection + + # access geometry, this should not seg fault as 1.2.15 did + assert child.wkt is not None + + +def test_from_numpy_array(): + geoms = np.array([Point(0, 0), LineString([(1, 1), (2, 2)])]) + geom = GeometryCollection(geoms) + assert len(geom.geoms) == 2 + np.testing.assert_array_equal(geoms, geom.geoms) + + +def test_from_geojson(geometrycollection_geojson): + geom = shape(geometrycollection_geojson) + assert geom.geom_type == "GeometryCollection" + assert len(geom.geoms) == 2 + + geom_types = [g.geom_type for g in geom.geoms] + assert "Point" in geom_types + assert "LineString" in geom_types + + +def test_geointerface(geometrycollection_geojson): + geom = shape(geometrycollection_geojson) + assert geom.__geo_interface__ == geometrycollection_geojson + + +def test_len_raises(geometrycollection_geojson): + geom = shape(geometrycollection_geojson) + with pytest.raises(TypeError): + len(geom) + + +def test_numpy_object_array(): + geom = GeometryCollection([LineString([(0, 0), (1, 1)])]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_coords.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_coords.py new file mode 100644 index 0000000000000000000000000000000000000000..113200570de0c9a16e1479810170406129f1e5a8 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_coords.py @@ -0,0 +1,127 @@ +import numpy as np +import pytest + +from shapely import LineString, geos_version +from shapely.tests.common import ( + line_string, + line_string_m, + line_string_z, + line_string_zm, + point, + point_m, + point_z, + point_zm, +) + + +class TestCoords: + """ + Shapely assumes contiguous C-order float64 data for internal ops. + Data should be converted to contiguous float64 if numpy exists. + c9a0707 broke this a little bit. + """ + + def test_data_promotion(self): + coords = np.array([[12, 34], [56, 78]], dtype=np.float32) + processed_coords = np.array(LineString(coords).coords) + + assert coords.tolist() == processed_coords.tolist() + + def test_data_destriding(self): + coords = np.array([[12, 34], [56, 78]], dtype=np.float32) + + # Easy way to introduce striding: reverse list order + processed_coords = np.array(LineString(coords[::-1]).coords) + + assert coords[::-1].tolist() == processed_coords.tolist() + + +class TestCoordsGetItem: + def test_index_coords(self): + c = [(float(x), float(-x)) for x in range(4)] + g = LineString(c) + for i in range(-4, 4): + assert g.coords[i] == c[i] + with pytest.raises(IndexError): + g.coords[4] + with pytest.raises(IndexError): + g.coords[-5] + + def test_index_coords_z(self): + c = [(float(x), float(-x), float(x * 2)) for x in range(4)] + g = LineString(c) + for i in range(-4, 4): + assert g.coords[i] == c[i] + with pytest.raises(IndexError): + g.coords[4] + with pytest.raises(IndexError): + g.coords[-5] + + def test_index_coords_misc(self): + g = LineString() # empty + with pytest.raises(IndexError): + g.coords[0] + with pytest.raises(TypeError): + g.coords[0.0] + + def test_slice_coords(self): + c = [(float(x), float(-x)) for x in range(4)] + g = LineString(c) + assert g.coords[1:] == c[1:] + assert g.coords[:-1] == c[:-1] + assert g.coords[::-1] == c[::-1] + assert g.coords[::2] == c[::2] + assert g.coords[:4] == c[:4] + assert g.coords[4:] == c[4:] == [] + + def test_slice_coords_z(self): + c = [(float(x), float(-x), float(x * 2)) for x in range(4)] + g = LineString(c) + assert g.coords[1:] == c[1:] + assert g.coords[:-1] == c[:-1] + assert g.coords[::-1] == c[::-1] + assert g.coords[::2] == c[::2] + assert g.coords[:4] == c[:4] + assert g.coords[4:] == c[4:] == [] + + +class TestXY: + """New geometry/coordseq method 'xy' makes numpy interop easier""" + + def test_arrays(self): + x, y = LineString([(0, 0), (1, 1)]).xy + assert len(x) == 2 + assert list(x) == [0.0, 1.0] + assert len(y) == 2 + assert list(y) == [0.0, 1.0] + + +@pytest.mark.parametrize("geom", [point, point_z, line_string, line_string_z]) +def test_coords_array_copy(geom): + """Test CoordinateSequence.__array__ method.""" + coord_seq = geom.coords + assert np.array(coord_seq) is not np.array(coord_seq) + assert np.array(coord_seq, copy=True) is not np.array(coord_seq, copy=True) + + # Behaviour of copy=False is different between NumPy 1.x and 2.x + if int(np.version.short_version.split(".", 1)[0]) >= 2: + with pytest.raises(ValueError, match="A copy is always created"): + np.array(coord_seq, copy=False) + else: + assert np.array(coord_seq, copy=False) is np.array(coord_seq, copy=False) + + +@pytest.mark.skipif(geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_coords_with_m(): + assert point_m.coords[:] == [(2.0, 3.0, 5.0)] + assert point_zm.coords[:] == [(2.0, 3.0, 4.0, 5.0)] + assert line_string_m.coords[:] == [ + (0.0, 0.0, 1.0), + (1.0, 0.0, 2.0), + (1.0, 1.0, 3.0), + ] + assert line_string_zm.coords[:] == [ + (0.0, 0.0, 4.0, 1.0), + (1.0, 0.0, 4.0, 2.0), + (1.0, 1.0, 4.0, 3.0), + ] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_decimal.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_decimal.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae805ae0d759baf3897907b22fad0f0dd6aea29 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_decimal.py @@ -0,0 +1,117 @@ +from decimal import Decimal + +import pytest + +from shapely import ( + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) + +items2d = [ + [(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)], + [(60.0, 80.0), (80.0, 80.0), (70.0, 60.0), (60.0, 80.0)], +] + +items2d_mixed = [ + [ + (Decimal("0.0"), Decimal("0.0")), + (Decimal("70.0"), 120.0), + (140.0, Decimal("0.0")), + (0.0, 0.0), + ], + [ + (Decimal("60.0"), Decimal("80.0")), + (Decimal("80.0"), 80.0), + (70.0, Decimal("60.0")), + (60.0, 80.0), + ], +] + +items2d_decimal = [ + [ + (Decimal("0.0"), Decimal("0.0")), + (Decimal("70.0"), Decimal("120.0")), + (Decimal("140.0"), Decimal("0.0")), + (Decimal("0.0"), Decimal("0.0")), + ], + [ + (Decimal("60.0"), Decimal("80.0")), + (Decimal("80.0"), Decimal("80.0")), + (Decimal("70.0"), Decimal("60.0")), + (Decimal("60.0"), Decimal("80.0")), + ], +] + +items3d = [ + [(0.0, 0.0, 1), (70.0, 120.0, 2), (140.0, 0.0, 3), (0.0, 0.0, 1)], + [(60.0, 80.0, 1), (80.0, 80.0, 2), (70.0, 60.0, 3), (60.0, 80.0, 1)], +] + +items3d_mixed = [ + [ + (Decimal("0.0"), Decimal("0.0"), Decimal(1)), + (Decimal("70.0"), 120.0, Decimal(2)), + (140.0, Decimal("0.0"), 3), + (0.0, 0.0, 1), + ], + [ + (Decimal("60.0"), Decimal("80.0"), Decimal(1)), + (Decimal("80.0"), 80.0, 2), + (70.0, Decimal("60.0"), Decimal(3)), + (60.0, 80.0, 1), + ], +] + +items3d_decimal = [ + [ + (Decimal("0.0"), Decimal("0.0"), Decimal(1)), + (Decimal("70.0"), Decimal("120.0"), Decimal(2)), + (Decimal("140.0"), Decimal("0.0"), Decimal(3)), + (Decimal("0.0"), Decimal("0.0"), Decimal(1)), + ], + [ + (Decimal("60.0"), Decimal("80.0"), Decimal(1)), + (Decimal("80.0"), Decimal("80.0"), Decimal(2)), + (Decimal("70.0"), Decimal("60.0"), Decimal(3)), + (Decimal("60.0"), Decimal("80.0"), Decimal(1)), + ], +] + +all_geoms = [ + [ + Point(items[0][0]), + Point(*items[0][0]), + MultiPoint(items[0]), + LinearRing(items[0]), + LineString(items[0]), + MultiLineString(items), + Polygon(items[0]), + MultiPolygon( + [ + Polygon(items[1]), + Polygon(items[0], holes=items[1:]), + ] + ), + GeometryCollection([Point(items[0][0]), Polygon(items[0])]), + ] + for items in [ + items2d, + items2d_mixed, + items2d_decimal, + items3d, + items3d_mixed, + items3d_decimal, + ] +] + + +@pytest.mark.parametrize("geoms", list(zip(*all_geoms))) +def test_decimal(geoms): + assert geoms[0] == geoms[1] == geoms[2] + assert geoms[3] == geoms[4] == geoms[5] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_emptiness.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_emptiness.py new file mode 100644 index 0000000000000000000000000000000000000000..005b2b8ecb88f5be4c72f63ce5737bc8a9bd9a68 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_emptiness.py @@ -0,0 +1,98 @@ +import math + +import numpy as np +import pytest + +from shapely import ( + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.geometry import mapping, shape +from shapely.geometry.base import BaseGeometry, EmptyGeometry + + +def empty_generator(): + return iter([]) + + +class TestEmptiness: + def test_empty_class(self): + with pytest.warns(FutureWarning): + g = EmptyGeometry() + assert g.is_empty + + def test_empty_base(self): + with pytest.warns(FutureWarning): + g = BaseGeometry() + assert g.is_empty + + def test_empty_point(self): + assert Point().is_empty + + def test_empty_multipoint(self): + assert MultiPoint().is_empty + + def test_empty_geometry_collection(self): + assert GeometryCollection().is_empty + + def test_empty_linestring(self): + assert LineString().is_empty + assert LineString(None).is_empty + assert LineString([]).is_empty + assert LineString(empty_generator()).is_empty + + def test_empty_multilinestring(self): + assert MultiLineString([]).is_empty + + def test_empty_polygon(self): + assert Polygon().is_empty + assert Polygon(None).is_empty + assert Polygon([]).is_empty + assert Polygon(empty_generator()).is_empty + + def test_empty_multipolygon(self): + assert MultiPolygon([]).is_empty + + def test_empty_linear_ring(self): + assert LinearRing().is_empty + assert LinearRing(None).is_empty + assert LinearRing([]).is_empty + assert LinearRing(empty_generator()).is_empty + + +def test_numpy_object_array(): + geoms = [Point(), GeometryCollection()] + arr = np.empty(2, object) + arr[:] = geoms + + +def test_shape_empty(): + empty_mp = MultiPolygon() + empty_json = mapping(empty_mp) + empty_shape = shape(empty_json) + assert empty_shape.is_empty + + +@pytest.mark.parametrize( + "geom", + [ + Point(), + LineString(), + Polygon(), + MultiPoint(), + MultiLineString(), + MultiPolygon(), + GeometryCollection(), + LinearRing(), + ], +) +def test_empty_geometry_bounds(geom): + """The bounds of an empty geometry is a tuple of NaNs""" + assert len(geom.bounds) == 4 + assert all(math.isnan(v) for v in geom.bounds) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_equality.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_equality.py new file mode 100644 index 0000000000000000000000000000000000000000..26704a1b9299030d743c8e493b133cd1320e9e86 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_equality.py @@ -0,0 +1,284 @@ +import numpy as np +import pytest + +import shapely +from shapely import LinearRing, LineString, MultiLineString, Point, Polygon +from shapely.tests.common import all_types, all_types_z, empty_point, ignore_invalid + +all_non_empty_types = np.array(all_types + all_types_z)[ + ~shapely.is_empty(all_types + all_types_z) +] + + +# TODO add all_types_m and all_types_zm once tranform supports M coordinates +@pytest.mark.parametrize("geom", all_types + all_types_z) +def test_equality(geom): + assert geom == geom # noqa: PLR0124 + transformed = shapely.transform(geom, lambda x: x, include_z=True) + if ( + shapely.geos_version < (3, 9, 0) + and isinstance(geom, Point) + and geom.is_empty + and not geom.has_z + ): + # the transformed empty 2D point has become 3D on GEOS 3.8 + transformed = shapely.force_2d(geom) + assert geom == transformed + assert not (geom != transformed) + + +@pytest.mark.parametrize( + "left, right", + # automated test cases with transformed coordinate values + [(geom, shapely.transform(geom, lambda x: x + 1)) for geom in all_non_empty_types] + + [ + # (slightly) different coordinate values + (LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 2)])), + (LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1 + 1e-12)])), + # different coordinate order + (LineString([(0, 0), (1, 1)]), LineString([(1, 1), (0, 0)])), + # different number of coordinates (but spatially equal) + (LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1), (1, 1)])), + (LineString([(0, 0), (1, 1)]), LineString([(0, 0), (0.5, 0.5), (1, 1)])), + # different order of sub-geometries + ( + MultiLineString([[(1, 1), (2, 2)], [(2, 2), (3, 3)]]), + MultiLineString([[(2, 2), (3, 3)], [(1, 1), (2, 2)]]), + ), + # M coordinates (don't work yet with automated cases) + pytest.param( + shapely.from_wkt("POINT M (0 0 0)"), + shapely.from_wkt("POINT M (0 0 1)"), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + pytest.param( + shapely.from_wkt("POINT ZM (0 0 0 0)"), + shapely.from_wkt("POINT ZM (0 0 0 1)"), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + ], +) +def test_equality_false(left, right): + assert left != right + assert not (left == right) + + +with ignore_invalid(): + cases1 = [ + (LineString([(0, 1), (2, np.nan)]), LineString([(0, 1), (2, np.nan)])), + ( + LineString([(0, 1), (np.nan, np.nan)]), + LineString([(0, 1), (np.nan, np.nan)]), + ), + (LineString([(np.nan, 1), (2, 3)]), LineString([(np.nan, 1), (2, 3)])), + (LineString([(0, np.nan), (2, 3)]), LineString([(0, np.nan), (2, 3)])), + ( + LineString([(np.nan, np.nan), (np.nan, np.nan)]), + LineString([(np.nan, np.nan), (np.nan, np.nan)]), + ), + # NaN as explicit Z coordinate + # TODO: if first z is NaN -> considered as 2D -> tested below explicitly + # ( + # LineString([(0, 1, np.nan), (2, 3, np.nan)]), + # LineString([(0, 1, np.nan), (2, 3, np.nan)]), + # ), + ( + LineString([(0, 1, 2), (2, 3, np.nan)]), + LineString([(0, 1, 2), (2, 3, np.nan)]), + ), + # ( + # LineString([(0, 1, np.nan), (2, 3, 4)]), + # LineString([(0, 1, np.nan), (2, 3, 4)]), + # ), + ] + + +@pytest.mark.parametrize("left, right", cases1) +def test_equality_with_nan(left, right): + assert left == right + assert not (left != right) + + +with ignore_invalid(): + cases2 = [ + ( + LineString([(0, 1, np.nan), (2, 3, np.nan)]), + LineString([(0, 1, np.nan), (2, 3, np.nan)]), + ), + ( + LineString([(0, 1, np.nan), (2, 3, 4)]), + LineString([(0, 1, np.nan), (2, 3, 4)]), + ), + ] + + +@pytest.mark.parametrize("left, right", cases2) +def test_equality_with_nan_z(left, right): + assert left == right + assert not (left != right) + + +with ignore_invalid(): + cases3 = [ + (LineString([(0, np.nan), (2, 3)]), LineString([(0, 1), (2, 3)])), + (LineString([(0, 1), (2, np.nan)]), LineString([(0, 1), (2, 3)])), + (LineString([(0, 1, np.nan), (2, 3, 4)]), LineString([(0, 1, 2), (2, 3, 4)])), + (LineString([(0, 1, 2), (2, 3, np.nan)]), LineString([(0, 1, 2), (2, 3, 4)])), + pytest.param( + shapely.from_wkt("POINT M (0 0 0)"), + shapely.from_wkt("POINT M (0 0 NaN)"), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + pytest.param( + shapely.from_wkt("POINT ZM (0 0 0 0)"), + shapely.from_wkt("POINT ZM (0 0 0 NaN)"), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + ] + + +@pytest.mark.parametrize("left, right", cases3) +def test_equality_with_nan_false(left, right): + assert left != right + + +def test_equality_with_nan_z_false(): + with ignore_invalid(): + left = LineString([(0, 1, np.nan), (2, 3, np.nan)]) + right = LineString([(0, 1, np.nan), (2, 3, 4)]) + + if shapely.geos_version < (3, 10, 0): + # GEOS <= 3.9 fill the NaN with 0, so the z dimension is different + assert left != right + elif shapely.geos_version < (3, 12, 0): + # GEOS 3.10-3.11 ignore NaN for Z also when explicitly created with 3D + # and so the geometries are considered as 2D (and thus z dimension is ignored) + assert left == right + else: + assert left != right + + +def test_equality_z(): + # different dimensionality + geom1 = Point(0, 1) + geom2 = Point(0, 1, 0) + assert geom1 != geom2 + + # different dimensionality with NaN z + geom2 = Point(0, 1, np.nan) + if shapely.geos_version < (3, 12, 0): + # GEOS 3.10-3.11 ignore NaN for Z also when explicitly created with 3D + # and so the geometries are considered as 2D (and thus z dimension is ignored) + assert geom1 == geom2 + else: + assert geom1 != geom2 + + +def test_equality_exact_type(): + # geometries with different type but same coord seq are not equal + geom1 = LineString([(0, 0), (1, 1), (0, 1), (0, 0)]) + geom2 = LinearRing([(0, 0), (1, 1), (0, 1), (0, 0)]) + geom3 = Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]) + assert geom1 != geom2 + assert geom1 != geom3 + assert geom2 != geom3 + + # empty with different type + geom1 = shapely.from_wkt("POINT EMPTY") + geom2 = shapely.from_wkt("LINESTRING EMPTY") + assert geom1 != geom2 + + +def test_equality_polygon(): + # different exterior rings + geom1 = shapely.from_wkt("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))") + geom2 = shapely.from_wkt("POLYGON ((0 0, 10 0, 10 10, 0 15, 0 0))") + assert geom1 != geom2 + + # different number of holes + geom1 = shapely.from_wkt( + "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1))" + ) + geom2 = shapely.from_wkt( + "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1), " + "(3 3, 4 3, 4 4, 3 3))" + ) + assert geom1 != geom2 + + # different order of holes + geom1 = shapely.from_wkt( + "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (3 3, 4 3, 4 4, 3 3), " + "(1 1, 2 1, 2 2, 1 1))" + ) + geom2 = shapely.from_wkt( + "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1), " + "(3 3, 4 3, 4 4, 3 3))" + ) + assert geom1 != geom2 + + +@pytest.mark.parametrize("geom", all_types) +def test_comparison_notimplemented(geom): + # comparing to a non-geometry class should return NotImplemented in __eq__ + # to ensure proper delegation to other (eg to ensure comparison of scalar + # with array works) + # https://github.com/shapely/shapely/issues/1056 + assert geom.__eq__(1) is NotImplemented + + # with array + arr = np.array([geom, geom], dtype=object) + + result = arr == geom + assert isinstance(result, np.ndarray) + assert result.all() + + result = geom == arr + assert isinstance(result, np.ndarray) + assert result.all() + + result = arr != geom + assert isinstance(result, np.ndarray) + assert not result.any() + + result = geom != arr + assert isinstance(result, np.ndarray) + assert not result.any() + + +def test_comparison_not_supported(): + geom1 = Point(1, 1) + geom2 = Point(2, 2) + + with pytest.raises(TypeError, match="not supported between instances"): + assert geom1 > geom2 + + with pytest.raises(TypeError, match="not supported between instances"): + assert geom1 < geom2 + + with pytest.raises(TypeError, match="not supported between instances"): + assert geom1 >= geom2 + + with pytest.raises(TypeError, match="not supported between instances"): + assert geom1 <= geom2 + + +@pytest.mark.parametrize( + "geom", all_types + (shapely.points(np.nan, np.nan), empty_point) +) +def test_hash_same_equal(geom): + hash1 = hash(geom) + hash2 = hash(shapely.transform(geom, lambda x: x)) + assert hash1 == hash2, geom + + +@pytest.mark.parametrize("geom", all_non_empty_types) +def test_hash_same_not_equal(geom): + assert hash(geom) != hash(shapely.transform(geom, lambda x: x + 1)) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_format.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..36c0fa38654407ef96884e0fd8ef17fb8997e06c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_format.py @@ -0,0 +1,118 @@ +import pytest + +from shapely import Point, Polygon, geos_version + + +def test_format_invalid(): + # check invalid spec formats + pt = Point(1, 2) + test_list = [ + ("5G", ValueError, "invalid format specifier"), + (".f", ValueError, "invalid format specifier"), + ("0.2e", ValueError, "invalid format specifier"), + (".1x", ValueError, "hex representation does not specify precision"), + ] + for format_spec, err, match in test_list: + with pytest.raises(err, match=match): + format(pt, format_spec) + + +def get_tst_format_point_params(): + xy1 = (0.12345678901234567, 1.2345678901234567e10) + xy2 = (-169.910918, -18.997564) + xyz3 = (630084, 4833438, 76) + test_list = [ + (".0f", xy1, "POINT (0 12345678901)", True), + (".1f", xy1, "POINT (0.1 12345678901.2)", True), + ("0.2f", xy2, "POINT (-169.91 -19.00)", True), + (".3F", (float("inf"), -float("inf")), "POINT (INF -INF)", True), + ] + if geos_version < (3, 10, 0): + # 'g' format varies depending on GEOS version + test_list += [ + (".1g", xy1, "POINT (0.1 1e+10)", True), + (".6G", xy1, "POINT (0.123457 1.23457E+10)", True), + ("0.12g", xy1, "POINT (0.123456789012 12345678901.2)", True), + ("0.4g", xy2, "POINT (-169.9 -19)", True), + ] + else: + test_list += [ + (".1g", xy1, "POINT (0.1 12345678901.2)", False), + (".6G", xy1, "POINT (0.123457 12345678901.234568)", False), + ("0.12g", xy1, "POINT (0.123456789012 12345678901.234568)", False), + ("g", xy2, "POINT (-169.910918 -18.997564)", False), + ("0.2g", xy2, "POINT (-169.91 -19)", False), + ] + # without precisions test GEOS rounding_precision=-1; different than Python + test_list += [ + ("f", (1, 2), f"POINT ({1:.16f} {2:.16f})", False), + ("F", xyz3, "POINT Z ({:.16f} {:.16f} {:.16f})".format(*xyz3), False), + ("g", xyz3, "POINT Z (630084 4833438 76)", False), + ] + return test_list + + +@pytest.mark.parametrize( + "format_spec, coords, expt_wkt, same_python_float", get_tst_format_point_params() +) +def test_format_point(format_spec, coords, expt_wkt, same_python_float): + pt = Point(*coords) + # basic checks + assert f"{pt}" == pt.wkt + assert format(pt, "") == pt.wkt + assert format(pt, "x") == pt.wkb_hex.lower() + assert format(pt, "X") == pt.wkb_hex + # check formatted WKT to expected + assert format(pt, format_spec) == expt_wkt, format_spec + # check Python's format consistency + text_coords = expt_wkt[expt_wkt.index("(") + 1 : expt_wkt.index(")")] + is_same = [] + for coord, expt_coord in zip(coords, text_coords.split()): + py_fmt_float = format(float(coord), format_spec) + if same_python_float: + assert py_fmt_float == expt_coord, format_spec + else: + is_same.append(py_fmt_float == expt_coord) + if not same_python_float: + assert not all(is_same), f"{format_spec!r} with {expt_wkt}" + + +def test_format_polygon(): + # check basic cases + poly = Point(0, 0).buffer(10, quad_segs=2) + assert f"{poly}" == poly.wkt + assert format(poly, "") == poly.wkt + assert format(poly, "x") == poly.wkb_hex.lower() + assert format(poly, "X") == poly.wkb_hex + + # Use f-strings with extra characters and rounding precision + if geos_version < (3, 13, 0): + assert f"<{poly:.2f}>" == ( + "" + ) + else: + assert f"<{poly:.2f}>" == ( + "" + ) + + # 'g' format varies depending on GEOS version + if geos_version < (3, 10, 0): + assert f"{poly:.2G}" == ( + "POLYGON ((10 0, 7.1 -7.1, 1.6E-14 -10, -7.1 -7.1, " + "-10 -3.2E-14, -7.1 7.1, -4.6E-14 10, 7.1 7.1, 10 0))" + ) + else: + assert f"{poly:.2G}" == ( + "POLYGON ((10 0, 7.07 -7.07, 0 -10, -7.07 -7.07, " + "-10 0, -7.07 7.07, 0 10, 7.07 7.07, 10 0))" + ) + + # check empty + empty = Polygon() + assert f"{empty}" == "POLYGON EMPTY" + assert format(empty, "") == empty.wkt + assert format(empty, ".2G") == empty.wkt + assert format(empty, "x") == empty.wkb_hex.lower() + assert format(empty, "X") == empty.wkb_hex diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_geometry_base.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_geometry_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0314ccb43dd3b4c8cfff74ad4e6987a8fd9241b2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_geometry_base.py @@ -0,0 +1,369 @@ +import platform +import weakref + +import numpy as np +import pytest + +import shapely +from shapely import ( + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.errors import ShapelyDeprecationWarning +from shapely.testing import assert_geometries_equal + + +def test_polygon(): + assert bool(Polygon()) is False + + +def test_linestring(): + assert bool(LineString()) is False + + +def test_point(): + assert bool(Point()) is False + + +def test_geometry_collection(): + assert bool(GeometryCollection()) is False + + +geometries_all_types = [ + Point(1, 1), + LinearRing([(0, 0), (1, 1), (0, 1), (0, 0)]), + LineString([(0, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]), + MultiPoint([(1, 1)]), + MultiLineString([[(0, 0), (1, 1), (0, 1), (0, 0)]]), + MultiPolygon([Polygon([(0, 0), (1, 1), (0, 1), (0, 0)])]), + GeometryCollection([Point(1, 1)]), +] + + +@pytest.mark.skipif( + platform.python_implementation() == "PyPy", + reason="Setting custom attributes doesn't fail on PyPy", +) +@pytest.mark.parametrize("geom", geometries_all_types) +def test_setattr_disallowed(geom): + with pytest.raises(AttributeError): + geom.name = "test" + + +@pytest.mark.parametrize("geom", geometries_all_types) +def test_weakrefable(geom): + _ = weakref.ref(geom) + + +def test_base_class_not_callable(): + with pytest.raises(TypeError): + shapely.Geometry("POINT (1 1)") + + +def test_GeometryType_deprecated(): + geom = Point(1, 1) + + with pytest.warns(ShapelyDeprecationWarning): + geom_type = geom.geometryType() + + assert geom_type == geom.geom_type + + +def test_type_deprecated(): + geom = Point(1, 1) + + with pytest.warns(ShapelyDeprecationWarning): + geom_type = geom.type + + assert geom_type == geom.geom_type + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_segmentize(): + line = LineString([(0, 0), (0, 10)]) + result = line.segmentize(max_segment_length=5) + assert result.equals(LineString([(0, 0), (0, 5), (0, 10)])) + + +def test_reverse(): + coords = [(0, 0), (1, 2)] + line = LineString(coords) + result = line.reverse() + assert result.coords[:] == coords[::-1] + + +@pytest.mark.parametrize( + "op", ["union", "intersection", "difference", "symmetric_difference"] +) +@pytest.mark.parametrize("grid_size", [0, 1, 2]) +def test_binary_op_grid_size(op, grid_size): + geom1 = shapely.box(0, 0, 2.5, 2.5) + geom2 = shapely.box(2, 2, 3, 3) + + result = getattr(geom1, op)(geom2, grid_size=grid_size) + expected = getattr(shapely, op)(geom1, geom2, grid_size=grid_size) + assert result == expected + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_dwithin(): + point = Point(1, 1) + line = LineString([(0, 0), (0, 10)]) + assert point.dwithin(line, 0.5) is False + assert point.dwithin(line, 1.5) is True + + +def test_contains_properly(): + polygon = Polygon([(0, 0), (10, 10), (10, -10)]) + line = LineString([(0, 0), (10, 0)]) + assert polygon.contains_properly(line) is False + assert polygon.contains(line) is True + + +@pytest.mark.parametrize( + "op", ["convex_hull", "envelope", "oriented_envelope", "minimum_rotated_rectangle"] +) +def test_constructive_properties(op): + geom = LineString([(0, 0), (0, 10), (10, 10)]) + result = getattr(geom, op) + expected = getattr(shapely, op)(geom) + assert result == expected + + +@pytest.mark.parametrize( + "op", + [ + "crosses", + "contains", + "contains_properly", + "covered_by", + "covers", + "disjoint", + "equals", + "intersects", + "overlaps", + "touches", + "within", + ], +) +def test_array_argument_binary_predicates(op): + polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + points = shapely.points([(0, 0), (0.5, 0.5), (1, 1)]) + + result = getattr(polygon, op)(points) + assert isinstance(result, np.ndarray) + expected = np.array([getattr(polygon, op)(p) for p in points], dtype=bool) + np.testing.assert_array_equal(result, expected) + + # check scalar + result = getattr(polygon, op)(points[0]) + assert type(result) is bool + + +@pytest.mark.parametrize( + "op, kwargs", + [ + pytest.param( + "dwithin", + dict(distance=0.5), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10" + ), + ), + ("equals_exact", dict(tolerance=0.01)), + ("relate_pattern", dict(pattern="T*F**F***")), + ], +) +def test_array_argument_binary_predicates2(op, kwargs): + polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + points = shapely.points([(0, 0), (0.5, 0.5), (1, 1)]) + + result = getattr(polygon, op)(points, **kwargs) + assert isinstance(result, np.ndarray) + expected = np.array([getattr(polygon, op)(p, **kwargs) for p in points], dtype=bool) + np.testing.assert_array_equal(result, expected) + + # check scalar + result = getattr(polygon, op)(points[0], **kwargs) + assert type(result) is bool + + +@pytest.mark.parametrize( + "op", + [ + "difference", + "intersection", + "symmetric_difference", + "union", + ], +) +def test_array_argument_binary_geo(op): + box = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + polygons = shapely.buffer(shapely.points([(0, 0), (0.5, 0.5), (1, 1)]), 0.5) + + result = getattr(box, op)(polygons) + assert isinstance(result, np.ndarray) + expected = np.array([getattr(box, op)(g) for g in polygons], dtype=object) + assert_geometries_equal(result, expected) + + # check scalar + result = getattr(box, op)(polygons[0]) + assert isinstance(result, (Polygon, MultiPolygon)) + + +@pytest.mark.parametrize("op", ["distance", "hausdorff_distance"]) +def test_array_argument_float(op): + polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + points = shapely.points([(0, 0), (0.5, 0.5), (1, 1)]) + + result = getattr(polygon, op)(points) + assert isinstance(result, np.ndarray) + expected = np.array([getattr(polygon, op)(p) for p in points], dtype="float64") + np.testing.assert_array_equal(result, expected) + + # check scalar + result = getattr(polygon, op)(points[0]) + assert type(result) is float + + +@pytest.mark.parametrize("op", ["line_interpolate_point", "interpolate"]) +def test_array_argument_linear_point(op): + line = LineString([(0, 0), (0, 1), (1, 1)]) + distances = np.array([0, 0.5, 1]) + + result = getattr(line, op)(distances) + assert isinstance(result, np.ndarray) + expected = np.array( + [line.line_interpolate_point(d) for d in distances], dtype=object + ) + assert_geometries_equal(result, expected) + + # check scalar + result = getattr(line, op)(distances[0]) + assert isinstance(result, Point) + + +@pytest.mark.parametrize("op", ["line_locate_point", "project"]) +def test_array_argument_linear_float(op): + line = LineString([(0, 0), (0, 1), (1, 1)]) + points = shapely.points([(0, 0), (0.5, 0.5), (1, 1)]) + + result = getattr(line, op)(points) + assert isinstance(result, np.ndarray) + expected = np.array([line.line_locate_point(p) for p in points], dtype="float64") + np.testing.assert_array_equal(result, expected) + + # check scalar + result = getattr(line, op)(points[0]) + assert type(result) is float + + +def test_array_argument_buffer(): + point = Point(1, 1) + distances = np.array([0, 0.5, 1]) + + result = point.buffer(distances) + assert isinstance(result, np.ndarray) + expected = np.array([point.buffer(d) for d in distances], dtype=object) + assert_geometries_equal(result, expected) + + # check scalar + result = point.buffer(distances[0]) + assert isinstance(result, Polygon) + + +def test_buffer_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `cap_style` for `buffer` is deprecated" + ): + point.buffer(1.0, 8, "round") + with pytest.deprecated_call( + match="positional arguments `cap_style` and `join_style` " + "for `buffer` are deprecated" + ): + point.buffer(1.0, 8, "round", "round") + with pytest.deprecated_call(): + point.buffer(1.0, 8, "round", "round", 5.0) + with pytest.deprecated_call(): + point.buffer(1.0, 8, "round", "round", 5.0, False) + + +def test_simplify_deprecate_positional(): + linestring = LineString([(0, 0), (1, 1)]) + with pytest.deprecated_call( + match="positional argument `preserve_topology` for `simplify` is deprecated" + ): + linestring.simplify(1.0, True) + + +def test_difference_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `grid_size` for `difference` is deprecated" + ): + point.difference(point, None) + + +def test_intersection_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `grid_size` for `intersection` is deprecated" + ): + point.intersection(point, None) + + +def test_symmetric_difference_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `grid_size` for `symmetric_difference` is deprecated" + ): + point.symmetric_difference(point, None) + + +def test_union_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `grid_size` for `union` is deprecated" + ): + point.union(point, None) + + +def test_line_locate_point_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `normalized` for `line_locate_point` is deprecated" + ): + line_string.line_locate_point(Point(1, 1), False) + + +def test_project_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `normalized` for `project` is deprecated" + ): + line_string.project(Point(1, 1), False) + + +def test_line_interpolate_point_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `normalized` for `line_interpolate_point` " + "is deprecated" + ): + line_string.line_interpolate_point(0, False) + + +def test_interpolate_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `normalized` for `interpolate` is deprecated" + ): + line_string.interpolate(0, False) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_hash.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..f54f88548c2f4422d86a74900fcd5f7197e6b3ce --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_hash.py @@ -0,0 +1,28 @@ +import pytest + +import shapely +from shapely.affinity import translate +from shapely.geometry import GeometryCollection, LineString, MultiPoint, Point + + +@pytest.mark.parametrize( + "geom", + [ + Point(1, 2), + MultiPoint([(1, 2), (3, 4)]), + LineString([(1, 2), (3, 4)]), + Point(0, 0).buffer(1.0), + GeometryCollection([Point(1, 2), LineString([(1, 2), (3, 4)])]), + ], + ids=[ + "Point", + "MultiPoint", + "LineString", + "Polygon", + "GeometryCollection", + ], +) +def test_hash(geom): + h1 = hash(geom) + assert h1 == hash(shapely.from_wkb(geom.wkb)) + assert h1 != hash(translate(geom, 1.0, 2.0)) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_linestring.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_linestring.py new file mode 100644 index 0000000000000000000000000000000000000000..231c75aa4fb15d442fe1a09bfa5452ae66b61f75 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_linestring.py @@ -0,0 +1,232 @@ +import numpy as np +import pytest + +import shapely +from shapely import LinearRing, LineString, Point +from shapely.coords import CoordinateSequence + + +def test_from_coordinate_sequence(): + # From coordinate tuples + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + assert len(line.coords) == 2 + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + +def test_from_coordinate_sequence_z(): + line = LineString([(1.0, 2.0, 3.0), (3.0, 4.0, 5.0)]) + assert line.has_z + assert line.coords[:] == [(1.0, 2.0, 3.0), (3.0, 4.0, 5.0)] + + +def test_from_points(): + # From Points + line = LineString([Point(1.0, 2.0), Point(3.0, 4.0)]) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + line = LineString([Point(1.0, 2.0), Point(3.0, 4.0)]) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + +def test_from_mix(): + # From mix of tuples and Points + line = LineString([Point(1.0, 2.0), (2.0, 3.0), Point(3.0, 4.0)]) + assert line.coords[:] == [(1.0, 2.0), (2.0, 3.0), (3.0, 4.0)] + + +def test_from_linestring(): + # From another linestring + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + copy = LineString(line) + assert copy.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + assert copy.geom_type == "LineString" + + +def test_from_linearring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + ring = LinearRing(coords) + copy = LineString(ring) + assert copy.coords[:] == coords + assert copy.geom_type == "LineString" + + +def test_from_linestring_z(): + coords = [(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)] + line = LineString(coords) + copy = LineString(line) + assert copy.coords[:] == coords + assert copy.geom_type == "LineString" + + +def test_from_generator(): + gen = (coord for coord in [(1.0, 2.0), (3.0, 4.0)]) + line = LineString(gen) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + +def test_from_empty(): + line = LineString() + assert line.is_empty + assert isinstance(line.coords, CoordinateSequence) + assert line.coords[:] == [] + + line = LineString([]) + assert line.is_empty + assert isinstance(line.coords, CoordinateSequence) + assert line.coords[:] == [] + + +def test_from_numpy(): + # Construct from a numpy array + line = LineString(np.array([[1.0, 2.0], [3.0, 4.0]])) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + +def test_numpy_empty_linestring_coords(): + # Check empty + line = LineString([]) + la = np.asarray(line.coords) + + assert la.shape == (0, 2) + + +def test_numpy_object_array(): + geom = LineString([(0.0, 0.0), (0.0, 1.0)]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom + + +@pytest.mark.filterwarnings("ignore:Creating an ndarray from ragged nested sequences:") +def test_from_invalid_dim(): + # TODO(shapely-2.0) better error message? + # pytest.raises( + # ValueError, match="at least 2 coordinate tuples|at least 2 coordinates" + # ): + with pytest.raises(shapely.GEOSException): + LineString([(1, 2)]) + + # exact error depends on numpy version + with pytest.raises((ValueError, TypeError)): + LineString([(1, 2, 3), (4, 5)]) + + with pytest.raises((ValueError, TypeError)): + LineString([(1, 2), (3, 4, 5)]) + + msg = r"The ordinate \(last\) dimension should be 2 or 3, got {}" + with pytest.raises(ValueError, match=msg.format(4)): + LineString([(1, 2, 3, 4), (4, 5, 6, 7)]) + + with pytest.raises(ValueError, match=msg.format(1)): + LineString([(1,), (4,)]) + + +def test_from_single_coordinate(): + """Test for issue #486""" + coords = [[-122.185933073564, 37.3629353839073]] + with pytest.raises(shapely.GEOSException): + ls = LineString(coords) + ls.geom_type # caused segfault before fix + + +class TestLineString: + def test_linestring(self): + # From coordinate tuples + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + assert len(line.coords) == 2 + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + # Bounds + assert line.bounds == (1.0, 2.0, 3.0, 4.0) + + # Coordinate access + assert tuple(line.coords) == ((1.0, 2.0), (3.0, 4.0)) + assert line.coords[0] == (1.0, 2.0) + assert line.coords[1] == (3.0, 4.0) + with pytest.raises(IndexError): + line.coords[2] # index out of range + + # Geo interface + assert line.__geo_interface__ == { + "type": "LineString", + "coordinates": ((1.0, 2.0), (3.0, 4.0)), + } + + def test_linestring_empty(self): + # Test Non-operability of Null geometry + l_null = LineString() + assert l_null.wkt == "LINESTRING EMPTY" + assert l_null.length == 0.0 + + def test_equals_argument_order(self): + """ + Test equals predicate functions correctly regardless of the order + of the inputs. See issue #317. + """ + coords = ((0, 0), (1, 0), (1, 1), (0, 0)) + ls = LineString(coords) + lr = LinearRing(coords) + + assert ls.__eq__(lr) is False # previously incorrectly returned True + assert lr.__eq__(ls) is False + assert (ls == lr) is False + assert (lr == ls) is False + + ls_clone = LineString(coords) + lr_clone = LinearRing(coords) + + assert ls.__eq__(ls_clone) is True + assert lr.__eq__(lr_clone) is True + assert (ls == ls_clone) is True + assert (lr == lr_clone) is True + + def test_numpy_linestring_coords(self): + from numpy.testing import assert_array_equal + + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + expected = np.array([[1.0, 2.0], [3.0, 4.0]]) + + # Coordinate sequences can be adapted as well + la = np.asarray(line.coords) + assert_array_equal(la, expected) + + +def test_linestring_immutable(): + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + + with pytest.raises(AttributeError): + line.coords = [(-1.0, -1.0), (1.0, 1.0)] + + with pytest.raises(TypeError): + line.coords[0] = (-1.0, -1.0) + + +def test_linestring_array_coercion(): + # don't convert to array of coordinates, keep objects + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + arr = np.array(line) + assert arr.ndim == 0 + assert arr.size == 1 + assert arr.dtype == np.dtype("object") + assert arr.item() == line + + +def test_offset_curve_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `quad_segs` for `offset_curve` is deprecated" + ): + line_string.offset_curve(1.0, 8) + with pytest.deprecated_call( + match="positional arguments `quad_segs` and `join_style` " + "for `offset_curve` are deprecated" + ): + line_string.offset_curve(1.0, 8, "round") + with pytest.deprecated_call( + match="positional arguments `quad_segs`, `join_style`, and `mitre_limit` " + "for `offset_curve` are deprecated" + ): + line_string.offset_curve(1.0, 8, "round", 5.0) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multi.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multi.py new file mode 100644 index 0000000000000000000000000000000000000000..59dc043540f6808e878af7ebedd9b03aa126e751 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multi.py @@ -0,0 +1,11 @@ +import numpy as np + +test_int_types = [int, np.int16, np.int32, np.int64] + + +class MultiGeometryTestCase: + def subgeom_access_test(self, cls, geoms): + geom = cls(geoms) + for t in test_int_types: + for i, g in enumerate(geoms): + assert geom.geoms[t(i)] == g diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multilinestring.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multilinestring.py new file mode 100644 index 0000000000000000000000000000000000000000..637e66ab930230ec398596d87ba2e46073f69ea8 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multilinestring.py @@ -0,0 +1,77 @@ +import numpy as np +import pytest + +from shapely import LineString, MultiLineString +from shapely.errors import EmptyPartError +from shapely.geometry.base import dump_coords +from shapely.tests.geometry.test_multi import MultiGeometryTestCase + + +class TestMultiLineString(MultiGeometryTestCase): + def test_multilinestring(self): + # From coordinate tuples + geom = MultiLineString([[(1.0, 2.0), (3.0, 4.0)]]) + assert isinstance(geom, MultiLineString) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [[(1.0, 2.0), (3.0, 4.0)]] + + # From lines + a = LineString([(1.0, 2.0), (3.0, 4.0)]) + ml = MultiLineString([a]) + assert len(ml.geoms) == 1 + assert dump_coords(ml) == [[(1.0, 2.0), (3.0, 4.0)]] + + # From another multi-line + ml2 = MultiLineString(ml) + assert len(ml2.geoms) == 1 + assert dump_coords(ml2) == [[(1.0, 2.0), (3.0, 4.0)]] + + # Sub-geometry Access + geom = MultiLineString([(((0.0, 0.0), (1.0, 2.0)))]) + assert isinstance(geom.geoms[0], LineString) + assert dump_coords(geom.geoms[0]) == [(0.0, 0.0), (1.0, 2.0)] + with pytest.raises(IndexError): # index out of range + geom.geoms[1] + + # Geo interface + assert geom.__geo_interface__ == { + "type": "MultiLineString", + "coordinates": (((0.0, 0.0), (1.0, 2.0)),), + } + + def test_from_multilinestring_z(self): + coords1 = [(0.0, 1.0, 2.0), (3.0, 4.0, 5.0)] + coords2 = [(6.0, 7.0, 8.0), (9.0, 10.0, 11.0)] + + # From coordinate tuples + ml = MultiLineString([coords1, coords2]) + copy = MultiLineString(ml) + assert isinstance(copy, MultiLineString) + assert copy.geom_type == "MultiLineString" + assert len(copy.geoms) == 2 + assert dump_coords(copy.geoms[0]) == coords1 + assert dump_coords(copy.geoms[1]) == coords2 + + def test_numpy(self): + # Construct from a numpy array + geom = MultiLineString([np.array(((0.0, 0.0), (1.0, 2.0)))]) + assert isinstance(geom, MultiLineString) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [[(0.0, 0.0), (1.0, 2.0)]] + + def test_subgeom_access(self): + line0 = LineString([(0.0, 1.0), (2.0, 3.0)]) + line1 = LineString([(4.0, 5.0), (6.0, 7.0)]) + self.subgeom_access_test(MultiLineString, [line0, line1]) + + def test_create_multi_with_empty_component(self): + msg = "Can't create MultiLineString with empty component" + with pytest.raises(EmptyPartError, match=msg): + MultiLineString([LineString([(0, 0), (1, 1), (2, 2)]), LineString()]).wkt + + +def test_numpy_object_array(): + geom = MultiLineString([[[5.0, 6.0], [7.0, 8.0]]]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multipoint.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multipoint.py new file mode 100644 index 0000000000000000000000000000000000000000..aedfce5499cd642ce16d0eeebe9f31a4162c9c99 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multipoint.py @@ -0,0 +1,93 @@ +import numpy as np +import pytest + +import shapely +from shapely import MultiPoint, Point +from shapely.errors import EmptyPartError +from shapely.geometry.base import dump_coords +from shapely.tests.geometry.test_multi import MultiGeometryTestCase + + +class TestMultiPoint(MultiGeometryTestCase): + def test_multipoint(self): + # From coordinate tuples + geom = MultiPoint([(1.0, 2.0), (3.0, 4.0)]) + assert len(geom.geoms) == 2 + assert dump_coords(geom) == [[(1.0, 2.0)], [(3.0, 4.0)]] + + # From points + geom = MultiPoint([Point(1.0, 2.0), Point(3.0, 4.0)]) + assert len(geom.geoms) == 2 + assert dump_coords(geom) == [[(1.0, 2.0)], [(3.0, 4.0)]] + + # From another multi-point + geom2 = MultiPoint(geom) + assert len(geom2.geoms) == 2 + assert dump_coords(geom2) == [[(1.0, 2.0)], [(3.0, 4.0)]] + + # Sub-geometry Access + assert isinstance(geom.geoms[0], Point) + assert geom.geoms[0].x == 1.0 + assert geom.geoms[0].y == 2.0 + with pytest.raises(IndexError): # index out of range + geom.geoms[2] + + # Geo interface + assert geom.__geo_interface__ == { + "type": "MultiPoint", + "coordinates": ((1.0, 2.0), (3.0, 4.0)), + } + + def test_multipoint_from_numpy(self): + # Construct from a numpy array + geom = MultiPoint(np.array([[0.0, 0.0], [1.0, 2.0]])) + assert isinstance(geom, MultiPoint) + assert len(geom.geoms) == 2 + assert dump_coords(geom) == [[(0.0, 0.0)], [(1.0, 2.0)]] + + def test_subgeom_access(self): + p0 = Point(1.0, 2.0) + p1 = Point(3.0, 4.0) + self.subgeom_access_test(MultiPoint, [p0, p1]) + + def test_create_multi_with_empty_component(self): + msg = "Can't create MultiPoint with empty component" + with pytest.raises(EmptyPartError, match=msg): + MultiPoint([Point(0, 0), Point()]) + + if shapely.geos_version < (3, 13, 0): + # for older GEOS, Point(NaN, NaN) is considered empty + with pytest.raises(EmptyPartError, match=msg): + MultiPoint([(0, 0), (np.nan, np.nan)]) + + with pytest.raises(EmptyPartError, match=msg): + MultiPoint(np.array([(0, 0), (np.nan, np.nan)])) + + else: + result = MultiPoint([(0, 0), (np.nan, np.nan)]) + expected = shapely.multipoints( + shapely.points([(0, 0), (np.nan, np.nan)], handle_nan="allow") + ) + assert result == expected + + +def test_multipoint_array_coercion(): + geom = MultiPoint([(1.0, 2.0), (3.0, 4.0)]) + arr = np.array(geom) + assert arr.ndim == 0 + assert arr.size == 1 + assert arr.dtype == np.dtype("object") + assert arr.item() == geom + + +def test_numpy_object_array(): + geom = MultiPoint([(1.0, 2.0), (3.0, 4.0)]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom + + +def test_len_raises(): + geom = MultiPoint([[5.0, 6.0], [7.0, 8.0]]) + with pytest.raises(TypeError): + len(geom) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multipolygon.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multipolygon.py new file mode 100644 index 0000000000000000000000000000000000000000..0494951ff4984d7b1a992fe5b1f5d4998dd9dd3e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_multipolygon.py @@ -0,0 +1,156 @@ +import numpy as np +import pytest + +from shapely import MultiPolygon, Polygon +from shapely.geometry.base import dump_coords +from shapely.tests.geometry.test_multi import MultiGeometryTestCase + + +class TestMultiPolygon(MultiGeometryTestCase): + def test_multipolygon(self): + # Empty + geom = MultiPolygon([]) + assert geom.is_empty + assert len(geom.geoms) == 0 + + # From coordinate tuples + coords = [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), + [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))], + ) + ] + geom = MultiPolygon(coords) + assert isinstance(geom, MultiPolygon) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [ + [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + [(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)], + ] + ] + + # Or without holes + coords2 = [(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)),)] + geom = MultiPolygon(coords2) + assert isinstance(geom, MultiPolygon) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [ + [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + ] + ] + + # Or from polygons + p = Polygon( + ((0, 0), (0, 1), (1, 1), (1, 0)), + [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))], + ) + geom = MultiPolygon([p]) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [ + [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + [(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)], + ] + ] + + # None and empty polygons are dropped + geom_from_list_with_empty = MultiPolygon([p, None, Polygon()]) + assert geom_from_list_with_empty == geom + + # Or from a list of multiple polygons + geom_multiple_from_list = MultiPolygon([p, p]) + assert len(geom_multiple_from_list.geoms) == 2 + assert all(p == geom.geoms[0] for p in geom_multiple_from_list.geoms) + + # Or from a np.array of polygons + geom_multiple_from_array = MultiPolygon(np.array([p, p])) + assert geom_multiple_from_array == geom_multiple_from_list + + # Or from another multi-polygon + geom2 = MultiPolygon(geom) + assert len(geom2.geoms) == 1 + assert dump_coords(geom2) == [ + [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + [(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)], + ] + ] + + # Sub-geometry Access + assert isinstance(geom.geoms[0], Polygon) + assert dump_coords(geom.geoms[0]) == [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + [(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)], + ] + with pytest.raises(IndexError): # index out of range + geom.geoms[1] + + # Geo interface + assert geom.__geo_interface__ == { + "type": "MultiPolygon", + "coordinates": [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)), + ((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)), + ) + ], + } + + def test_subgeom_access(self): + poly0 = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)]) + poly1 = Polygon([(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25)]) + self.subgeom_access_test(MultiPolygon, [poly0, poly1]) + + +def test_fail_list_of_multipolygons(): + """A list of multipolygons is not a valid multipolygon ctor argument""" + poly = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)]) + multi = MultiPolygon( + [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), + [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))], + ) + ] + ) + with pytest.raises(ValueError): + MultiPolygon([multi]) + + with pytest.raises(ValueError): + MultiPolygon([poly, multi]) + + +def test_numpy_object_array(): + geom = MultiPolygon( + [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), + [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))], + ) + ] + ) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_point.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_point.py new file mode 100644 index 0000000000000000000000000000000000000000..9995c89adb5946f95382b1cd1ee55defca43b87f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_point.py @@ -0,0 +1,201 @@ +import numpy as np +import pytest + +from shapely import Point, geos_version +from shapely.coords import CoordinateSequence +from shapely.errors import DimensionError, UnsupportedGEOSVersionError + + +def test_from_coordinates(): + # Point + p = Point(1.0, 2.0) + assert p.coords[:] == [(1.0, 2.0)] + assert p.has_z is False + + # PointZ + p = Point(1.0, 2.0, 3.0) + assert p.coords[:] == [(1.0, 2.0, 3.0)] + assert p.has_z + + # empty + p = Point() + assert p.is_empty + assert isinstance(p.coords, CoordinateSequence) + assert p.coords[:] == [] + + +def test_from_sequence(): + # From single coordinate pair + p = Point((3.0, 4.0)) + assert p.coords[:] == [(3.0, 4.0)] + p = Point([3.0, 4.0]) + assert p.coords[:] == [(3.0, 4.0)] + + # From coordinate sequence + p = Point([(3.0, 4.0)]) + assert p.coords[:] == [(3.0, 4.0)] + p = Point([[3.0, 4.0]]) + assert p.coords[:] == [(3.0, 4.0)] + + # PointZ + p = Point((3.0, 4.0, 5.0)) + assert p.coords[:] == [(3.0, 4.0, 5.0)] + p = Point([3.0, 4.0, 5.0]) + assert p.coords[:] == [(3.0, 4.0, 5.0)] + p = Point([(3.0, 4.0, 5.0)]) + assert p.coords[:] == [(3.0, 4.0, 5.0)] + + +def test_from_numpy(): + # Construct from a numpy array + p = Point(np.array([1.0, 2.0])) + assert p.coords[:] == [(1.0, 2.0)] + + p = Point(np.array([1.0, 2.0, 3.0])) + assert p.coords[:] == [(1.0, 2.0, 3.0)] + + +def test_from_numpy_xy(): + # Construct from separate x, y numpy arrays - if those are length 1, + # this is allowed for compat with shapely 1.8 + # (https://github.com/shapely/shapely/issues/1587) + p = Point(np.array([1.0]), np.array([2.0])) + assert p.coords[:] == [(1.0, 2.0)] + + p = Point(np.array([1.0]), np.array([2.0]), np.array([3.0])) + assert p.coords[:] == [(1.0, 2.0, 3.0)] + + +def test_from_point(): + # From another point + p = Point(3.0, 4.0) + q = Point(p) + assert q.coords[:] == [(3.0, 4.0)] + + p = Point(3.0, 4.0, 5.0) + q = Point(p) + assert q.coords[:] == [(3.0, 4.0, 5.0)] + + +def test_from_generator(): + gen = (coord for coord in [(1.0, 2.0)]) + p = Point(gen) + assert p.coords[:] == [(1.0, 2.0)] + + +def test_from_invalid(): + with pytest.raises(TypeError, match="takes at most 3 arguments"): + Point(1, 2, 3, 4) + + # this worked in shapely 1.x, just ignoring the other coords + with pytest.raises( + ValueError, match="takes only scalar or 1-size vector arguments" + ): + Point([(2, 3), (11, 4)]) + + +class TestPoint: + def test_point(self): + # Test XY point + p = Point(1.0, 2.0) + assert p.x == 1.0 + assert type(p.x) is float + assert p.y == 2.0 + assert type(p.y) is float + assert p.coords[:] == [(1.0, 2.0)] + assert str(p) == p.wkt + assert p.has_z is False + with pytest.raises(DimensionError): + p.z + if geos_version >= (3, 12, 0): + assert p.has_m is False + with pytest.raises(DimensionError): + p.m + else: + with pytest.raises(UnsupportedGEOSVersionError): + p.m + + # Check XYZ point + p = Point(1.0, 2.0, 3.0) + assert p.coords[:] == [(1.0, 2.0, 3.0)] + assert str(p) == p.wkt + assert p.has_z is True + assert p.z == 3.0 + assert type(p.z) is float + if geos_version >= (3, 12, 0): + assert p.has_m is False + with pytest.raises(DimensionError): + p.m + + # TODO: Check XYM and XYZM points + + # Coordinate access + p = Point((3.0, 4.0)) + assert p.x == 3.0 + assert p.y == 4.0 + assert tuple(p.coords) == ((3.0, 4.0),) + assert p.coords[0] == (3.0, 4.0) + with pytest.raises(IndexError): # index out of range + p.coords[1] + + # Bounds + assert p.bounds == (3.0, 4.0, 3.0, 4.0) + + # Geo interface + assert p.__geo_interface__ == {"type": "Point", "coordinates": (3.0, 4.0)} + + def test_point_empty(self): + # Test Non-operability of Null geometry + p_null = Point() + assert p_null.wkt == "POINT EMPTY" + assert p_null.coords[:] == [] + assert p_null.area == 0.0 + + assert p_null.__geo_interface__ == {"type": "Point", "coordinates": ()} + + def test_coords(self): + # From Array.txt + p = Point(0.0, 0.0, 1.0) + coords = p.coords[0] + assert coords == (0.0, 0.0, 1.0) + + # Convert to Numpy array, passing through Python sequence + a = np.asarray(coords) + assert a.ndim == 1 + assert a.size == 3 + assert a.shape == (3,) + + +def test_point_immutable(): + p = Point(3.0, 4.0) + + with pytest.raises(AttributeError): + p.coords = (2.0, 1.0) + + with pytest.raises(TypeError): + p.coords[0] = (2.0, 1.0) + + +def test_point_array_coercion(): + # don't convert to array of coordinates, keep objects + p = Point(3.0, 4.0) + arr = np.array(p) + assert arr.ndim == 0 + assert arr.size == 1 + assert arr.dtype == np.dtype("object") + assert arr.item() == p + + +def test_numpy_empty_point_coords(): + pe = Point() + + # Access the coords + a = np.asarray(pe.coords) + assert a.shape == (0, 2) + + +def test_numpy_object_array(): + geom = Point(3.0, 4.0) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_polygon.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_polygon.py new file mode 100644 index 0000000000000000000000000000000000000000..21a67a461c28f7f18fc3f66a1e008335ebb30b2c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/geometry/test_polygon.py @@ -0,0 +1,460 @@ +"""Polygons and Linear Rings""" + +import numpy as np +import pytest + +from shapely import LinearRing, LineString, Point, Polygon +from shapely.coords import CoordinateSequence +from shapely.errors import TopologicalError +from shapely.wkb import loads as load_wkb + + +def test_empty_linearring_coords(): + assert LinearRing().coords[:] == [] + + +def test_linearring_from_coordinate_sequence(): + expected_coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + + ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + assert ring.coords[:] == expected_coords + + ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + assert ring.coords[:] == expected_coords + + +def test_linearring_from_points(): + # From Points + expected_coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + + ring = LinearRing([Point(0.0, 0.0), Point(0.0, 1.0), Point(1.0, 1.0)]) + assert ring.coords[:] == expected_coords + + +def test_linearring_from_closed_linestring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + line = LineString(coords) + ring = LinearRing(line) + assert len(ring.coords) == 4 + assert ring.coords[:] == coords + assert ring.geom_type == "LinearRing" + + +def test_linearring_from_unclosed_linestring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + line = LineString(coords[:-1]) # Pass in unclosed line + ring = LinearRing(line) + assert len(ring.coords) == 4 + assert ring.coords[:] == coords + assert ring.geom_type == "LinearRing" + + +def test_linearring_from_invalid(): + coords = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)] + line = LineString(coords) + assert not line.is_valid + with pytest.raises(TopologicalError): + LinearRing(line) + + +def test_linearring_from_too_short_linestring(): + # Creation of LinearRing request at least 3 coordinates (unclosed) or + # 4 coordinates (closed) + coords = [(0.0, 0.0), (1.0, 1.0)] + line = LineString(coords) + with pytest.raises(ValueError, match="requires at least 4 coordinates"): + LinearRing(line) + + +def test_linearring_from_linearring(): + coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + ring = LinearRing(coords) + assert ring.coords[:] == coords + + +def test_linearring_from_generator(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + gen = (coord for coord in coords) + ring = LinearRing(gen) + assert ring.coords[:] == coords + + +def test_linearring_from_empty(): + ring = LinearRing() + assert ring.is_empty + assert isinstance(ring.coords, CoordinateSequence) + assert ring.coords[:] == [] + + ring = LinearRing([]) + assert ring.is_empty + assert isinstance(ring.coords, CoordinateSequence) + assert ring.coords[:] == [] + + +def test_linearring_from_numpy(): + # Construct from a numpy array + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + + ring = LinearRing(np.array(coords)) + assert ring.coords[:] == [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + + +def test_numpy_linearring_coords(): + from numpy.testing import assert_array_equal + + ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + ra = np.asarray(ring.coords) + expected = np.asarray([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]) + assert_array_equal(ra, expected) + + +def test_numpy_empty_linearring_coords(): + ring = LinearRing() + assert np.asarray(ring.coords).shape == (0, 2) + + +def test_numpy_object_array(): + geom = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom + + +def test_polygon_from_coordinate_sequence(): + coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + + # Construct a polygon, exterior ring only + polygon = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 0 + + polygon = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 0 + + +def test_polygon_from_coordinate_sequence_with_holes(): + coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + + # Interior rings (holes) + polygon = Polygon(coords, [[(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25)]]) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 1 + assert len(polygon.interiors[0].coords) == 5 + + # Multiple interior rings with different length + coords = [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)] + holes = [ + [(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)], + [(3, 3), (3, 4), (4, 5), (5, 4), (5, 3), (3, 3)], + ] + polygon = Polygon(coords, holes) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 2 + assert len(polygon.interiors[0].coords) == 5 + assert len(polygon.interiors[1].coords) == 6 + + +def test_polygon_from_linearring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + ring = LinearRing(coords) + + polygon = Polygon(ring) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 0 + + # from shell and holes linearrings + shell = LinearRing([(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)]) + holes = [ + LinearRing([(60.0, 80.0), (80.0, 80.0), (70.0, 60.0), (60.0, 80.0)]), + LinearRing([(30.0, 10.0), (50.0, 10.0), (40.0, 30.0), (30.0, 10.0)]), + LinearRing([(90.0, 10), (110.0, 10.0), (100.0, 30.0), (90.0, 10.0)]), + ] + polygon = Polygon(shell, holes) + assert polygon.exterior.coords[:] == shell.coords[:] + assert len(polygon.interiors) == 3 + for i in range(3): + assert polygon.interiors[i].coords[:] == holes[i].coords[:] + + +def test_polygon_from_linestring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + line = LineString(coords) + polygon = Polygon(line) + assert polygon.exterior.coords[:] == coords + + # from unclosed linestring + line = LineString(coords[:-1]) + polygon = Polygon(line) + assert polygon.exterior.coords[:] == coords + + +def test_polygon_from_points(): + polygon = Polygon([Point(0.0, 0.0), Point(0.0, 1.0), Point(1.0, 1.0)]) + expected_coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + assert polygon.exterior.coords[:] == expected_coords + + +def test_polygon_from_polygon(): + coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)] + polygon = Polygon(coords, [[(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25)]]) + + # Test from another Polygon + copy = Polygon(polygon) + assert len(copy.exterior.coords) == 5 + assert len(copy.interiors) == 1 + assert len(copy.interiors[0].coords) == 5 + + +def test_polygon_from_invalid(): + # Error handling + with pytest.raises(ValueError): + # A LinearRing must have at least 3 coordinate tuples + Polygon([[1, 2], [2, 3]]) + + +def test_polygon_from_empty(): + polygon = Polygon() + assert polygon.is_empty + assert polygon.exterior.coords[:] == [] + + polygon = Polygon([]) + assert polygon.is_empty + assert polygon.exterior.coords[:] == [] + + +def test_polygon_from_numpy(): + a = np.array(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0))) + polygon = Polygon(a) + assert len(polygon.exterior.coords) == 5 + assert polygon.exterior.coords[:] == [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + ] + assert len(polygon.interiors) == 0 + + +def test_polygon_from_generator(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + gen = (coord for coord in coords) + polygon = Polygon(gen) + assert polygon.exterior.coords[:] == coords + + +class TestPolygon: + def test_linearring(self): + # Initialization + # Linear rings won't usually be created by users, but by polygons + coords = ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)) + ring = LinearRing(coords) + assert len(ring.coords) == 5 + assert ring.coords[0] == ring.coords[4] + assert ring.coords[0] == ring.coords[-1] + assert ring.is_ring is True + + def test_polygon(self): + coords = ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)) + + # Construct a polygon, exterior ring only + polygon = Polygon(coords) + assert len(polygon.exterior.coords) == 5 + + # Ring Access + assert isinstance(polygon.exterior, LinearRing) + ring = polygon.exterior + assert len(ring.coords) == 5 + assert ring.coords[0] == ring.coords[4] + assert ring.coords[0] == (0.0, 0.0) + assert ring.is_ring is True + assert len(polygon.interiors) == 0 + + # Create a new polygon from WKB + data = polygon.wkb + polygon = None + ring = None + polygon = load_wkb(data) + ring = polygon.exterior + assert len(ring.coords) == 5 + assert ring.coords[0] == ring.coords[4] + assert ring.coords[0] == (0.0, 0.0) + assert ring.is_ring is True + polygon = None + + # Interior rings (holes) + polygon = Polygon( + coords, [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))] + ) + assert len(polygon.exterior.coords) == 5 + assert len(polygon.interiors[0].coords) == 5 + with pytest.raises(IndexError): # index out of range + polygon.interiors[1] + + # Coordinate getter raises exceptions + with pytest.raises(NotImplementedError): + polygon.coords + + # Geo interface + assert polygon.__geo_interface__ == { + "type": "Polygon", + "coordinates": ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)), + ((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)), + ), + } + + def test_linearring_empty(self): + # Test Non-operability of Null rings + r_null = LinearRing() + assert r_null.wkt == "LINEARRING EMPTY" + assert r_null.length == 0.0 + + def test_dimensions(self): + # Background: see http://trac.gispython.org/lab/ticket/168 + # http://lists.gispython.org/pipermail/community/2008-August/001859.html + + coords = ((0.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 1.0, 0.0), (1.0, 0.0, 0.0)) + polygon = Polygon(coords) + assert polygon._ndim == 3 + gi = polygon.__geo_interface__ + assert gi["coordinates"] == ( + ( + (0.0, 0.0, 0.0), + (0.0, 1.0, 0.0), + (1.0, 1.0, 0.0), + (1.0, 0.0, 0.0), + (0.0, 0.0, 0.0), + ), + ) + + e = polygon.exterior + assert e._ndim == 3 + gi = e.__geo_interface__ + assert gi["coordinates"] == ( + (0.0, 0.0, 0.0), + (0.0, 1.0, 0.0), + (1.0, 1.0, 0.0), + (1.0, 0.0, 0.0), + (0.0, 0.0, 0.0), + ) + + def test_attribute_chains(self): + # Attribute Chaining + # See also ticket #151. + p = Polygon([(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)]) + assert list(p.boundary.coords) == [ + (0.0, 0.0), + (0.0, 1.0), + (-1.0, 1.0), + (-1.0, 0.0), + (0.0, 0.0), + ] + + ec = list(Point(0.0, 0.0).buffer(1.0, quad_segs=1).exterior.coords) + assert isinstance(ec, list) # TODO: this is a poor test + + # Test chained access to interiors + p = Polygon( + [(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)], + [[(-0.25, 0.25), (-0.25, 0.75), (-0.75, 0.75), (-0.75, 0.25)]], + ) + assert p.area == 0.75 + + """Not so much testing the exact values here, which are the + responsibility of the geometry engine (GEOS), but that we can get + chain functions and properties using anonymous references. + """ + assert list(p.interiors[0].coords) == [ + (-0.25, 0.25), + (-0.25, 0.75), + (-0.75, 0.75), + (-0.75, 0.25), + (-0.25, 0.25), + ] + xy = next(iter(p.interiors[0].buffer(1).exterior.coords)) + assert len(xy) == 2 + + # Test multiple operators, boundary of a buffer + ec = list(p.buffer(1).boundary.coords) + assert isinstance(ec, list) # TODO: this is a poor test + + def test_empty_equality(self): + # Test equals operator, including empty geometries + # see issue #338 + + point1 = Point(0, 0) + polygon1 = Polygon([(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)]) + polygon2 = Polygon([(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)]) + polygon_empty1 = Polygon() + polygon_empty2 = Polygon() + + assert point1 != polygon1 + assert polygon_empty1 == polygon_empty2 + assert polygon1 != polygon_empty1 + assert polygon1 == polygon2 + assert polygon_empty1 is not None + + def test_from_bounds(self): + xmin, ymin, xmax, ymax = -180, -90, 180, 90 + coords = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)] + assert Polygon(coords) == Polygon.from_bounds(xmin, ymin, xmax, ymax) + + def test_empty_polygon_exterior(self): + p = Polygon() + assert p.exterior == LinearRing() + + +def test_linearring_immutable(): + ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)]) + + with pytest.raises(AttributeError): + ring.coords = [(1.0, 1.0), (2.0, 2.0), (1.0, 2.0)] + + with pytest.raises(TypeError): + ring.coords[0] = (1.0, 1.0) + + +class TestLinearRingGetItem: + def test_index_linearring(self): + shell = LinearRing([(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)]) + holes = [ + LinearRing([(60.0, 80.0), (80.0, 80.0), (70.0, 60.0), (60.0, 80.0)]), + LinearRing([(30.0, 10.0), (50.0, 10.0), (40.0, 30.0), (30.0, 10.0)]), + LinearRing([(90.0, 10), (110.0, 10.0), (100.0, 30.0), (90.0, 10.0)]), + ] + g = Polygon(shell, holes) + for i in range(-3, 3): + assert g.interiors[i].equals(holes[i]) + with pytest.raises(IndexError): + g.interiors[3] + with pytest.raises(IndexError): + g.interiors[-4] + + def test_index_linearring_misc(self): + g = Polygon() # empty + with pytest.raises(IndexError): + g.interiors[0] + with pytest.raises(TypeError): + g.interiors[0.0] + + def test_slice_linearring(self): + shell = LinearRing([(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)]) + holes = [ + LinearRing([(60.0, 80.0), (80.0, 80.0), (70.0, 60.0), (60.0, 80.0)]), + LinearRing([(30.0, 10.0), (50.0, 10.0), (40.0, 30.0), (30.0, 10.0)]), + LinearRing([(90.0, 10), (110.0, 10.0), (100.0, 30.0), (90.0, 10.0)]), + ] + g = Polygon(shell, holes) + t = [a.equals(b) for (a, b) in zip(g.interiors[1:], holes[1:])] + assert all(t) + t = [a.equals(b) for (a, b) in zip(g.interiors[:-1], holes[:-1])] + assert all(t) + t = [a.equals(b) for (a, b) in zip(g.interiors[::-1], holes[::-1])] + assert all(t) + t = [a.equals(b) for (a, b) in zip(g.interiors[::2], holes[::2])] + assert all(t) + t = [a.equals(b) for (a, b) in zip(g.interiors[:3], holes[:3])] + assert all(t) + assert g.interiors[3:] == holes[3:] == [] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b420cd6e9d0ac11cb819c54d9365c01fdfc8d18 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/conftest.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..253bcec40476a2437aa62971670c44a180d263db Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/conftest.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_affinity.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_affinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c621539110934a63451590c1fc31ce9f932b2914 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_affinity.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_box.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_box.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54ac80f9b95097b5bfc9b47380ba03d4c8a25c04 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_box.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_buffer.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_buffer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60723be15ced83de7cfd343b84d0d7ca9e7a2afe Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_buffer.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_cga.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_cga.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ef90b8d9807f9c981f6c6129399800783fba17c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_cga.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_clip_by_rect.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_clip_by_rect.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac631a9035193fe49f352f61e6d48f342f301165 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_clip_by_rect.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_create_inconsistent_dimensionality.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_create_inconsistent_dimensionality.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91dd0bd30b6414d85f8e72bf5e43957c0948184e Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_create_inconsistent_dimensionality.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_delaunay.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_delaunay.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f72adf861265cdc1b2b6a9a78d9bb0b39cd0fac7 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_delaunay.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_empty_polygons.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_empty_polygons.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d39279e070817355074c80272ec9f8782947147 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_empty_polygons.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_equality.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_equality.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b90acb6a24e3e19fbb3c510ec4a93fcef8df13c2 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_equality.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_geointerface.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_geointerface.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d2685621776151805f8d68d4359bf71595b17b7 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_geointerface.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_invalid_geometries.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_invalid_geometries.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63755f2803ce46151ae517081b328f7f231d71e5 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_invalid_geometries.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_linear_referencing.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_linear_referencing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ded7f1224ca2edf37ffd7f6652c50168f2fbd92 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_linear_referencing.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_linemerge.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_linemerge.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9781ebec378af0f883790fe7c898eb991128dfcf Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_linemerge.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_locale.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_locale.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67c22062504259079d5ec2eb5d03578fca7ce27f Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_locale.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_make_valid.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_make_valid.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf544aa046a6cf36d5d390994067c5344e5cc851 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_make_valid.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_mapping.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_mapping.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5f9e7b6aedd3e1958bbc6aa7152696a93ab2845 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_mapping.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_minimum_clearance.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_minimum_clearance.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f75ea5ae7b331a25c241a3a40a453b36f4cd00b9 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_minimum_clearance.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_ndarrays.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_ndarrays.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b59d1d07cb676f708832d69ed12250f59e04299a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_ndarrays.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_nearest.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_nearest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5097496a2437028ad6128d5865d9dfff551b5426 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_nearest.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_operations.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_operations.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd8b138d88be653682246bba90d5ba465a1fa16c Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_operations.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_operators.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_operators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aa9561c97b4a83a022e4550d89c5e5c3ea36a88 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_operators.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_orient.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_orient.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e3a224cc71c6b6595e4bc106c536712ee7dea30 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_orient.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_parallel_offset.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_parallel_offset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..137b23c4de97c8554215bd37506b01263cfdc8f1 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_parallel_offset.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_persist.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_persist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24642624a2cb707707f52943b7f7529385a9b676 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_persist.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_pickle.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_pickle.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35393f188b8be6b1128d42131297f88968b34f49 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_pickle.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_polygonize.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_polygonize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6e3ea0b59c4d4629c3b581de54d9f5b0bf595b3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_polygonize.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_polylabel.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_polylabel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb3c55d49aa63bb043211767b71afc484ad4fe79 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_polylabel.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_predicates.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_predicates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..836f2ae76229cff942e94fd85893b19cf9fd49fe Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_predicates.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_prepared.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_prepared.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b38a97908d202dee2d3b60dbf006eec7d9c54fe Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_prepared.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_products_z.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_products_z.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38b95e4bcd6bb6cd2e07d1df579a756f3da049c2 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_products_z.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_shape.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_shape.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7afc1a5a624ad3ccb3ac663af2c90acd6f261ac3 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_shape.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_shared_paths.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_shared_paths.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ff430fbfc41b5d76d3ea7e41f933e8e7b98318b Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_shared_paths.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_singularity.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_singularity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e69829d8faecf39c24533c13f6c90622336be916 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_singularity.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_snap.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_snap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b254d50a5cbd5255e99edff73eb6ff51075fa03 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_snap.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_split.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_split.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f69e1e481b661cae2ec4c2c90c3e837a4ea2d1f8 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_split.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_substring.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_substring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ea57d15a367cabc8935b0260c1660e3990be33a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_substring.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_svg.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_svg.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef994c79206816e7675e4778eddb01c029cf5c22 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_svg.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_transform.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_transform.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5523a608c8e017ad95a84c79c450e15e9b6102e8 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_transform.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_union.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_union.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e55a4b833862f25089a7058725305d930737194d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_union.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_validation.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_validation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72437dae2a7ce01f0413b538de2d650643bad78d Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_validation.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_vectorized.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_vectorized.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88cb9d3af547b0b43a93eba80f43c72b573641c8 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_vectorized.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_voronoi_diagram.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_voronoi_diagram.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..415c3ff044855ff0ef5a7ff93de706d5be29d834 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_voronoi_diagram.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_wkb.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_wkb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a32913ab1ff1b92544b17f67ebd2b40c07c130ee Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_wkb.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_wkt.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_wkt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c29d01409f9bcfaddf8226f8f47a414be8c398b0 Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/test_wkt.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/threading_test.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/threading_test.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16d1ff144e285b3dc557f9884fd5fa03d3f2682a Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/__pycache__/threading_test.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/conftest.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..76519cc0d053a7a74d9eda1b31a22c8bcb6ec85f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/conftest.py @@ -0,0 +1,12 @@ +import numpy +import pytest + +shapely20_todo = pytest.mark.xfail( + strict=True, reason="Not yet implemented for Shapely 2.0" +) +shapely20_wontfix = pytest.mark.xfail(strict=True, reason="Will fail for Shapely 2.0") + + +def pytest_report_header(config): + """Header for pytest.""" + return f"dependencies: numpy-{numpy.__version__}" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_affinity.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_affinity.py new file mode 100644 index 0000000000000000000000000000000000000000..b7cf7b9a9ed59827635820ed5e358c24bcdb1cdc --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_affinity.py @@ -0,0 +1,308 @@ +import unittest +from math import pi + +import numpy as np +import pytest + +from shapely import affinity +from shapely.geometry import Point +from shapely.wkt import loads as load_wkt + + +class AffineTestCase(unittest.TestCase): + def test_affine_params(self): + g = load_wkt("LINESTRING(2.4 4.1, 2.4 3, 3 3)") + + with pytest.raises(TypeError): + affinity.affine_transform(g, None) + + with pytest.raises(ValueError): + affinity.affine_transform(g, [1, 2, 3, 4, 5, 6, 7, 8, 9]) + + with pytest.raises(AttributeError): + affinity.affine_transform(None, [1, 2, 3, 4, 5, 6]) + + def test_affine_geom_types(self): + # identity matrices, which should result with no transformation + matrix2d = (1, 0, 0, 1, 0, 0) + matrix3d = (1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0) + + # empty in, empty out + empty2d = load_wkt("MULTIPOLYGON EMPTY") + assert affinity.affine_transform(empty2d, matrix2d).is_empty + + def test_geom(g2, g3=None): + assert not g2.has_z + a2 = affinity.affine_transform(g2, matrix2d) + assert not a2.has_z + assert g2.equals(a2) + if g3 is not None: + assert g3.has_z + a3 = affinity.affine_transform(g3, matrix3d) + assert a3.has_z + assert g3.equals(a3) + + pt2d = load_wkt("POINT(12.3 45.6)") + pt3d = load_wkt("POINT(12.3 45.6 7.89)") + test_geom(pt2d, pt3d) + ls2d = load_wkt("LINESTRING(0.9 3.4, 0.7 2, 2.5 2.7)") + ls3d = load_wkt("LINESTRING(0.9 3.4 3.3, 0.7 2 2.3, 2.5 2.7 5.5)") + test_geom(ls2d, ls3d) + lr2d = load_wkt("LINEARRING(0.9 3.4, 0.7 2, 2.5 2.7, 0.9 3.4)") + lr3d = load_wkt("LINEARRING(0.9 3.4 3.3, 0.7 2 2.3, 2.5 2.7 5.5, 0.9 3.4 3.3)") + test_geom(lr2d, lr3d) + test_geom( + load_wkt( + "POLYGON((0.9 2.3, 0.5 1.1, 2.4 0.8, 0.9 2.3), " + "(1.1 1.7, 0.9 1.3, 1.4 1.2, 1.1 1.7), " + "(1.6 1.3, 1.7 1, 1.9 1.1, 1.6 1.3))" + ) + ) + test_geom( + load_wkt("MULTIPOINT ((-300 300), (700 300), (-800 -1100), (200 -300))") + ) + test_geom( + load_wkt( + "MULTILINESTRING((0 0, -0.7 -0.7, 0.6 -1), (-0.5 0.5, 0.7 0.6, 0 -0.6))" + ) + ) + test_geom( + load_wkt( + "MULTIPOLYGON(((900 4300, -1100 -400, 900 -800, 900 4300)), " + "((1200 4300, 2300 4400, 1900 1000, 1200 4300)))" + ) + ) + test_geom( + load_wkt( + "GEOMETRYCOLLECTION(POINT(20 70)," + " POLYGON((60 70, 13 35, 60 -30, 60 70))," + " LINESTRING(60 70, 50 100, 80 100))" + ) + ) + + def test_affine_2d(self): + g = load_wkt("LINESTRING(2.4 4.1, 2.4 3, 3 3)") + # custom scale and translate + expected2d = load_wkt("LINESTRING(-0.2 14.35, -0.2 11.6, 1 11.6)") + matrix2d = (2, 0, 0, 2.5, -5, 4.1) + a2 = affinity.affine_transform(g, matrix2d) + assert a2.equals_exact(expected2d, 1e-6) + assert not a2.has_z + # Make sure a 3D matrix does not make a 3D shape from a 2D input + matrix3d = (2, 0, 0, 0, 2.5, 0, 0, 0, 10, -5, 4.1, 100) + a3 = affinity.affine_transform(g, matrix3d) + assert a3.equals_exact(expected2d, 1e-6) + assert not a3.has_z + + def test_affine_3d(self): + g2 = load_wkt("LINESTRING(2.4 4.1, 2.4 3, 3 3)") + g3 = load_wkt("LINESTRING(2.4 4.1 100.2, 2.4 3 132.8, 3 3 128.6)") + # custom scale and translate + matrix2d = (2, 0, 0, 2.5, -5, 4.1) + matrix3d = (2, 0, 0, 0, 2.5, 0, 0, 0, 0.3048, -5, 4.1, 100) + # Combinations of 2D and 3D geometries and matrices + a22 = affinity.affine_transform(g2, matrix2d) + a23 = affinity.affine_transform(g2, matrix3d) + a32 = affinity.affine_transform(g3, matrix2d) + a33 = affinity.affine_transform(g3, matrix3d) + # Check dimensions + assert not a22.has_z + assert not a23.has_z + assert a32.has_z + assert a33.has_z + + # 2D equality checks + expected2d = load_wkt("LINESTRING(-0.2 14.35, -0.2 11.6, 1 11.6)") + expected3d = load_wkt( + "LINESTRING(-0.2 14.35 130.54096, -0.2 11.6 140.47744, 1 11.6 139.19728)" + ) + expected32 = load_wkt( + "LINESTRING(-0.2 14.35 100.2, -0.2 11.6 132.8, 1 11.6 128.6)" + ) + assert a22.equals_exact(expected2d, 1e-6) + assert a23.equals_exact(expected2d, 1e-6) + # Do explicit 3D check of coordinate values + for a, e in zip(a32.coords, expected32.coords): + for ap, ep in zip(a, e): + self.assertAlmostEqual(ap, ep) + for a, e in zip(a33.coords, expected3d.coords): + for ap, ep in zip(a, e): + self.assertAlmostEqual(ap, ep) + + +class TransformOpsTestCase(unittest.TestCase): + def test_rotate(self): + ls = load_wkt("LINESTRING(240 400, 240 300, 300 300)") + # counter-clockwise degrees + rls = affinity.rotate(ls, 90) + els = load_wkt("LINESTRING(220 320, 320 320, 320 380)") + assert rls.equals(els) + # retest with named parameters for the same result + rls = affinity.rotate(geom=ls, angle=90, origin="center") + assert rls.equals(els) + # clockwise radians + rls = affinity.rotate(ls, -pi / 2, use_radians=True) + els = load_wkt("LINESTRING(320 380, 220 380, 220 320)") + assert rls.equals(els) + ## other `origin` parameters + # around the centroid + rls = affinity.rotate(ls, 90, origin="centroid") + els = load_wkt("LINESTRING(182.5 320, 282.5 320, 282.5 380)") + assert rls.equals(els) + # around the second coordinate tuple + rls = affinity.rotate(ls, 90, origin=ls.coords[1]) + els = load_wkt("LINESTRING(140 300, 240 300, 240 360)") + assert rls.equals(els) + # around the absolute Point of origin + rls = affinity.rotate(ls, 90, origin=Point(0, 0)) + els = load_wkt("LINESTRING(-400 240, -300 240, -300 300)") + assert rls.equals(els) + + def test_rotate_empty(self): + rls = affinity.rotate(load_wkt("LINESTRING EMPTY"), 90) + els = load_wkt("LINESTRING EMPTY") + assert rls.equals(els) + + def test_rotate_angle_array(self): + ls = load_wkt("LINESTRING(240 400, 240 300, 300 300)") + els = load_wkt("LINESTRING(220 320, 320 320, 320 380)") + # check with degrees + theta = np.array(90.0) + rls = affinity.rotate(ls, theta) + assert theta.item() == 90.0 + assert rls.equals(els) + # check with radians + theta = np.array(pi / 2) + rls = affinity.rotate(ls, theta, use_radians=True) + assert theta.item() == pi / 2 + assert rls.equals(els) + + def test_scale(self): + ls = load_wkt("LINESTRING(240 400 10, 240 300 30, 300 300 20)") + # test defaults of 1.0 + sls = affinity.scale(ls) + assert sls.equals(ls) + # different scaling in different dimensions + sls = affinity.scale(ls, 2, 3, 0.5) + els = load_wkt("LINESTRING(210 500 5, 210 200 15, 330 200 10)") + assert sls.equals(els) + # Do explicit 3D check of coordinate values + for a, b in zip(sls.coords, els.coords): + for ap, bp in zip(a, b): + self.assertEqual(ap, bp) + # retest with named parameters for the same result + sls = affinity.scale(geom=ls, xfact=2, yfact=3, zfact=0.5, origin="center") + assert sls.equals(els) + ## other `origin` parameters + # around the centroid + sls = affinity.scale(ls, 2, 3, 0.5, origin="centroid") + els = load_wkt("LINESTRING(228.75 537.5, 228.75 237.5, 348.75 237.5)") + assert sls.equals(els) + # around the second coordinate tuple + sls = affinity.scale(ls, 2, 3, 0.5, origin=ls.coords[1]) + els = load_wkt("LINESTRING(240 600, 240 300, 360 300)") + assert sls.equals(els) + # around some other 3D Point of origin + sls = affinity.scale(ls, 2, 3, 0.5, origin=Point(100, 200, 1000)) + els = load_wkt("LINESTRING(380 800 505, 380 500 515, 500 500 510)") + assert sls.equals(els) + # Do explicit 3D check of coordinate values + for a, b in zip(sls.coords, els.coords): + for ap, bp in zip(a, b): + assert ap == bp + + def test_scale_empty(self): + sls = affinity.scale(load_wkt("LINESTRING EMPTY")) + els = load_wkt("LINESTRING EMPTY") + assert sls.equals(els) + + def test_skew(self): + ls = load_wkt("LINESTRING(240 400 10, 240 300 30, 300 300 20)") + # test default shear angles of 0.0 + sls = affinity.skew(ls) + assert sls.equals(ls) + # different shearing in x- and y-directions + sls = affinity.skew(ls, 15, -30) + els = load_wkt( + "LINESTRING (253.39745962155615 417.3205080756888, " + "226.60254037844385 317.3205080756888, " + "286.60254037844385 282.67949192431126)" + ) + assert sls.equals_exact(els, 1e-6) + # retest with radians for the same result + sls = affinity.skew(ls, pi / 12, -pi / 6, use_radians=True) + assert sls.equals_exact(els, 1e-6) + # retest with named parameters for the same result + sls = affinity.skew(geom=ls, xs=15, ys=-30, origin="center", use_radians=False) + assert sls.equals_exact(els, 1e-6) + ## other `origin` parameters + # around the centroid + sls = affinity.skew(ls, 15, -30, origin="centroid") + els = load_wkt( + "LINESTRING(258.42150697963973 406.49519052838332, " + "231.6265877365273980 306.4951905283833185, " + "291.6265877365274264 271.8541743770057337)" + ) + assert sls.equals_exact(els, 1e-6) + # around the second coordinate tuple + sls = affinity.skew(ls, 15, -30, origin=ls.coords[1]) + els = load_wkt( + "LINESTRING(266.7949192431123038 400, 240 300, 300 265.3589838486224153)" + ) + assert sls.equals_exact(els, 1e-6) + # around the absolute Point of origin + sls = affinity.skew(ls, 15, -30, origin=Point(0, 0)) + els = load_wkt( + "LINESTRING(347.179676972449101 261.435935394489832, " + "320.3847577293367976 161.4359353944898317, " + "380.3847577293367976 126.7949192431122754)" + ) + assert sls.equals_exact(els, 1e-6) + + def test_skew_empty(self): + sls = affinity.skew(load_wkt("LINESTRING EMPTY")) + els = load_wkt("LINESTRING EMPTY") + assert sls.equals(els) + + def test_skew_xs_ys_array(self): + ls = load_wkt("LINESTRING(240 400 10, 240 300 30, 300 300 20)") + els = load_wkt( + "LINESTRING (253.39745962155615 417.3205080756888, " + "226.60254037844385 317.3205080756888, " + "286.60254037844385 282.67949192431126)" + ) + # check with degrees + xs_ys = np.array([15.0, -30.0]) + sls = affinity.skew(ls, xs_ys[0, ...], xs_ys[1, ...]) + assert xs_ys[0] == 15.0 + assert xs_ys[1] == -30.0 + assert sls.equals_exact(els, 1e-6) + # check with radians + xs_ys = np.array([pi / 12, -pi / 6]) + sls = affinity.skew(ls, xs_ys[0, ...], xs_ys[1, ...], use_radians=True) + assert xs_ys[0] == pi / 12 + assert xs_ys[1] == -pi / 6 + assert sls.equals_exact(els, 1e-6) + + def test_translate(self): + ls = load_wkt("LINESTRING(240 400 10, 240 300 30, 300 300 20)") + # test default offset of 0.0 + tls = affinity.translate(ls) + assert tls.equals(ls) + # test all offsets + tls = affinity.translate(ls, 100, 400, -10) + els = load_wkt("LINESTRING(340 800 0, 340 700 20, 400 700 10)") + assert tls.equals(els) + # Do explicit 3D check of coordinate values + for a, b in zip(tls.coords, els.coords): + for ap, bp in zip(a, b): + assert ap == bp + # retest with named parameters for the same result + tls = affinity.translate(geom=ls, xoff=100, yoff=400, zoff=-10) + assert tls.equals(els) + + def test_translate_empty(self): + tls = affinity.translate(load_wkt("LINESTRING EMPTY")) + els = load_wkt("LINESTRING EMPTY") + self.assertTrue(tls.equals(els)) + assert tls.equals(els) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_box.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_box.py new file mode 100644 index 0000000000000000000000000000000000000000..40d5a536323587d83fefd6d4e1798ee9736eff25 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_box.py @@ -0,0 +1,20 @@ +import unittest + +from shapely import geometry + + +class BoxTestCase(unittest.TestCase): + def test_ccw(self): + b = geometry.box(0, 0, 1, 1, ccw=True) + assert b.exterior.coords[0] == (1.0, 0.0) + assert b.exterior.coords[1] == (1.0, 1.0) + + def test_ccw_default(self): + b = geometry.box(0, 0, 1, 1) + assert b.exterior.coords[0] == (1.0, 0.0) + assert b.exterior.coords[1] == (1.0, 1.0) + + def test_cw(self): + b = geometry.box(0, 0, 1, 1, ccw=False) + assert b.exterior.coords[0] == (0.0, 0.0) + assert b.exterior.coords[1] == (0.0, 1.0) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_buffer.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..8faf9230f6460f4ab345d320688d3c7647ce7746 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_buffer.py @@ -0,0 +1,173 @@ +import unittest + +import pytest + +from shapely import geometry +from shapely.constructive import BufferCapStyle, BufferJoinStyle +from shapely.geometry.base import CAP_STYLE, JOIN_STYLE + + +@pytest.mark.parametrize("distance", [float("nan"), float("inf")]) +def test_non_finite_distance(distance): + g = geometry.Point(0, 0) + with pytest.raises(ValueError, match="distance must be finite"): + g.buffer(distance) + + +class BufferTests(unittest.TestCase): + """Test Buffer Point/Line/Polygon with and without single_sided params""" + + def test_empty(self): + g = geometry.Point(0, 0) + h = g.buffer(0) + assert h.is_empty + + def test_point(self): + g = geometry.Point(0, 0) + h = g.buffer(1, quad_segs=1) + assert h.geom_type == "Polygon" + expected_coord = [(1.0, 0.0), (0, -1.0), (-1.0, 0), (0, 1.0), (1.0, 0.0)] + for index, coord in enumerate(h.exterior.coords): + assert coord[0] == pytest.approx(expected_coord[index][0]) + assert coord[1] == pytest.approx(expected_coord[index][1]) + + def test_point_single_sidedd(self): + g = geometry.Point(0, 0) + h = g.buffer(1, quad_segs=1, single_sided=True) + assert h.geom_type == "Polygon" + expected_coord = [(1.0, 0.0), (0, -1.0), (-1.0, 0), (0, 1.0), (1.0, 0.0)] + for index, coord in enumerate(h.exterior.coords): + assert coord[0] == pytest.approx(expected_coord[index][0]) + assert coord[1] == pytest.approx(expected_coord[index][1]) + + def test_line(self): + g = geometry.LineString([[0, 0], [0, 1]]) + h = g.buffer(1, quad_segs=1) + assert h.geom_type == "Polygon" + expected_coord = [ + (-1.0, 1.0), + (0, 2.0), + (1.0, 1.0), + (1.0, 0.0), + (0, -1.0), + (-1.0, 0.0), + (-1.0, 1.0), + ] + for index, coord in enumerate(h.exterior.coords): + assert coord[0] == pytest.approx(expected_coord[index][0]) + assert coord[1] == pytest.approx(expected_coord[index][1]) + + def test_line_single_sideded_left(self): + g = geometry.LineString([[0, 0], [0, 1]]) + h = g.buffer(1, quad_segs=1, single_sided=True) + assert h.geom_type == "Polygon" + expected_coord = [(0.0, 1.0), (0.0, 0.0), (-1.0, 0.0), (-1.0, 1.0), (0.0, 1.0)] + for index, coord in enumerate(h.exterior.coords): + assert coord[0] == pytest.approx(expected_coord[index][0]) + assert coord[1] == pytest.approx(expected_coord[index][1]) + + def test_line_single_sideded_right(self): + g = geometry.LineString([[0, 0], [0, 1]]) + h = g.buffer(-1, quad_segs=1, single_sided=True) + assert h.geom_type == "Polygon" + expected_coord = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)] + for index, coord in enumerate(h.exterior.coords): + assert coord[0] == pytest.approx(expected_coord[index][0]) + assert coord[1] == pytest.approx(expected_coord[index][1]) + + def test_polygon(self): + g = geometry.Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]) + h = g.buffer(1, quad_segs=1) + assert h.geom_type == "Polygon" + expected_coord = [ + (-1.0, 0.0), + (-1.0, 1.0), + (0.0, 2.0), + (1.0, 2.0), + (2.0, 1.0), + (2.0, 0.0), + (1.0, -1.0), + (0.0, -1.0), + (-1.0, 0.0), + ] + for index, coord in enumerate(h.exterior.coords): + assert coord[0] == pytest.approx(expected_coord[index][0]) + assert coord[1] == pytest.approx(expected_coord[index][1]) + + def test_polygon_single_sideded(self): + g = geometry.Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]) + h = g.buffer(1, quad_segs=1, single_sided=True) + assert h.geom_type == "Polygon" + expected_coord = [ + (-1.0, 0.0), + (-1.0, 1.0), + (0.0, 2.0), + (1.0, 2.0), + (2.0, 1.0), + (2.0, 0.0), + (1.0, -1.0), + (0.0, -1.0), + (-1.0, 0.0), + ] + for index, coord in enumerate(h.exterior.coords): + assert coord[0] == pytest.approx(expected_coord[index][0]) + assert coord[1] == pytest.approx(expected_coord[index][1]) + + def test_enum_values(self): + assert CAP_STYLE.round == 1 + assert CAP_STYLE.round == BufferCapStyle.round + assert CAP_STYLE.flat == 2 + assert CAP_STYLE.flat == BufferCapStyle.flat + assert CAP_STYLE.square == 3 + assert CAP_STYLE.square == BufferCapStyle.square + + assert JOIN_STYLE.round == 1 + assert JOIN_STYLE.round == BufferJoinStyle.round + assert JOIN_STYLE.mitre == 2 + assert JOIN_STYLE.mitre == BufferJoinStyle.mitre + assert JOIN_STYLE.bevel == 3 + assert JOIN_STYLE.bevel == BufferJoinStyle.bevel + + def test_cap_style(self): + g = geometry.LineString([[0, 0], [1, 0]]) + h = g.buffer(1, cap_style=BufferCapStyle.round) + assert h == g.buffer(1, cap_style=CAP_STYLE.round) + assert h == g.buffer(1, cap_style="round") + + h = g.buffer(1, cap_style=BufferCapStyle.flat) + assert h == g.buffer(1, cap_style=CAP_STYLE.flat) + assert h == g.buffer(1, cap_style="flat") + + h = g.buffer(1, cap_style=BufferCapStyle.square) + assert h == g.buffer(1, cap_style=CAP_STYLE.square) + assert h == g.buffer(1, cap_style="square") + + def test_buffer_style(self): + g = geometry.LineString([[0, 0], [1, 0]]) + h = g.buffer(1, join_style=BufferJoinStyle.round) + assert h == g.buffer(1, join_style=JOIN_STYLE.round) + assert h == g.buffer(1, join_style="round") + + h = g.buffer(1, join_style=BufferJoinStyle.mitre) + assert h == g.buffer(1, join_style=JOIN_STYLE.mitre) + assert h == g.buffer(1, join_style="mitre") + + h = g.buffer(1, join_style=BufferJoinStyle.bevel) + assert h == g.buffer(1, join_style=JOIN_STYLE.bevel) + assert h == g.buffer(1, join_style="bevel") + + +def test_deprecated_quadsegs(): + point = geometry.Point(0, 0) + with pytest.warns(FutureWarning): + result = point.buffer(1, quadsegs=1) + expected = point.buffer(1, quad_segs=1) + assert result.equals(expected) + + +def test_deprecated_resolution(): + point = geometry.Point(0, 0) + with pytest.deprecated_call(match="Use 'quad_segs' instead"): + result = point.buffer(1, resolution=1) + expected = point.buffer(1, quad_segs=1) + assert result.equals(expected) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_cga.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_cga.py new file mode 100644 index 0000000000000000000000000000000000000000..e378559673c749394477587d4349defc7f3ad44e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_cga.py @@ -0,0 +1,51 @@ +import unittest + +import pytest + +from shapely.geometry.polygon import LinearRing, Polygon, orient, signed_area + + +class SignedAreaTestCase(unittest.TestCase): + def test_triangle(self): + tri = LinearRing([(0, 0), (2, 5), (7, 0)]) + assert signed_area(tri) == pytest.approx(-7 * 5 / 2) + + def test_square(self): + xmin, xmax = (-1, 1) + ymin, ymax = (-2, 3) + rect = LinearRing( + [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax), (xmin, ymin)] + ) + assert signed_area(rect) == pytest.approx(10.0) + + +class RingOrientationTestCase(unittest.TestCase): + def test_ccw(self): + ring = LinearRing([(1, 0), (0, 1), (0, 0)]) + assert ring.is_ccw + + def test_cw(self): + ring = LinearRing([(0, 0), (0, 1), (1, 0)]) + assert not ring.is_ccw + + +class PolygonOrienterTestCase(unittest.TestCase): + def test_no_holes(self): + ring = LinearRing([(0, 0), (0, 1), (1, 0)]) + polygon = Polygon(ring) + assert not polygon.exterior.is_ccw + polygon = orient(polygon, 1) + assert polygon.exterior.is_ccw + + def test_holes(self): + # fmt: off + polygon = Polygon( + [(0, 0), (0, 1), (1, 0)], + [[(0.5, 0.25), (0.25, 0.5), (0.25, 0.25)]] + ) + # fmt: on + assert not polygon.exterior.is_ccw + assert polygon.interiors[0].is_ccw + polygon = orient(polygon, 1) + assert polygon.exterior.is_ccw + assert not polygon.interiors[0].is_ccw diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_clip_by_rect.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_clip_by_rect.py new file mode 100644 index 0000000000000000000000000000000000000000..06ccbc533d35de00e17e90e610665d11dd93d71a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_clip_by_rect.py @@ -0,0 +1,119 @@ +""" +Tests for GEOSClipByRect based on unit tests from libgeos. + +There are some expected differences due to Shapely's handling of empty +geometries. +""" + +import pytest + +from shapely.ops import clip_by_rect +from shapely.wkt import dumps as dump_wkt, loads as load_wkt + + +def test_point_outside(): + """Point outside""" + geom1 = load_wkt("POINT (0 0)") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY" + + +def test_point_inside(): + """Point inside""" + geom1 = load_wkt("POINT (15 15)") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "POINT (15 15)" + + +def test_point_on_boundary(): + """Point on boundary""" + geom1 = load_wkt("POINT (15 10)") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY" + + +def test_line_outside(): + """Line outside""" + geom1 = load_wkt("LINESTRING (0 0, -5 5)") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY" + + +def test_line_inside(): + """Line inside""" + geom1 = load_wkt("LINESTRING (15 15, 16 15)") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "LINESTRING (15 15, 16 15)" + + +def test_line_on_boundary(): + """Line on boundary""" + geom1 = load_wkt("LINESTRING (10 15, 10 10, 15 10)") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY" + + +def test_line_splitting_rectangle(): + """Line splitting rectangle""" + geom1 = load_wkt("LINESTRING (10 5, 25 20)") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "LINESTRING (15 10, 20 15)" + + +@pytest.mark.xfail(reason="TODO issue to CCW") +def test_polygon_shell_ccw_fully_on_rectangle_boundary(): + """Polygon shell (CCW) fully on rectangle boundary""" + geom1 = load_wkt("POLYGON ((10 10, 20 10, 20 20, 10 20, 10 10))") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert ( + dump_wkt(geom2, rounding_precision=0) + == "POLYGON ((10 10, 20 10, 20 20, 10 20, 10 10))" + ) + + +@pytest.mark.xfail(reason="TODO issue to CW") +def test_polygon_shell_cc_fully_on_rectangle_boundary(): + """Polygon shell (CW) fully on rectangle boundary""" + geom1 = load_wkt("POLYGON ((10 10, 10 20, 20 20, 20 10, 10 10))") + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert ( + dump_wkt(geom2, rounding_precision=0) + == "POLYGON ((10 10, 20 10, 20 20, 10 20, 10 10))" + ) + + +def polygon_hole_ccw_fully_on_rectangle_boundary(): + """Polygon hole (CCW) fully on rectangle boundary""" + geom1 = load_wkt( + "POLYGON ((0 0, 0 30, 30 30, 30 0, 0 0), (10 10, 20 10, 20 20, 10 20, 10 10))" + ) + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY" + + +def polygon_hole_cw_fully_on_rectangle_boundary(): + """Polygon hole (CW) fully on rectangle boundary""" + geom1 = load_wkt( + "POLYGON ((0 0, 0 30, 30 30, 30 0, 0 0), (10 10, 10 20, 20 20, 20 10, 10 10))" + ) + geom2 = clip_by_rect(geom1, 10, 10, 20, 20) + assert dump_wkt(geom2, rounding_precision=0) == "GEOMETRYCOLLECTION EMPTY" + + +def polygon_fully_within_rectangle(): + """Polygon fully within rectangle""" + wkt = "POLYGON ((1 1, 1 30, 30 30, 30 1, 1 1), (10 10, 20 10, 20 20, 10 20, 10 10))" + geom1 = load_wkt(wkt) + geom2 = clip_by_rect(geom1, 0, 0, 40, 40) + assert dump_wkt(geom2, rounding_precision=0) == wkt + + +def polygon_overlapping_rectangle(): + """Polygon overlapping rectangle""" + wkt = "POLYGON ((0 0, 0 30, 30 30, 30 0, 0 0), (10 10, 20 10, 20 20, 10 20, 10 10))" + geom1 = load_wkt(wkt) + geom2 = clip_by_rect(geom1, 5, 5, 15, 15) + assert ( + dump_wkt(geom2, rounding_precision=0) + == "POLYGON ((5 5, 5 15, 10 15, 10 10, 15 10, 15 5, 5 5))" + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_create_inconsistent_dimensionality.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_create_inconsistent_dimensionality.py new file mode 100644 index 0000000000000000000000000000000000000000..d87fba2a8c00e438369e00056fd294399b7b5f12 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_create_inconsistent_dimensionality.py @@ -0,0 +1,217 @@ +""" +When a "context" passed to shape/asShape has a coordinate +which is missing a dimension we should raise a descriptive error. + +When we use mixed dimensions in a WKT geometry, the parser strips +any dimension which is not present in every coordinate. +""" + +import pytest + +import shapely +from shapely import wkt +from shapely.errors import GEOSException +from shapely.geometry import LineString, Polygon, shape + +geojson_cases = [ + {"type": "LineString", "coordinates": [[1, 1, 1], [2, 2]]}, + # Specific test case from #869 + { + "type": "Polygon", + "coordinates": [ + [ + [55.12916764533149, 24.980385694214384, 2.5], + [55.13098248044217, 24.979828079961905], + [55.13966519231666, 24.97801442415322], + [55.13966563924936, 24.97801442415322], + [55.14139286840762, 24.982307444496097], + [55.14169331277646, 24.983717465495562], + [55.14203489144224, 24.985419446276566, 2.5], + [55.14180327151276, 24.98428602667792, 2.5], + [55.14170091915952, 24.984242720177235, 2.5], + [55.14122966992623, 24.984954809433702, 2.5], + [55.14134021791831, 24.985473928648396, 2.5], + [55.141405876161286, 24.986090184809793, 2.5], + [55.141361358941225, 24.986138101357326, 2.5], + [55.14093322994411, 24.986218753894093, 2.5], + [55.140897653420964, 24.986214283545635, 2.5], + [55.14095492976058, 24.9863027591922, 2.5], + [55.140900447388745, 24.98628436557094, 2.5], + [55.140867059473706, 24.98628869622101, 2.5], + [55.14089155325796, 24.986402364143782, 2.5], + [55.14090938808566, 24.986479011993385, 2.5], + [55.140943893587824, 24.986471188883584, 2.5], + [55.1410161176551, 24.9864174050037, 2.5], + [55.140996932409635, 24.986521806266644, 2.5], + [55.14163554031332, 24.986910400619593, 2.5], + [55.14095781686062, 24.987033474900578, 2.5], + [55.14058258698692, 24.98693261266349, 2.5], + [55.14032624044253, 24.98747538747211, 2.5], + [55.14007240846915, 24.988001119077232, 2.5], + [55.14013122149105, 24.98831115636925, 2.5], + [55.13991827457961, 24.98834356639557, 2.5], + [55.139779460946755, 24.988254625087706, 2.5], + [55.13974742344948, 24.988261377176524, 2.5], + [55.139515198160304, 24.98841811876934, 2.5], + [55.13903617238334, 24.98817914139135, 2.5], + [55.1391330764994, 24.988660542040925, 2.5], + [55.13914369357698, 24.989438289540374, 2.5], + [55.136431216517785, 24.98966711550207, 2.0], + [55.13659028641709, 24.99041706302204, 2.0], + [55.1355852030721, 24.990933481401207, 2.5], + [55.13535549235394, 24.99110470506038, 2.5], + [55.13512578163577, 24.99127592871955, 2.5], + [55.129969653784556, 24.991440074326995, 2.5], + [55.130221623112746, 24.988070688875112, 2.5], + [55.130451333830905, 24.98789946521594, 2.5], + [55.13089208224919, 24.98742639990359, 2.5], + [55.132177586827666, 24.989003408454433, 2.5], + [55.13238862452779, 24.988701566801254, 2.5], + [55.132482594977674, 24.988501518707757, 2.5], + [55.132525994610624, 24.988048802794115, 2.5], + [55.13249018525683, 24.987180623870653, 2.5], + [55.13253358488978, 24.986727907957015, 2.5], + [55.1322761673244, 24.985827132742713, 2.5], + [55.13163341503516, 24.98503862846729, 2.5], + [55.131514764536504, 24.984469124700183, 2.5], + [55.131275600894, 24.983796337257242, 2.0], + [55.13066865795855, 24.98387601190528, 2.0], + [55.13026930682963, 24.981537228037503, 2.0], + [55.130260412698846, 24.981495691049748, 2.0], + [55.13025151856806, 24.981454154061993, 2.0], + [55.13022925995803, 24.98096497686874, 2.5], + [55.12984453059386, 24.9804285816199, 2.5], + [55.129998291954365, 24.98021419115843, 2.5], + [55.12916764533149, 24.980385694214384, 2.5], + ] + ], + }, +] + + +direct_cases = [ + (LineString, [[[0, 0, 0], [1, 1]]]), + (Polygon, [[[0, 0, 0], [1, 1, 0], [1, 1], [0, 1, 0], [0, 0, 0]]]), + # Specific test case from #869 + ( + Polygon, + [ + [ + [55.12916764533149, 24.980385694214384, 2.5], + [55.13098248044217, 24.979828079961905], + [55.13966519231666, 24.97801442415322], + [55.13966563924936, 24.97801442415322], + [55.14139286840762, 24.982307444496097], + [55.14169331277646, 24.983717465495562], + [55.14203489144224, 24.985419446276566, 2.5], + [55.14180327151276, 24.98428602667792, 2.5], + [55.14170091915952, 24.984242720177235, 2.5], + [55.14122966992623, 24.984954809433702, 2.5], + [55.14134021791831, 24.985473928648396, 2.5], + [55.141405876161286, 24.986090184809793, 2.5], + [55.141361358941225, 24.986138101357326, 2.5], + [55.14093322994411, 24.986218753894093, 2.5], + [55.140897653420964, 24.986214283545635, 2.5], + [55.14095492976058, 24.9863027591922, 2.5], + [55.140900447388745, 24.98628436557094, 2.5], + [55.140867059473706, 24.98628869622101, 2.5], + [55.14089155325796, 24.986402364143782, 2.5], + [55.14090938808566, 24.986479011993385, 2.5], + [55.140943893587824, 24.986471188883584, 2.5], + [55.1410161176551, 24.9864174050037, 2.5], + [55.140996932409635, 24.986521806266644, 2.5], + [55.14163554031332, 24.986910400619593, 2.5], + [55.14095781686062, 24.987033474900578, 2.5], + [55.14058258698692, 24.98693261266349, 2.5], + [55.14032624044253, 24.98747538747211, 2.5], + [55.14007240846915, 24.988001119077232, 2.5], + [55.14013122149105, 24.98831115636925, 2.5], + [55.13991827457961, 24.98834356639557, 2.5], + [55.139779460946755, 24.988254625087706, 2.5], + [55.13974742344948, 24.988261377176524, 2.5], + [55.139515198160304, 24.98841811876934, 2.5], + [55.13903617238334, 24.98817914139135, 2.5], + [55.1391330764994, 24.988660542040925, 2.5], + [55.13914369357698, 24.989438289540374, 2.5], + [55.136431216517785, 24.98966711550207, 2.0], + [55.13659028641709, 24.99041706302204, 2.0], + [55.1355852030721, 24.990933481401207, 2.5], + [55.13535549235394, 24.99110470506038, 2.5], + [55.13512578163577, 24.99127592871955, 2.5], + [55.129969653784556, 24.991440074326995, 2.5], + [55.130221623112746, 24.988070688875112, 2.5], + [55.130451333830905, 24.98789946521594, 2.5], + [55.13089208224919, 24.98742639990359, 2.5], + [55.132177586827666, 24.989003408454433, 2.5], + [55.13238862452779, 24.988701566801254, 2.5], + [55.132482594977674, 24.988501518707757, 2.5], + [55.132525994610624, 24.988048802794115, 2.5], + [55.13249018525683, 24.987180623870653, 2.5], + [55.13253358488978, 24.986727907957015, 2.5], + [55.1322761673244, 24.985827132742713, 2.5], + [55.13163341503516, 24.98503862846729, 2.5], + [55.131514764536504, 24.984469124700183, 2.5], + [55.131275600894, 24.983796337257242, 2.0], + [55.13066865795855, 24.98387601190528, 2.0], + [55.13026930682963, 24.981537228037503, 2.0], + [55.130260412698846, 24.981495691049748, 2.0], + [55.13025151856806, 24.981454154061993, 2.0], + [55.13022925995803, 24.98096497686874, 2.5], + [55.12984453059386, 24.9804285816199, 2.5], + [55.129998291954365, 24.98021419115843, 2.5], + [55.12916764533149, 24.980385694214384, 2.5], + ] + ], + ), +] + + +wkt_cases = [ + # preserve 3rd dimension + ("MULTIPOINT (1 1 1, 2 2)", "MULTIPOINT Z (1 1 1, 2 2 0)"), + ("MULTIPOINT (1 1, 2 2 2)", "MULTIPOINT Z (1 1 0, 2 2 2)"), + ("LINESTRING (1 1 1, 2 2)", "LINESTRING Z (1 1 1, 2 2 0)"), + ( + "POLYGON ((0 0 0, 1 0 0, 1 1, 0 1 0, 0 0 0))", + "POLYGON Z ((0 0 0, 1 0 0, 1 1 0, 0 1 0, 0 0 0))", + ), + # drop 3rd dimension + ("LINESTRING (1 1, 2 2 2)", "LINESTRING (1 1, 2 2)"), + ("POLYGON ((0 0, 1 0 1, 1 1, 0 1, 0 0))", "POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))"), +] + + +@pytest.mark.filterwarnings("ignore:Creating an ndarray from ragged nested sequences:") +@pytest.mark.parametrize("geojson", geojson_cases) +def test_create_from_geojson(geojson): + # exact error depends on numpy version + with pytest.raises((ValueError, TypeError)) as exc: + shape(geojson).wkt + assert exc.match( + "Inconsistent coordinate dimensionality|Input operand 0 does not have enough " + "dimensions|ufunc 'linestrings' not supported for the input types|setting an " + "array element with a sequence. The requested array has an inhomogeneous shape" + ) + + +@pytest.mark.filterwarnings("ignore:Creating an ndarray from ragged nested sequences:") +@pytest.mark.parametrize("constructor, args", direct_cases) +def test_create_directly(constructor, args): + with pytest.raises((ValueError, TypeError)) as exc: + constructor(*args) + assert exc.match( + "Inconsistent coordinate dimensionality|Input operand 0 does not have enough " + "dimensions|ufunc 'linestrings' not supported for the input types|setting an " + "array element with a sequence. The requested array has an inhomogeneous shape" + ) + + +@pytest.mark.parametrize("wkt_geom,expected", wkt_cases) +def test_create_from_wkt(wkt_geom, expected): + if shapely.geos_version >= (3, 12, 0): + # https://github.com/shapely/shapely/issues/1541 + with pytest.raises(GEOSException): + wkt.loads(wkt_geom) + else: + geom = wkt.loads(wkt_geom) + assert geom.wkt == expected diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_delaunay.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_delaunay.py new file mode 100644 index 0000000000000000000000000000000000000000..2f21b2211821c65e75c93b1e4f3d65707bb73f24 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_delaunay.py @@ -0,0 +1,32 @@ +import unittest + +from shapely.geometry import LineString, Point, Polygon +from shapely.ops import triangulate + + +class DelaunayTriangulation(unittest.TestCase): + """ + Only testing the number of triangles and their type here. + This doesn't actually test the points in the resulting geometries. + + """ + + def setUp(self): + self.p = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) + + def test_polys(self): + polys = triangulate(self.p) + assert len(polys) == 2 + for p in polys: + assert isinstance(p, Polygon) + + def test_lines(self): + polys = triangulate(self.p, edges=True) + assert len(polys) == 5 + for p in polys: + assert isinstance(p, LineString) + + def test_point(self): + p = Point(1, 1) + polys = triangulate(p) + assert len(polys) == 0 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_empty_polygons.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_empty_polygons.py new file mode 100644 index 0000000000000000000000000000000000000000..a2caff758951be30b5d42ba7be7592ecfebec950 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_empty_polygons.py @@ -0,0 +1,22 @@ +from shapely.geometry import MultiPolygon, Point, Polygon + + +def test_empty_polygon(): + """No constructor arg makes an empty polygon geometry.""" + assert Polygon().is_empty + + +def test_empty_multipolygon(): + """No constructor arg makes an empty multipolygon geometry.""" + assert MultiPolygon().is_empty + + +def test_multipolygon_empty_polygon(): + """An empty polygon passed to MultiPolygon() makes an empty + multipolygon geometry.""" + assert MultiPolygon([Polygon()]).is_empty + + +def test_multipolygon_empty_among_polygon(): + """An empty polygon passed to MultiPolygon() is ignored.""" + assert len(MultiPolygon([Point(0, 0).buffer(1.0), Polygon()]).geoms) == 1 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_equality.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_equality.py new file mode 100644 index 0000000000000000000000000000000000000000..32aae55aa6da0ba08d4cec289940c4dd35a4999b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_equality.py @@ -0,0 +1,24 @@ +from shapely import Point, Polygon + + +def test_equals_exact(): + p1 = Point(1.0, 1.0) + p2 = Point(2.0, 2.0) + p3 = Point(1.0, 1.0 + 1e-7) + assert not p1.equals(p2) + assert not p1.equals_exact(p2, 0.001) + assert not p1.equals_exact(p3) + assert p1.equals_exact(p3, 1e-6) + + # test polygons + shell = [(10, 10), (10, -10), (-10, -10), (-10, 10)] + holes = [[(1, 1), (1, -1), (-1, -1), (-1, 1)]] + p1 = Polygon(shell, holes) + p2 = Polygon(shell, holes=[holes[0][::-1]]) + assert p1.equals(p2) + assert not p1.equals_exact(p2, 1e-5) + assert p1.equals_exact(p2, 1e-5, normalize=True) + + hole2 = [(1, 1), (1, -1), (-1, -1), (-1, 1.01)] + p3 = Polygon(shell, holes=[hole2]) + assert not p1.equals_exact(p3, 1e-5) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_geointerface.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_geointerface.py new file mode 100644 index 0000000000000000000000000000000000000000..326a8d694cf22eca7b873df17f85e1843f1ababf --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_geointerface.py @@ -0,0 +1,118 @@ +import unittest + +from shapely import wkt +from shapely.geometry import shape +from shapely.geometry.linestring import LineString +from shapely.geometry.multilinestring import MultiLineString +from shapely.geometry.multipoint import MultiPoint +from shapely.geometry.multipolygon import MultiPolygon +from shapely.geometry.polygon import LinearRing, Polygon + + +class GeoThing: + def __init__(self, d): + self.__geo_interface__ = d + + +class GeoInterfaceTestCase(unittest.TestCase): + def test_geointerface(self): + # Convert a dictionary + d = {"type": "Point", "coordinates": (0.0, 0.0)} + geom = shape(d) + assert geom.geom_type == "Point" + assert tuple(geom.coords) == ((0.0, 0.0),) + + # Convert an object that implements the geo protocol + geom = None + thing = GeoThing({"type": "Point", "coordinates": (0.0, 0.0)}) + geom = shape(thing) + assert geom.geom_type == "Point" + assert tuple(geom.coords) == ((0.0, 0.0),) + + # Check line string + geom = shape({"type": "LineString", "coordinates": ((-1.0, -1.0), (1.0, 1.0))}) + assert isinstance(geom, LineString) + assert tuple(geom.coords) == ((-1.0, -1.0), (1.0, 1.0)) + + # Check linearring + geom = shape( + { + "type": "LinearRing", + "coordinates": ( + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (2.0, -1.0), + (0.0, 0.0), + ), + } + ) + assert isinstance(geom, LinearRing) + assert tuple(geom.coords) == ( + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (2.0, -1.0), + (0.0, 0.0), + ) + + # polygon + geom = shape( + { + "type": "Polygon", + "coordinates": ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (2.0, -1.0), (0.0, 0.0)), + ((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1), (0.1, 0.1)), + ), + } + ) + assert isinstance(geom, Polygon) + assert tuple(geom.exterior.coords) == ( + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (2.0, -1.0), + (0.0, 0.0), + ) + assert len(geom.interiors) == 1 + + # multi point + geom = shape({"type": "MultiPoint", "coordinates": ((1.0, 2.0), (3.0, 4.0))}) + assert isinstance(geom, MultiPoint) + assert len(geom.geoms) == 2 + + # multi line string + geom = shape( + {"type": "MultiLineString", "coordinates": (((0.0, 0.0), (1.0, 2.0)),)} + ) + assert isinstance(geom, MultiLineString) + assert len(geom.geoms) == 1 + + # multi polygon + geom = shape( + { + "type": "MultiPolygon", + "coordinates": [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)), + ((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1), (0.1, 0.1)), + ) + ], + } + ) + assert isinstance(geom, MultiPolygon) + assert len(geom.geoms) == 1 + + +def test_empty_wkt_polygon(): + """Confirm fix for issue #450""" + g = wkt.loads("POLYGON EMPTY") + assert g.__geo_interface__["type"] == "Polygon" + assert g.__geo_interface__["coordinates"] == () + + +def test_empty_polygon(): + """Confirm fix for issue #450""" + g = Polygon() + assert g.__geo_interface__["type"] == "Polygon" + assert g.__geo_interface__["coordinates"] == () diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_invalid_geometries.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_invalid_geometries.py new file mode 100644 index 0000000000000000000000000000000000000000..28ae504352a2b23fb9aabec458993acc9e529229 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_invalid_geometries.py @@ -0,0 +1,26 @@ +"""Test recovery from operation on invalid geometries""" + +import unittest + +import pytest + +import shapely +from shapely.errors import TopologicalError +from shapely.geometry import Polygon + + +class InvalidGeometriesTestCase(unittest.TestCase): + def test_invalid_intersection(self): + # Make a self-intersecting polygon + polygon_invalid = Polygon([(0, 0), (1, 1), (1, -1), (0, 1), (0, 0)]) + assert not polygon_invalid.is_valid + + # Intersect with a valid polygon + polygon = Polygon([(-0.5, -0.5), (-0.5, 0.5), (0.5, 0.5), (0.5, -5)]) + assert polygon.is_valid + assert polygon_invalid.intersects(polygon) + + with pytest.raises((TopologicalError, shapely.GEOSException)): + polygon_invalid.intersection(polygon) + with pytest.raises((TopologicalError, shapely.GEOSException)): + polygon.intersection(polygon_invalid) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_linear_referencing.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_linear_referencing.py new file mode 100644 index 0000000000000000000000000000000000000000..47e5c015b9aa6de91b71d942316adc16a4e7e86b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_linear_referencing.py @@ -0,0 +1,72 @@ +import unittest + +import pytest + +import shapely +from shapely.geometry import LineString, MultiLineString, Point + + +class LinearReferencingTestCase(unittest.TestCase): + def setUp(self): + self.point = Point(1, 1) + self.line1 = LineString([(0, 0), (2, 0)]) + self.line2 = LineString([(3, 0), (3, 6)]) + self.multiline = MultiLineString( + [list(self.line1.coords), list(self.line2.coords)] + ) + + def test_line1_project(self): + assert self.line1.project(self.point) == 1.0 + assert self.line1.project(self.point, normalized=True) == 0.5 + + def test_alias_project(self): + assert self.line1.line_locate_point(self.point) == 1.0 + assert self.line1.line_locate_point(self.point, normalized=True) == 0.5 + + def test_line2_project(self): + assert self.line2.project(self.point) == 1.0 + assert self.line2.project(self.point, normalized=True) == pytest.approx( + 0.16666666666, 8 + ) + + def test_multiline_project(self): + assert self.multiline.project(self.point) == 1.0 + assert self.multiline.project(self.point, normalized=True) == 0.125 + + def test_not_supported_project(self): + with pytest.raises(shapely.GEOSException, match="IllegalArgumentException"): + self.point.buffer(1.0).project(self.point) + + def test_not_on_line_project(self): + # Points that aren't on the line project to 0. + assert self.line1.project(Point(-10, -10)) == 0.0 + + def test_line1_interpolate(self): + assert self.line1.interpolate(0.5).equals(Point(0.5, 0.0)) + assert self.line1.interpolate(-0.5).equals(Point(1.5, 0.0)) + assert self.line1.interpolate(0.5, normalized=True).equals(Point(1, 0)) + assert self.line1.interpolate(-0.5, normalized=True).equals(Point(1, 0)) + + def test_alias_interpolate(self): + assert self.line1.line_interpolate_point(0.5).equals(Point(0.5, 0.0)) + assert self.line1.line_interpolate_point(-0.5).equals(Point(1.5, 0.0)) + assert self.line1.line_interpolate_point(0.5, normalized=True).equals( + Point(1, 0) + ) + assert self.line1.line_interpolate_point(-0.5, normalized=True).equals( + Point(1, 0) + ) + + def test_line2_interpolate(self): + assert self.line2.interpolate(0.5).equals(Point(3.0, 0.5)) + assert self.line2.interpolate(0.5, normalized=True).equals(Point(3, 3)) + + def test_multiline_interpolate(self): + assert self.multiline.interpolate(0.5).equals(Point(0.5, 0)) + assert self.multiline.interpolate(0.5, normalized=True).equals(Point(3.0, 2.0)) + + def test_line_ends_interpolate(self): + # Distances greater than length of the line or less than + # zero yield the line's ends. + assert self.line1.interpolate(-1000).equals(Point(0.0, 0.0)) + assert self.line1.interpolate(1000).equals(Point(2.0, 0.0)) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_linemerge.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_linemerge.py new file mode 100644 index 0000000000000000000000000000000000000000..f18f32baf60ab83f16537f718cbd5d9066114d09 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_linemerge.py @@ -0,0 +1,43 @@ +import unittest + +from shapely.geometry import LineString, MultiLineString +from shapely.ops import linemerge + + +class LineMergeTestCase(unittest.TestCase): + def test_linemerge(self): + lines = MultiLineString([[(0, 0), (1, 1)], [(2, 0), (2, 1), (1, 1)]]) + result = linemerge(lines) + assert isinstance(result, LineString) + assert not result.is_ring + assert len(result.coords) == 4 + assert result.coords[0] == (0.0, 0.0) + assert result.coords[3] == (2.0, 0.0) + + lines2 = MultiLineString([((0, 0), (1, 1)), ((0, 0), (2, 0), (2, 1), (1, 1))]) + result = linemerge(lines2) + assert result.is_ring + assert len(result.coords) == 5 + + lines3 = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + ] + result = linemerge(lines3) + assert not result.is_ring + assert len(result.coords) == 3 + assert result.coords[0] == (0.0, 1.0) + assert result.coords[2] == (1.0, 1.0) + + lines4 = [ + [(0, 0), (1, 1)], + [(0, 0), (0, 1)], + ] + assert result.equals(linemerge(lines4)) + + lines5 = [ + ((0, 0), (1, 1)), + ((1, 0), (0, 1)), + ] + result = linemerge(lines5) + assert result.geom_type == "MultiLineString" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_locale.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_locale.py new file mode 100644 index 0000000000000000000000000000000000000000..85221200262268fd25e7f6267d4b246e9b23e32c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_locale.py @@ -0,0 +1,54 @@ +"""Test locale independence of WKT""" + +import locale +import sys +import unittest + +from shapely.wkt import dumps, loads + +# Set locale to one that uses a comma as decimal separator +# TODO: try a few other common locales +if sys.platform == "win32": + test_locales = {"Portuguese": "portuguese_brazil", "Italian": "italian_italy"} +else: + test_locales = { + "Portuguese": "pt_BR.UTF-8", + "Italian": "it_IT.UTF-8", + } + +do_test_locale = False + + +def setUpModule(): + global do_test_locale + for name in test_locales: + try: + test_locale = test_locales[name] + locale.setlocale(locale.LC_ALL, test_locale) + do_test_locale = True + break + except Exception: + pass + if not do_test_locale: + raise unittest.SkipTest("test locale not found") + + +def tearDownModule(): + if sys.platform == "win32" or sys.version_info[0:2] >= (3, 11): + locale.setlocale(locale.LC_ALL, "") + else: + # Deprecated since version 3.11, will be removed in version 3.13 + locale.resetlocale() + + +class LocaleTestCase(unittest.TestCase): + # @unittest.skipIf(not do_test_locale, 'test locale not found') + + def test_wkt_locale(self): + # Test reading and writing + p = loads("POINT (0.0 0.0)") + assert p.x == 0.0 + assert p.y == 0.0 + wkt = dumps(p) + assert wkt.startswith("POINT") + assert "," not in wkt diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_make_valid.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_make_valid.py new file mode 100644 index 0000000000000000000000000000000000000000..7da01b7d32938db774387bd3bd77a5d2313cae3a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_make_valid.py @@ -0,0 +1,15 @@ +from shapely.geometry import Polygon +from shapely.validation import make_valid + + +def test_make_valid_invalid_input(): + geom = Polygon([(0, 0), (0, 2), (1, 1), (2, 2), (2, 0), (1, 1), (0, 0)]) + valid = make_valid(geom) + assert len(valid.geoms) == 2 + assert all(geom.geom_type == "Polygon" for geom in valid.geoms) + + +def test_make_valid_input(): + geom = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + valid = make_valid(geom) + assert id(valid) == id(geom) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_mapping.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..1e730932245342ab35975f1a6613b3d53edd11b5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_mapping.py @@ -0,0 +1,14 @@ +import unittest + +from shapely.geometry import Point, Polygon, mapping + + +class MappingTestCase(unittest.TestCase): + def test_point(self): + m = mapping(Point(0, 0)) + assert m["type"] == "Point" + assert m["coordinates"] == (0.0, 0.0) + + def test_empty_polygon(self): + """Empty polygons will round trip without error""" + assert mapping(Polygon()) is not None diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_minimum_clearance.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_minimum_clearance.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb8cf57b5646417acfdba62a8c94dc4f772fac9 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_minimum_clearance.py @@ -0,0 +1,30 @@ +""" +Tests for the minimum clearance property. +""" + +import math + +from shapely.wkt import loads as load_wkt + + +def test_point(): + point = load_wkt("POINT (0 0)") + assert point.minimum_clearance == math.inf + + +def test_linestring(): + line = load_wkt("LINESTRING (0 0, 1 1, 2 2)") + assert round(line.minimum_clearance, 6) == 1.414214 + + +def test_simple_polygon(): + poly = load_wkt("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))") + assert poly.minimum_clearance == 1.0 + + +def test_more_complicated_polygon(): + poly = load_wkt( + "POLYGON ((20 20, 34 124, 70 140, 130 130, 70 100, 110 70, 170 20, 90 10, " + "20 20))" + ) + assert round(poly.minimum_clearance, 6) == 35.777088 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_ndarrays.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_ndarrays.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b9a4aa762cced22edf5a682253ee053826c09c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_ndarrays.py @@ -0,0 +1,42 @@ +# Tests of support for Numpy ndarrays. See +# https://github.com/sgillies/shapely/issues/26 for discussion. + +import unittest +from functools import reduce + +import numpy as np + +from shapely import geometry + + +class TransposeTestCase(unittest.TestCase): + def test_multipoint(self): + arr = np.array([[1.0, 1.0, 2.0, 2.0, 1.0], [3.0, 4.0, 4.0, 3.0, 3.0]]) + tarr = arr.T + shape = geometry.MultiPoint(tarr) + coords = reduce(lambda x, y: x + y, [list(g.coords) for g in shape.geoms]) + assert coords == [(1.0, 3.0), (1.0, 4.0), (2.0, 4.0), (2.0, 3.0), (1.0, 3.0)] + + def test_linestring(self): + a = np.array([[1.0, 1.0, 2.0, 2.0, 1.0], [3.0, 4.0, 4.0, 3.0, 3.0]]) + t = a.T + s = geometry.LineString(t) + assert list(s.coords) == [ + (1.0, 3.0), + (1.0, 4.0), + (2.0, 4.0), + (2.0, 3.0), + (1.0, 3.0), + ] + + def test_polygon(self): + a = np.array([[1.0, 1.0, 2.0, 2.0, 1.0], [3.0, 4.0, 4.0, 3.0, 3.0]]) + t = a.T + s = geometry.Polygon(t) + assert list(s.exterior.coords) == [ + (1.0, 3.0), + (1.0, 4.0), + (2.0, 4.0), + (2.0, 3.0), + (1.0, 3.0), + ] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_nearest.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_nearest.py new file mode 100644 index 0000000000000000000000000000000000000000..48f058d871d9c26aac99e25388afb06394592ea5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_nearest.py @@ -0,0 +1,18 @@ +import unittest + +import pytest + +from shapely.geometry import Point +from shapely.ops import nearest_points + + +class Nearest(unittest.TestCase): + def test_nearest(self): + first, second = nearest_points( + Point(0, 0).buffer(1.0), + Point(3, 0).buffer(1.0), + ) + assert first.x == pytest.approx(1.0) + assert second.x == pytest.approx(2.0) + assert first.y == pytest.approx(0.0) + assert second.y == pytest.approx(0.0) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_operations.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..8b8b732f6c205ab22b1e10dd4137ee985bce6491 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_operations.py @@ -0,0 +1,124 @@ +import unittest + +import pytest + +import shapely +from shapely import geos_version +from shapely.errors import TopologicalError +from shapely.geometry import GeometryCollection, LineString, MultiPoint, Point, Polygon +from shapely.wkt import loads + + +class OperationsTestCase(unittest.TestCase): + def test_operations(self): + point = Point(0.0, 0.0) + + # General geometry + assert point.area == 0.0 + assert point.length == 0.0 + assert point.distance(Point(-1.0, -1.0)) == pytest.approx(1.4142135623730951) + + # Topology operations + + # Envelope + assert isinstance(point.envelope, Point) + + # Intersection + assert point.intersection(Point(-1, -1)).is_empty + + # Buffer + assert isinstance(point.buffer(10.0), Polygon) + assert isinstance(point.buffer(10.0, quad_segs=32), Polygon) + + # Simplify + p = loads( + "POLYGON ((120 120, 140 199, 160 200, 180 199, 220 120, 122 122, 121 121, " + "120 120))" + ) + expected = loads( + "POLYGON ((120 120, 140 199, 160 200, 180 199, 220 120, 120 120))" + ) + s = p.simplify(10.0, preserve_topology=False) + assert s.equals_exact(expected, 0.001) + + p = loads( + "POLYGON ((80 200, 240 200, 240 60, 80 60, 80 200)," + "(120 120, 220 120, 180 199, 160 200, 140 199, 120 120))" + ) + expected = loads( + "POLYGON ((80 200, 240 200, 240 60, 80 60, 80 200)," + "(120 120, 220 120, 180 199, 160 200, 140 199, 120 120))" + ) + s = p.simplify(10.0, preserve_topology=True) + assert s.equals_exact(expected, 0.001) + + # Convex Hull + assert isinstance(point.convex_hull, Point) + + # Differences + assert isinstance(point.difference(Point(-1, 1)), Point) + + assert isinstance(point.symmetric_difference(Point(-1, 1)), MultiPoint) + + # Boundary + assert isinstance(point.boundary, GeometryCollection) + + # Union + assert isinstance(point.union(Point(-1, 1)), MultiPoint) + + assert isinstance(point.representative_point(), Point) + assert isinstance(point.point_on_surface(), Point) + assert point.representative_point() == point.point_on_surface() + + assert isinstance(point.centroid, Point) + + def test_relate(self): + # Relate + assert Point(0, 0).relate(Point(-1, -1)) == "FF0FFF0F2" + + # issue #294: should raise TopologicalError on exception + invalid_polygon = loads( + "POLYGON ((40 100, 80 100, 80 60, 40 60, 40 100), " + "(60 60, 80 60, 80 40, 60 40, 60 60))" + ) + assert not invalid_polygon.is_valid + if geos_version < (3, 13, 0): + with pytest.raises((TopologicalError, shapely.GEOSException)): + invalid_polygon.relate(invalid_polygon) + else: # resolved with RelateNG + assert invalid_polygon.relate(invalid_polygon) == "2FFF1FFF2" + + def test_hausdorff_distance(self): + point = Point(1, 1) + line = LineString([(2, 0), (2, 4), (3, 4)]) + + distance = point.hausdorff_distance(line) + assert distance == point.distance(Point(3, 4)) + + def test_interpolate(self): + # successful interpolation + test_line = LineString([(1, 1), (1, 2)]) + known_point = Point(1, 1.5) + interpolated_point = test_line.interpolate(0.5, normalized=True) + assert interpolated_point == known_point + + # Issue #653; should nog segfault for empty geometries + empty_line = loads("LINESTRING EMPTY") + assert empty_line.is_empty + interpolated_point = empty_line.interpolate(0.5, normalized=True) + assert interpolated_point.is_empty + + # invalid geometry should raise TypeError on exception + polygon = loads("POLYGON EMPTY") + with pytest.raises(TypeError, match="incorrect geometry type"): + polygon.interpolate(0.5, normalized=True) + + def test_normalize(self): + point = Point(1, 1) + result = point.normalize() + assert result == point + + line = loads("MULTILINESTRING ((1 1, 0 0), (1 1, 1 2))") + result = line.normalize() + expected = loads("MULTILINESTRING ((1 1, 1 2), (0 0, 1 1))") + assert result == expected diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_operators.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..9b47e948cf5e77ff96f58a9712561df527903d9a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_operators.py @@ -0,0 +1,60 @@ +import unittest + +from shapely.geometry import LineString, MultiPoint, Point, Polygon + + +class OperatorsTestCase(unittest.TestCase): + def test_point(self): + point = Point(0, 0) + point2 = Point(-1, 1) + assert point.union(point2).equals(point | point2) + assert (point & point2).is_empty + assert point.equals(point - point2) + assert point.symmetric_difference(point2).equals(point ^ point2) + assert point != point2 + point_dupe = Point(0, 0) + assert point, point_dupe + + def test_multipoint(self): + mp1 = MultiPoint([(0, 0), (1, 1)]) + mp1_dup = MultiPoint([(0, 0), (1, 1)]) + mp1_rev = MultiPoint([(1, 1), (0, 0)]) + mp2 = MultiPoint([(0, 0), (1, 1), (2, 2)]) + mp3 = MultiPoint([(0, 0), (1, 1), (2, 3)]) + + assert mp1 == mp1_dup + assert mp1 != mp1_rev + assert mp1 != mp2 + assert mp2 != mp3 + + p = Point(0, 0) + mp = MultiPoint([(0, 0)]) + assert p != mp + assert mp != p + + def test_polygon(self): + shell = ((0, 0), (3, 0), (3, 3), (0, 3)) + hole = ((1, 1), (2, 1), (2, 2), (1, 2)) + p_solid = Polygon(shell) + p2_solid = Polygon(shell) + p_hole = Polygon(shell, holes=[hole]) + p2_hole = Polygon(shell, holes=[hole]) + + assert p_solid == p2_solid + assert p_hole == p2_hole + assert p_solid != p_hole + + shell2 = ((-5, 2), (10.5, 3), (7, 3)) + p3_hole = Polygon(shell2, holes=[hole]) + assert p_hole != p3_hole + + def test_linestring(self): + line1 = LineString([(0, 0), (1, 1), (2, 2)]) + line2 = LineString([(0, 0), (2, 2)]) + line2_dup = LineString([(0, 0), (2, 2)]) + # .equals() indicates these are the same + assert line1.equals(line2) + # but != indicates these are different + assert line1 != line2 + # but dupes are the same with == + assert line2 == line2_dup diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_orient.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_orient.py new file mode 100644 index 0000000000000000000000000000000000000000..e18f2987be23653f7407d907190ecb4b64532a90 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_orient.py @@ -0,0 +1,92 @@ +import unittest + +from numpy.testing import assert_array_equal + +from shapely.geometry import ( + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.ops import orient + + +class OrientTestCase(unittest.TestCase): + def test_point(self): + point = Point(0, 0) + assert orient(point, 1) == point + assert orient(point, -1) == point + + def test_multipoint(self): + multipoint = MultiPoint([(0, 0), (1, 1)]) + assert orient(multipoint, 1) == multipoint + assert orient(multipoint, -1) == multipoint + + def test_linestring(self): + linestring = LineString([(0, 0), (1, 1)]) + assert orient(linestring, 1) == linestring + assert orient(linestring, -1) == linestring + + def test_multilinestring(self): + multilinestring = MultiLineString([[(0, 0), (1, 1)], [(1, 0), (0, 1)]]) + assert orient(multilinestring, 1) == multilinestring + assert orient(multilinestring, -1) == multilinestring + + def test_linearring(self): + linearring = LinearRing([(0, 0), (0, 1), (1, 0)]) + assert orient(linearring, 1) == linearring + assert orient(linearring, -1) == linearring + + def test_empty_polygon(self): + polygon = Polygon() + assert orient(polygon) == polygon + + def test_polygon(self): + polygon = Polygon([(0, 0), (0, 1), (1, 0)]) + polygon_reversed = Polygon(polygon.exterior.coords[::-1]) + assert (orient(polygon, 1)) == polygon_reversed + assert (orient(polygon, -1)) == polygon + + def test_multipolygon(self): + polygon1 = Polygon([(0, 0), (0, 1), (1, 0)]) + polygon2 = Polygon([(1, 0), (2, 0), (2, 1)]) + polygon1_reversed = Polygon(polygon1.exterior.coords[::-1]) + polygon2_reversed = Polygon(polygon2.exterior.coords[::-1]) + multipolygon = MultiPolygon([polygon1, polygon2]) + assert not polygon1.exterior.is_ccw + assert polygon2.exterior.is_ccw + assert orient(multipolygon, 1) == MultiPolygon([polygon1_reversed, polygon2]) + assert orient(multipolygon, -1) == MultiPolygon([polygon1, polygon2_reversed]) + + def test_geometrycollection(self): + polygon = Polygon([(0, 0), (0, 1), (1, 0)]) + polygon_reversed = Polygon(polygon.exterior.coords[::-1]) + collection = GeometryCollection([polygon]) + assert orient(collection, 1) == GeometryCollection([polygon_reversed]) + assert orient(collection, -1) == GeometryCollection([polygon]) + + def test_polygon_with_holes(self): + ring_cw = LinearRing([(0, 0), (0, 1), (1, 1), (0, 0)]) + ring_cw2 = LinearRing([(0, 0), (0, 3), (3, 3), (0, 0)]) + ring_ccw = LinearRing([(0, 0), (1, 1), (0, 1), (0, 0)]) + ring_ccw2 = LinearRing([(0, 0), (2, 2), (0, 2), (0, 0)]) + + polygon_with_holes_mixed = Polygon( + ring_ccw, [ring_cw, ring_ccw2, ring_cw2, ring_ccw] + ) + polygon_with_holes_ccw = Polygon( + ring_ccw, [ring_cw, ring_ccw2.reverse(), ring_cw2, ring_ccw.reverse()] + ) + + assert_array_equal(orient(polygon_with_holes_ccw, 1), polygon_with_holes_ccw) + assert_array_equal( + orient(polygon_with_holes_ccw, -1), polygon_with_holes_ccw.reverse() + ) + assert_array_equal(orient(polygon_with_holes_mixed, 1), polygon_with_holes_ccw) + assert_array_equal( + orient(polygon_with_holes_mixed, -1), polygon_with_holes_ccw.reverse() + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_parallel_offset.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_parallel_offset.py new file mode 100644 index 0000000000000000000000000000000000000000..26ae927c28ca7911a45d4870feaa2675ae8e8781 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_parallel_offset.py @@ -0,0 +1,60 @@ +import unittest + +import pytest + +from shapely.geometry import LinearRing, LineString +from shapely.testing import assert_geometries_equal + + +@pytest.mark.parametrize("distance", [float("nan"), float("inf")]) +def test_non_finite_distance(distance): + g = LineString([(0, 0), (10, 0)]) + with pytest.raises(ValueError, match="distance must be finite"): + g.parallel_offset(distance) + + +class OperationsTestCase(unittest.TestCase): + def test_parallel_offset_linestring(self): + line1 = LineString([(0, 0), (10, 0)]) + left = line1.parallel_offset(5, "left") + assert_geometries_equal(left, LineString([(0, 5), (10, 5)])) + right = line1.parallel_offset(5, "right") + assert_geometries_equal(right, LineString([(10, -5), (0, -5)]), normalize=True) + right = line1.parallel_offset(-5, "left") + assert_geometries_equal(right, LineString([(10, -5), (0, -5)]), normalize=True) + left = line1.parallel_offset(-5, "right") + assert_geometries_equal(left, LineString([(0, 5), (10, 5)])) + + # by default, parallel_offset is right-handed + assert_geometries_equal(line1.parallel_offset(5), right) + + line2 = LineString([(0, 0), (5, 0), (5, -5)]) + assert_geometries_equal( + line2.parallel_offset(2, "left", join_style=3), + LineString([(0, 2), (5, 2), (7, 0), (7, -5)]), + ) + assert_geometries_equal( + line2.parallel_offset(2, "left", join_style=2), + LineString([(0, 2), (7, 2), (7, -5)]), + ) + # offset_curve alias + assert_geometries_equal( + line1.offset_curve(2, quad_segs=10), + line1.parallel_offset(2, "left", resolution=10), + ) + assert_geometries_equal( + line1.offset_curve(-2, join_style="mitre"), + line1.parallel_offset(2, "right", join_style=2), + ) + + def test_parallel_offset_linear_ring(self): + lr1 = LinearRing([(0, 0), (5, 0), (5, 5), (0, 5), (0, 0)]) + assert_geometries_equal( + lr1.parallel_offset(2, "left", resolution=1), + LineString([(2, 2), (3, 2), (3, 3), (2, 3), (2, 2)]), + ) + # offset_curve alias + assert_geometries_equal( + lr1.offset_curve(2, quad_segs=1), + lr1.parallel_offset(2, "left", resolution=1), + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_persist.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_persist.py new file mode 100644 index 0000000000000000000000000000000000000000..736e974f835067e7e00fa83a1ec508f8304103c6 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_persist.py @@ -0,0 +1,48 @@ +"""Persistence tests""" + +import pickle +import struct +import unittest + +from shapely import wkb, wkt +from shapely.geometry import Point + + +class PersistTestCase(unittest.TestCase): + def test_pickle(self): + p = Point(0.0, 0.0) + data = pickle.dumps(p) + q = pickle.loads(data) + assert q.equals(p) + + def test_wkb(self): + p = Point(0.0, 0.0) + wkb_big_endian = wkb.dumps(p, big_endian=True) + wkb_little_endian = wkb.dumps(p, big_endian=False) + # Regardless of byte order, loads ought to correctly recover the + # geometry + assert p.equals(wkb.loads(wkb_big_endian)) + assert p.equals(wkb.loads(wkb_little_endian)) + + def test_wkb_dumps_endianness(self): + p = Point(0.5, 2.0) + wkb_big_endian = wkb.dumps(p, big_endian=True) + wkb_little_endian = wkb.dumps(p, big_endian=False) + assert wkb_big_endian != wkb_little_endian + # According to WKB specification in section 3.3 of OpenGIS + # Simple Features Specification for SQL, revision 1.1, the + # first byte of a WKB representation indicates byte order. + # Big-endian is 0, little-endian is 1. + assert wkb_big_endian[0] == 0 + assert wkb_little_endian[0] == 1 + # Check that the doubles (0.5, 2.0) are in correct byte order + double_size = struct.calcsize("d") + assert wkb_big_endian[(-2 * double_size) :] == struct.pack(">2d", p.x, p.y) + assert wkb_little_endian[(-2 * double_size) :] == struct.pack("<2d", p.x, p.y) + + def test_wkt(self): + p = Point(0.0, 0.0) + text = wkt.dumps(p) + assert text.startswith("POINT") + pt = wkt.loads(text) + assert pt.equals(p) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_pickle.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..0b2e438051a0efa8bc5f067664de8d05e6951c5b --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_pickle.py @@ -0,0 +1,81 @@ +import pathlib +import pickle +import warnings +from pickle import HIGHEST_PROTOCOL, dumps, loads + +import pytest + +import shapely +from shapely import wkt +from shapely.geometry import ( + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, + box, +) + +HERE = pathlib.Path(__file__).parent + + +TEST_DATA = { + "point2d": Point([(1.0, 2.0)]), + "point3d": Point([(1.0, 2.0, 3.0)]), + "linestring": LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]), + "linearring": LinearRing([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]), + "polygon": Polygon([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]), + "multipoint": MultiPoint([(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)]), + "multilinestring": MultiLineString( + [[(0.0, 0.0), (1.0, 1.0)], [(1.0, 2.0), (3.0, 3.0)]] + ), + "multipolygon": MultiPolygon([box(0, 0, 1, 1), box(2, 2, 3, 3)]), + "geometrycollection": GeometryCollection([Point(1.0, 2.0), box(0, 0, 1, 1)]), + "emptypoint": wkt.loads("POINT EMPTY"), + "emptypolygon": wkt.loads("POLYGON EMPTY"), +} +TEST_NAMES, TEST_GEOMS = zip(*TEST_DATA.items()) + + +@pytest.mark.parametrize("geom1", TEST_GEOMS, ids=TEST_NAMES) +def test_pickle_round_trip(geom1): + data = dumps(geom1, HIGHEST_PROTOCOL) + with warnings.catch_warnings(): + warnings.simplefilter("error") + geom2 = loads(data) + assert geom2.has_z == geom1.has_z + assert type(geom2) is type(geom1) + assert geom2.geom_type == geom1.geom_type + assert geom2.wkt == geom1.wkt + + +@pytest.mark.parametrize( + "fname", (HERE / "data").glob("*.pickle"), ids=lambda fname: fname.name +) +def test_unpickle_pre_20(fname): + from shapely.testing import assert_geometries_equal + + geom_type = fname.name.split("_")[0] + expected = TEST_DATA[geom_type] + + with open(fname, "rb") as f: + with pytest.warns(UserWarning, match="may be removed in a future version"): + result = pickle.load(f) + + assert_geometries_equal(result, expected) + + +if __name__ == "__main__": + datadir = HERE / "data" + datadir.mkdir(exist_ok=True) + + shapely_version = shapely.__version__ + print(shapely_version) + print(shapely.geos_version) + + for name, geom in TEST_DATA.items(): + with open(datadir / f"{name}_{shapely_version}.pickle", "wb") as f: + pickle.dump(geom, f) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_polygonize.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_polygonize.py new file mode 100644 index 0000000000000000000000000000000000000000..91477a04e9ca759a04152a866ceafa0a145fb109 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_polygonize.py @@ -0,0 +1,43 @@ +import unittest + +from shapely.geometry import LineString, Point, Polygon +from shapely.geometry.base import dump_coords +from shapely.ops import polygonize, polygonize_full + + +class PolygonizeTestCase(unittest.TestCase): + def test_polygonize(self): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + LineString([(1, 1), (1, 0)]), + LineString([(1, 0), (0, 0)]), + LineString([(5, 5), (6, 6)]), + Point(0, 0), + ] + result = list(polygonize(lines)) + assert all(isinstance(x, Polygon) for x in result) + + def test_polygonize_full(self): + lines2 = [ + [(0, 0), (1, 1)], + [(0, 0), (0, 1)], + [(0, 1), (1, 1)], + [(1, 1), (1, 0)], + [(1, 0), (0, 0)], + [(5, 5), (6, 6)], + [(1, 1), (100, 100)], + ] + + result2, cuts, dangles, invalids = polygonize_full(lines2) + assert len(result2.geoms) == 2 + assert all(isinstance(x, Polygon) for x in result2.geoms) + assert list(cuts.geoms) == [] + assert all(isinstance(x, LineString) for x in dangles.geoms) + + assert dump_coords(dangles) == [ + [(1.0, 1.0), (100.0, 100.0)], + [(5.0, 5.0), (6.0, 6.0)], + ] + assert list(invalids.geoms) == [] diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_polylabel.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_polylabel.py new file mode 100644 index 0000000000000000000000000000000000000000..e13200ab80b5ceffef3f6ff5431a4038a667eeb0 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_polylabel.py @@ -0,0 +1,85 @@ +import unittest + +import pytest + +import shapely +from shapely.algorithms.polylabel import polylabel +from shapely.geometry import LineString, Point, Polygon + + +class PolylabelTestCase(unittest.TestCase): + def test_polylabel(self): + """ + Finds pole of inaccessibility for a polygon with a tolerance of 10 + + """ + polygon = LineString( + [(0, 0), (50, 200), (100, 100), (20, 50), (-100, -20), (-150, -200)] + ).buffer(100) + label = polylabel(polygon, tolerance=0.001) + expected = Point(59.733, 111.330) + assert expected.equals_exact(label, 1e-3) + + def test_concave_polygon(self): + """ + Finds pole of inaccessibility for a concave polygon and ensures that + the point is inside. + + """ + concave_polygon = LineString([(500, 0), (0, 0), (0, 500), (500, 500)]).buffer( + 100 + ) + label = polylabel(concave_polygon) + assert concave_polygon.contains(label) + + def test_rectangle_special_case(self): + """ + The centroid algorithm used is vulnerable to floating point errors + and can give unexpected results for rectangular polygons. Test + that this special case is handled correctly. + https://github.com/mapbox/polylabel/issues/3 + """ + polygon = Polygon( + [ + (32.71997, -117.19310), + (32.71997, -117.21065), + (32.72408, -117.21065), + (32.72408, -117.19310), + ] + ) + label = polylabel(polygon) + if shapely.geos_version >= (3, 14, 0): + # https://github.com/libgeos/geos/issues/1265 + assert label.coords[:] == [(32.722025, -117.195155)] + elif shapely.geos_version >= (3, 12, 0): + # recent GEOS corrects for this + assert label.coords[:] == [(32.722025, -117.201875)] + else: + # older versions not + assert label.coords[:] == [(32.722025, -117.208595)] + + def test_polygon_with_hole(self): + """ + Finds pole of inaccessibility for a polygon with a hole + https://github.com/shapely/shapely/issues/817 + """ + polygon = Polygon( + shell=[(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)], + holes=[[(2, 2), (6, 2), (6, 6), (2, 6), (2, 2)]], + ) + label = polylabel(polygon, 0.05) + assert label.x == pytest.approx(7.65625) + assert label.y == pytest.approx(7.65625) + + @pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="Fails with GEOS < 3.12" + ) + def test_polygon_infinite_loop(self): + # https://github.com/shapely/shapely/issues/1836 + # corner case that caused an infinite loop in the old custom implemetation + polygon = shapely.from_wkt( + "POLYGON ((536520.0679737709 5438764.374763639, 536520.0679737704 5438764.374763602, 536520.0679737709 5438764.374763642, 536520.0679737709 5438764.374763639))" # noqa: E501 + ) + label = polylabel(polygon) + assert label.x == pytest.approx(536520.068) + assert label.y == pytest.approx(5438764.375) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_predicates.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_predicates.py new file mode 100644 index 0000000000000000000000000000000000000000..0e596605612faecfbb56afcb0ea49eb94efd3334 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_predicates.py @@ -0,0 +1,95 @@ +"""Test GEOS predicates""" + +import unittest + +import pytest + +import shapely +from shapely import geos_version +from shapely.geometry import Point, Polygon + + +class PredicatesTestCase(unittest.TestCase): + def test_binary_predicates(self): + point = Point(0.0, 0.0) + point2 = Point(2.0, 2.0) + + assert point.disjoint(Point(-1.0, -1.0)) + assert not point.touches(Point(-1.0, -1.0)) + assert not point.crosses(Point(-1.0, -1.0)) + assert not point.within(Point(-1.0, -1.0)) + assert not point.contains(Point(-1.0, -1.0)) + assert not point.equals(Point(-1.0, -1.0)) + assert not point.touches(Point(-1.0, -1.0)) + assert point.equals(Point(0.0, 0.0)) + assert point.covers(Point(0.0, 0.0)) + assert point.covered_by(Point(0.0, 0.0)) + assert not point.covered_by(point2) + assert not point2.covered_by(point) + assert not point.covers(Point(-1.0, -1.0)) + + def test_unary_predicates(self): + point = Point(0.0, 0.0) + + assert not point.is_empty + assert point.is_valid + assert point.is_simple + assert not point.is_ring + assert not point.has_z + + def test_binary_predicate_exceptions(self): + p1 = [ + (339, 346), + (459, 346), + (399, 311), + (340, 277), + (399, 173), + (280, 242), + (339, 415), + (280, 381), + (460, 207), + (339, 346), + ] + p2 = [ + (339, 207), + (280, 311), + (460, 138), + (399, 242), + (459, 277), + (459, 415), + (399, 381), + (519, 311), + (520, 242), + (519, 173), + (399, 450), + (339, 207), + ] + + g1 = Polygon(p1) + g2 = Polygon(p2) + assert not g1.is_valid + assert not g2.is_valid + if geos_version < (3, 13, 0): + with pytest.raises(shapely.GEOSException): + g1.within(g2) + else: # resolved with RelateNG + assert not g1.within(g2) + + def test_relate_pattern(self): + # a pair of partially overlapping polygons, and a nearby point + g1 = Polygon([(0, 0), (0, 1), (3, 1), (3, 0), (0, 0)]) + g2 = Polygon([(1, -1), (1, 2), (2, 2), (2, -1), (1, -1)]) + g3 = Point(5, 5) + + assert g1.relate(g2) == "212101212" + assert g1.relate_pattern(g2, "212101212") + assert g1.relate_pattern(g2, "*********") + assert g1.relate_pattern(g2, "2********") + assert g1.relate_pattern(g2, "T********") + assert not g1.relate_pattern(g2, "112101212") + assert not g1.relate_pattern(g2, "1********") + assert g1.relate_pattern(g3, "FF2FF10F2") + + # an invalid pattern should raise an exception + with pytest.raises(shapely.GEOSException, match="IllegalArgumentException"): + g1.relate_pattern(g2, "fail") diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_prepared.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_prepared.py new file mode 100644 index 0000000000000000000000000000000000000000..d29fda65ef05bbff0aa9571bde82dd309a075a85 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_prepared.py @@ -0,0 +1,65 @@ +import numpy as np +import pytest + +from shapely.geometry import Point, Polygon +from shapely.prepared import PreparedGeometry, prep + + +def test_prepared_geometry(): + polygon = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) + p = PreparedGeometry(polygon) + assert p.contains(Point(0.5, 0.5)) + assert not p.contains(Point(0.5, 1.5)) + + +def test_prep(): + polygon = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) + p = prep(polygon) + assert p.contains(Point(0.5, 0.5)) + assert not p.contains(Point(0.5, 1.5)) + + +def test_op_not_allowed(): + p = PreparedGeometry(Point(0.0, 0.0).buffer(1.0)) + with pytest.raises(TypeError): + Point(0.0, 0.0).union(p) + + +def test_predicate_not_allowed(): + p = PreparedGeometry(Point(0.0, 0.0).buffer(1.0)) + with pytest.raises(TypeError): + Point(0.0, 0.0).contains(p) + + +def test_prepared_predicates(): + # check prepared predicates give the same result as regular predicates + polygon1 = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + polygon2 = Polygon([(0.5, 0.5), (1.5, 0.5), (1.0, 1.0), (0.5, 0.5)]) + point2 = Point(0.5, 0.5) + polygon_empty = Polygon() + prepared_polygon1 = PreparedGeometry(polygon1) + for geom2 in (polygon2, point2, polygon_empty): + with np.errstate(invalid="ignore"): + assert polygon1.disjoint(geom2) == prepared_polygon1.disjoint(geom2) + assert polygon1.touches(geom2) == prepared_polygon1.touches(geom2) + assert polygon1.intersects(geom2) == prepared_polygon1.intersects(geom2) + assert polygon1.crosses(geom2) == prepared_polygon1.crosses(geom2) + assert polygon1.within(geom2) == prepared_polygon1.within(geom2) + assert polygon1.contains(geom2) == prepared_polygon1.contains(geom2) + assert polygon1.contains_properly( + geom2 + ) == prepared_polygon1.contains_properly(geom2) + assert polygon1.overlaps(geom2) == prepared_polygon1.overlaps(geom2) + + +def test_prepare_already_prepared(): + polygon = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) + prepared = prep(polygon) + # attempt to prepare an already prepared geometry with `prep` + result = prep(prepared) + assert isinstance(result, PreparedGeometry) + assert result.context is polygon + # attempt to prepare an already prepared geometry with `PreparedGeometry` + result = PreparedGeometry(prepared) + assert isinstance(result, PreparedGeometry) + assert result.context is polygon diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_products_z.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_products_z.py new file mode 100644 index 0000000000000000000000000000000000000000..96fa545067f9b8d0a7ac41d28f752211101abbf9 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_products_z.py @@ -0,0 +1,13 @@ +import unittest + +from shapely.geometry import LineString + + +class ProductZTestCase(unittest.TestCase): + def test_line_intersection(self): + line1 = LineString([(0, 0, 0), (1, 1, 1)]) + line2 = LineString([(0, 1, 1), (1, 0, 0)]) + interxn = line1.intersection(line2) + assert interxn.has_z + assert interxn._ndim == 3 + assert 0.0 <= interxn.z <= 1.0 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_shape.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..f2eb772f37a2b7be50d88e0827fae611203afad5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_shape.py @@ -0,0 +1,63 @@ +import pytest + +from shapely.geometry import MultiLineString, Point, Polygon, shape +from shapely.geometry.geo import _is_coordinates_empty + + +@pytest.mark.parametrize( + "geom", + [{"type": "Polygon", "coordinates": None}, {"type": "Polygon", "coordinates": []}], +) +def test_polygon_no_coords(geom): + assert shape(geom) == Polygon() + + +def test_polygon_empty_np_array(): + np = pytest.importorskip("numpy") + geom = {"type": "Polygon", "coordinates": np.array([])} + assert shape(geom) == Polygon() + + +def test_polygon_with_coords_list(): + geom = {"type": "Polygon", "coordinates": [[[5, 10], [10, 10], [10, 5]]]} + obj = shape(geom) + assert obj == Polygon([(5, 10), (10, 10), (10, 5)]) + + +def test_polygon_not_empty_np_array(): + np = pytest.importorskip("numpy") + geom = {"type": "Polygon", "coordinates": np.array([[[5, 10], [10, 10], [10, 5]]])} + obj = shape(geom) + assert obj == Polygon([(5, 10), (10, 10), (10, 5)]) + + +@pytest.mark.parametrize( + "geom", + [ + {"type": "MultiLineString", "coordinates": []}, + {"type": "MultiLineString", "coordinates": [[]]}, + {"type": "MultiLineString", "coordinates": None}, + ], +) +def test_multilinestring_empty(geom): + assert shape(geom) == MultiLineString() + + +@pytest.mark.parametrize("coords", [[], [[]], [[], []], None, [[[]]]]) +def test_is_coordinates_empty(coords): + assert _is_coordinates_empty(coords) + + +def test_feature_from_geo_interface(): + # https://github.com/shapely/shapely/issues/1814 + class Feature: + @property + def __geo_interface__(self): + return { + "type": "Feature", + "geometry": {"type": "Point", "coordinates": [0, 0]}, + } + + expected = Point([0, 0]) + result = shape(Feature()) + assert result == expected diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_shared_paths.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_shared_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..e7015e6c7077068f7cae5a9f579deaa29fa987fe --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_shared_paths.py @@ -0,0 +1,45 @@ +import unittest + +import pytest + +from shapely.errors import GeometryTypeError +from shapely.geometry import GeometryCollection, LineString, MultiLineString, Point +from shapely.ops import shared_paths + + +class SharedPaths(unittest.TestCase): + def test_shared_paths_forward(self): + g1 = LineString([(0, 0), (10, 0), (10, 5), (20, 5)]) + g2 = LineString([(5, 0), (15, 0)]) + result = shared_paths(g1, g2) + + assert isinstance(result, GeometryCollection) + assert len(result.geoms) == 2 + a, b = result.geoms + assert isinstance(a, MultiLineString) + assert len(a.geoms) == 1 + assert a.geoms[0].coords[:] == [(5, 0), (10, 0)] + assert b.is_empty + + def test_shared_paths_forward2(self): + g1 = LineString([(0, 0), (10, 0), (10, 5), (20, 5)]) + g2 = LineString([(15, 0), (5, 0)]) + result = shared_paths(g1, g2) + + assert isinstance(result, GeometryCollection) + assert len(result.geoms) == 2 + a, b = result.geoms + assert isinstance(b, MultiLineString) + assert len(b.geoms) == 1 + assert b.geoms[0].coords[:] == [(5, 0), (10, 0)] + assert a.is_empty + + def test_wrong_type(self): + g1 = Point(0, 0) + g2 = LineString([(5, 0), (15, 0)]) + + with pytest.raises(GeometryTypeError): + shared_paths(g1, g2) + + with pytest.raises(GeometryTypeError): + shared_paths(g2, g1) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_singularity.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_singularity.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f74b494db8bdae37aca3b0c7997aa9d6cbfa75 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_singularity.py @@ -0,0 +1,15 @@ +import unittest + +from shapely.geometry import Polygon + + +class PolygonTestCase(unittest.TestCase): + def test_polygon_3(self): + p = (1.0, 1.0) + poly = Polygon([p, p, p]) + assert poly.bounds == (1.0, 1.0, 1.0, 1.0) + + def test_polygon_5(self): + p = (1.0, 1.0) + poly = Polygon([p, p, p, p, p]) + assert poly.bounds == (1.0, 1.0, 1.0, 1.0) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_snap.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_snap.py new file mode 100644 index 0000000000000000000000000000000000000000..91360dab7bfb4d63261b050b0f8d49ba0cce547e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_snap.py @@ -0,0 +1,24 @@ +import unittest + +from shapely.geometry import LineString, Polygon +from shapely.ops import snap + + +class Snap(unittest.TestCase): + def test_snap(self): + # input geometries + square = Polygon([(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)]) + line = LineString([(0, 0), (0.8, 0.8), (1.8, 0.95), (2.6, 0.5)]) + + square_coords = square.exterior.coords[:] + line_coords = line.coords[:] + + result = snap(line, square, 0.5) + + # test result is correct + assert isinstance(result, LineString) + assert result.coords[:] == [(0.0, 0.0), (1.0, 1.0), (2.0, 1.0), (2.6, 0.5)] + + # test inputs have not been modified + assert square.exterior.coords[:] == square_coords + assert line.coords[:] == line_coords diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_split.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbf4eaf1bd5eff6fcc62904905faf9e133bc28d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_split.py @@ -0,0 +1,285 @@ +import unittest + +import pytest + +from shapely.errors import GeometryTypeError +from shapely.geometry import ( + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.ops import linemerge, split, unary_union + + +class TestSplitGeometry(unittest.TestCase): + # helper class for testing below + def helper(self, geom, splitter, expected_chunks): + s = split(geom, splitter) + assert s.geom_type == "GeometryCollection" + assert len(s.geoms) == expected_chunks + if expected_chunks > 1: + # split --> expected collection that when merged is again equal to original + # geometry + if s.geoms[0].geom_type == "LineString": + self.assertTrue(linemerge(s).simplify(0.000001).equals(geom)) + elif s.geoms[0].geom_type == "Polygon": + union = unary_union(s).simplify(0.000001) + assert union.equals(geom) + assert union.area == geom.area + else: + raise ValueError + elif expected_chunks == 1: + # not split --> expected equal to line + assert s.geoms[0].equals(geom) + + def test_split_closed_line_with_point(self): + # point at start/end of closed ring -> return equal + # see GH #524 + ls = LineString([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + splitter = Point(0, 0) + self.helper(ls, splitter, 1) + + +class TestSplitPolygon(TestSplitGeometry): + poly_simple = Polygon([(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]) + poly_hole = Polygon( + [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)], + [[(0.5, 0.5), (0.5, 1.5), (1.5, 1.5), (1.5, 0.5), (0.5, 0.5)]], + ) + + def test_split_poly_with_line(self): + # crossing at 2 points --> return 2 polygons + splitter = LineString([(1, 3), (1, -3)]) + self.helper(self.poly_simple, splitter, 2) + self.helper(self.poly_hole, splitter, 2) + + # crossing twice with one linestring --> return 3 polygons + splitter = LineString([(1, 3), (1, -3), (1.7, -3), (1.7, 3)]) + self.helper(self.poly_simple, splitter, 3) + self.helper(self.poly_hole, splitter, 3) + + # touching the boundary --> return equal + splitter = LineString([(0, 2), (5, 2)]) + self.helper(self.poly_simple, splitter, 1) + self.helper(self.poly_hole, splitter, 1) + + # inside the polygon --> return equal + splitter = LineString([(0.2, 0.2), (1.7, 1.7), (3, 2)]) + self.helper(self.poly_simple, splitter, 1) + self.helper(self.poly_hole, splitter, 1) + + # outside the polygon --> return equal + splitter = LineString([(0, 3), (3, 3), (3, 0)]) + self.helper(self.poly_simple, splitter, 1) + self.helper(self.poly_hole, splitter, 1) + + def test_split_poly_with_multiline(self): + # crossing twice with a multilinestring --> return 3 polygons + splitter = MultiLineString([[(0.2, 3), (0.2, -3)], [(1.7, -3), (1.7, 3)]]) + self.helper(self.poly_simple, splitter, 3) + self.helper(self.poly_hole, splitter, 3) + + # crossing twice with a cross multilinestring --> return 4 polygons + splitter = MultiLineString([[(0.2, 3), (0.2, -3)], [(-3, 1), (3, 1)]]) + self.helper(self.poly_simple, splitter, 4) + self.helper(self.poly_hole, splitter, 4) + + # cross once, touch the boundary once --> return 2 polygons + splitter = MultiLineString([[(0.2, 3), (0.2, -3)], [(0, 2), (5, 2)]]) + self.helper(self.poly_simple, splitter, 2) + self.helper(self.poly_hole, splitter, 2) + + # cross once, inside the polygon once --> return 2 polygons + splitter = MultiLineString( + [[(0.2, 3), (0.2, -3)], [(1.2, 1.2), (1.7, 1.7), (3, 2)]] + ) + self.helper(self.poly_simple, splitter, 2) + self.helper(self.poly_hole, splitter, 2) + + # cross once, outside the polygon once --> return 2 polygons + splitter = MultiLineString([[(0.2, 3), (0.2, -3)], [(0, 3), (3, 3), (3, 0)]]) + self.helper(self.poly_simple, splitter, 2) + self.helper(self.poly_hole, splitter, 2) + + def test_split_poly_with_other(self): + with pytest.raises(GeometryTypeError): + split(self.poly_simple, Point(1, 1)) + with pytest.raises(GeometryTypeError): + split(self.poly_simple, MultiPoint([(1, 1), (3, 4)])) + with pytest.raises(GeometryTypeError): + split(self.poly_simple, self.poly_hole) + + +class TestSplitLine(TestSplitGeometry): + ls = LineString([(0, 0), (1.5, 1.5), (3.0, 4.0)]) + + def test_split_line_with_point(self): + # point on line interior --> return 2 segments + splitter = Point(1, 1) + self.helper(self.ls, splitter, 2) + + # point on line point --> return 2 segments + splitter = Point(1.5, 1.5) + self.helper(self.ls, splitter, 2) + + # point on boundary --> return equal + splitter = Point(3, 4) + self.helper(self.ls, splitter, 1) + + # point on exterior of line --> return equal + splitter = Point(2, 2) + self.helper(self.ls, splitter, 1) + + def test_split_line_with_multipoint(self): + # points on line interior --> return 4 segments + splitter = MultiPoint([(1, 1), (1.5, 1.5), (0.5, 0.5)]) + self.helper(self.ls, splitter, 4) + + # points on line interior and boundary -> return 2 segments + splitter = MultiPoint([(1, 1), (3, 4)]) + self.helper(self.ls, splitter, 2) + + # point on linear interior but twice --> return 2 segments + splitter = MultiPoint([(1, 1), (1.5, 1.5), (1, 1)]) + self.helper(self.ls, splitter, 3) + + def test_split_line_with_line(self): + # crosses at one point --> return 2 segments + splitter = LineString([(0, 1), (1, 0)]) + self.helper(self.ls, splitter, 2) + + # crosses at two points --> return 3 segments + splitter = LineString([(0, 1), (1, 0), (1, 2)]) + self.helper(self.ls, splitter, 3) + + # overlaps --> raise + splitter = LineString([(0, 0), (15, 15)]) + with pytest.raises(ValueError): + self.helper(self.ls, splitter, 1) + + # does not cross --> return equal + splitter = LineString([(0, 1), (0, 2)]) + self.helper(self.ls, splitter, 1) + + # is touching the boundary --> return equal + splitter = LineString([(-1, 1), (1, -1)]) + assert splitter.touches(self.ls) + self.helper(self.ls, splitter, 1) + + # splitter boundary touches interior of line --> return 2 segments + splitter = LineString([(0, 1), (1, 1)]) # touches at (1, 1) + assert splitter.touches(self.ls) + self.helper(self.ls, splitter, 2) + + def test_split_line_with_multiline(self): + # crosses at one point --> return 2 segments + splitter = MultiLineString([[(0, 1), (1, 0)], [(0, 0), (2, -2)]]) + self.helper(self.ls, splitter, 2) + + # crosses at two points --> return 3 segments + splitter = MultiLineString([[(0, 1), (1, 0)], [(0, 2), (2, 0)]]) + self.helper(self.ls, splitter, 3) + + # crosses at three points --> return 4 segments + splitter = MultiLineString([[(0, 1), (1, 0)], [(0, 2), (2, 0), (2.2, 3.2)]]) + self.helper(self.ls, splitter, 4) + + # overlaps --> raise + splitter = MultiLineString([[(0, 0), (1.5, 1.5)], [(1.5, 1.5), (3, 4)]]) + with pytest.raises(ValueError): + self.helper(self.ls, splitter, 1) + + # does not cross --> return equal + splitter = MultiLineString([[(0, 1), (0, 2)], [(1, 0), (2, 0)]]) + self.helper(self.ls, splitter, 1) + + def test_split_line_with_polygon(self): + # crosses at two points --> return 3 segments + splitter = Polygon([(1, 0), (1, 2), (2, 2), (2, 0), (1, 0)]) + self.helper(self.ls, splitter, 3) + + # crosses at one point and touches boundary --> return 2 segments + splitter = Polygon([(0, 0), (1, 2), (2, 2), (1, 0), (0, 0)]) + self.helper(self.ls, splitter, 2) + + # exterior crosses at one point and touches at (0, 0) + # interior crosses at two points + splitter = Polygon( + [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)], + [[(0.5, 0.5), (0.5, 1.5), (1.5, 1.5), (1.5, 0.5), (0.5, 0.5)]], + ) + self.helper(self.ls, splitter, 4) + + def test_split_line_with_multipolygon(self): + poly1 = Polygon( + [(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)] + ) # crosses at one point and touches at (0, 0) + poly2 = Polygon( + [(0.5, 0.5), (0.5, 1.5), (1.5, 1.5), (1.5, 0.5), (0.5, 0.5)] + ) # crosses at two points + poly3 = Polygon([(0, 0), (0, -2), (-2, -2), (-2, 0), (0, 0)]) # not crossing + splitter = MultiPolygon([poly1, poly2, poly3]) + self.helper(self.ls, splitter, 4) + + +class TestSplitClosedRing(TestSplitGeometry): + ls = LineString([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]) + + def test_split_closed_ring_with_point(self): + splitter = Point([0.0, 0.0]) + self.helper(self.ls, splitter, 1) + + splitter = Point([0.0, 0.5]) + self.helper(self.ls, splitter, 2) + result = split(self.ls, splitter) + assert result.geoms[0].coords[:] == [(0, 0), (0.0, 0.5)] + assert result.geoms[1].coords[:] == [(0.0, 0.5), (0, 1), (1, 1), (1, 0), (0, 0)] + + # previously failed, see GH#585 + splitter = Point([0.5, 0.0]) + self.helper(self.ls, splitter, 2) + result = split(self.ls, splitter) + assert result.geoms[0].coords[:] == [(0, 0), (0, 1), (1, 1), (1, 0), (0.5, 0)] + assert result.geoms[1].coords[:] == [(0.5, 0), (0, 0)] + + splitter = Point([2.0, 2.0]) + self.helper(self.ls, splitter, 1) + + +class TestSplitMulti(TestSplitGeometry): + def test_split_multiline_with_point(self): + # a cross-like multilinestring with a point in the middle --> return 4 line + # segments + l1 = LineString([(0, 1), (2, 1)]) + l2 = LineString([(1, 0), (1, 2)]) + ml = MultiLineString([l1, l2]) + splitter = Point((1, 1)) + self.helper(ml, splitter, 4) + + def test_split_multiline_with_multipoint(self): + # a cross-like multilinestring with a point in middle, a point on one of the + # lines and a point in the exterior + # --> return 4+1 line segments + l1 = LineString([(0, 1), (3, 1)]) + l2 = LineString([(1, 0), (1, 2)]) + ml = MultiLineString([l1, l2]) + splitter = MultiPoint([(1, 1), (2, 1), (4, 2)]) + self.helper(ml, splitter, 5) + + def test_split_multipolygon_with_line(self): + # two polygons with a crossing line --> return 4 triangles + poly1 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + poly2 = Polygon([(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)]) + mpoly = MultiPolygon([poly1, poly2]) + ls = LineString([(-1, -1), (3, 3)]) + self.helper(mpoly, ls, 4) + + # two polygons away from the crossing line --> return identity + poly1 = Polygon([(10, 10), (10, 11), (11, 11), (11, 10), (10, 10)]) + poly2 = Polygon([(-10, -10), (-10, -11), (-11, -11), (-11, -10), (-10, -10)]) + mpoly = MultiPolygon([poly1, poly2]) + ls = LineString([(-1, -1), (3, 3)]) + self.helper(mpoly, ls, 2) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_substring.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_substring.py new file mode 100644 index 0000000000000000000000000000000000000000..829943ba757b689bcb82e6fbc16ad47d94776e70 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_substring.py @@ -0,0 +1,220 @@ +import json +import unittest + +import pytest + +from shapely.errors import GeometryTypeError +from shapely.geometry import LineString, Point, shape +from shapely.ops import substring + + +class SubstringTestCase(unittest.TestCase): + def setUp(self): + self.point = Point(1, 1) + self.line1 = LineString([(0, 0), (2, 0)]) + self.line2 = LineString([(3, 0), (3, 6), (4.5, 6)]) + self.line3 = LineString((0, i) for i in range(5)) + + def test_return_startpoint(self): + assert substring(self.line1, -500, -600).equals(Point(0, 0)) + assert substring(self.line1, -500, -500).equals(Point(0, 0)) + assert substring(self.line1, -1, -1.1, True).equals(Point(0, 0)) + assert substring(self.line1, -1.1, -1.1, True).equals(Point(0, 0)) + + def test_return_endpoint(self): + assert substring(self.line1, 500, 600).equals(Point(2, 0)) + assert substring(self.line1, 500, 500).equals(Point(2, 0)) + assert substring(self.line1, 1, 1.1, True).equals(Point(2, 0)) + assert substring(self.line1, 1.1, 1.1, True).equals(Point(2, 0)) + + def test_return_midpoint(self): + assert substring(self.line1, 0.5, 0.5).equals(Point(0.5, 0)) + assert substring(self.line1, -0.5, -0.5).equals(Point(1.5, 0)) + assert substring(self.line1, 0.5, 0.5, True).equals(Point(1, 0)) + assert substring(self.line1, -0.5, -0.5, True).equals(Point(1, 0)) + + # Coming from opposite ends + assert substring(self.line1, 1.5, -0.5).equals(Point(1.5, 0)) + assert substring(self.line1, -0.5, 1.5).equals(Point(1.5, 0)) + assert substring(self.line1, -0.7, 0.3, True).equals(Point(0.6, 0)) + assert substring(self.line1, 0.3, -0.7, True).equals(Point(0.6, 0)) + + def test_return_startsubstring(self): + assert ( + substring(self.line1, -500, 0.6).wkt == LineString([(0, 0), (0.6, 0)]).wkt + ) + assert ( + substring(self.line1, -1.1, 0.6, True).wkt + == LineString([(0, 0), (1.2, 0)]).wkt + ) + + def test_return_startsubstring_reversed(self): + # not normalized + assert substring(self.line1, -1, -500).wkt == LineString([(1, 0), (0, 0)]).wkt + assert ( + substring(self.line3, 3.5, 0).wkt + == LineString([(0, 3.5), (0, 3), (0, 2), (0, 1), (0, 0)]).wkt + ) + assert ( + substring(self.line3, -1.5, -500).wkt + == LineString([(0, 2.5), (0, 2), (0, 1), (0, 0)]).wkt + ) + # normalized + assert ( + substring(self.line1, -0.5, -1.1, True).wkt + == LineString([(1.0, 0), (0, 0)]).wkt + ) + assert ( + substring(self.line3, 0.5, 0, True).wkt + == LineString([(0, 2.0), (0, 1), (0, 0)]).wkt + ) + assert ( + substring(self.line3, -0.5, -1.1, True).wkt + == LineString([(0, 2.0), (0, 1), (0, 0)]).wkt + ) + + def test_return_endsubstring(self): + assert substring(self.line1, 0.6, 500).wkt == LineString([(0.6, 0), (2, 0)]).wkt + assert ( + substring(self.line1, 0.6, 1.1, True).wkt + == LineString([(1.2, 0), (2, 0)]).wkt + ) + + def test_return_endsubstring_reversed(self): + # not normalized + assert substring(self.line1, 500, -1).wkt == LineString([(2, 0), (1, 0)]).wkt + assert ( + substring(self.line3, 4, 2.5).wkt + == LineString([(0, 4), (0, 3), (0, 2.5)]).wkt + ) + assert ( + substring(self.line3, 500, -1.5).wkt + == LineString([(0, 4), (0, 3), (0, 2.5)]).wkt + ) + # normalized + assert ( + substring(self.line1, 1.1, -0.5, True).wkt + == LineString([(2, 0), (1.0, 0)]).wkt + ) + assert ( + substring(self.line3, 1, 0.5, True).wkt + == LineString([(0, 4), (0, 3), (0, 2.0)]).wkt + ) + assert ( + substring(self.line3, 1.1, -0.5, True).wkt + == LineString([(0, 4), (0, 3), (0, 2.0)]).wkt + ) + + def test_return_midsubstring(self): + assert ( + substring(self.line1, 0.5, 0.6).wkt == LineString([(0.5, 0), (0.6, 0)]).wkt + ) + assert ( + substring(self.line1, -0.6, -0.5).wkt + == LineString([(1.4, 0), (1.5, 0)]).wkt + ) + assert ( + substring(self.line1, 0.5, 0.6, True).wkt + == LineString([(1, 0), (1.2, 0)]).wkt + ) + assert ( + substring(self.line1, -0.6, -0.5, True).wkt + == LineString([(0.8, 0), (1, 0)]).wkt + ) + + def test_return_midsubstring_reversed(self): + assert ( + substring(self.line1, 0.6, 0.5).wkt == LineString([(0.6, 0), (0.5, 0)]).wkt + ) + assert ( + substring(self.line1, -0.5, -0.6).wkt + == LineString([(1.5, 0), (1.4, 0)]).wkt + ) + assert ( + substring(self.line1, 0.6, 0.5, True).wkt + == LineString([(1.2, 0), (1, 0)]).wkt + ) + assert ( + substring(self.line1, -0.5, -0.6, True).wkt + == LineString([(1, 0), (0.8, 0)]).wkt + ) + + # with vertices + # not normalized + assert ( + substring(self.line3, 3.5, 2.5).wkt + == LineString([(0, 3.5), (0, 3), (0, 2.5)]).wkt + ) # (+, +) + assert ( + substring(self.line3, -0.5, -1.5).wkt + == LineString([(0, 3.5), (0, 3), (0, 2.5)]).wkt + ) # (-, -) + assert ( + substring(self.line3, 3.5, -1.5).wkt + == LineString([(0, 3.5), (0, 3), (0, 2.5)]).wkt + ) # (+, -) + assert ( + substring(self.line3, -0.5, 2.5).wkt + == LineString([(0, 3.5), (0, 3), (0, 2.5)]).wkt + ) # (-, +) + + # normalized + assert ( + substring(self.line3, 0.875, 0.625, True).wkt + == LineString([(0, 3.5), (0, 3), (0, 2.5)]).wkt + ) + assert ( + substring(self.line3, -0.125, -0.375, True).wkt + == LineString([(0, 3.5), (0, 3), (0, 2.5)]).wkt + ) + assert ( + substring(self.line3, 0.875, -0.375, True).wkt + == LineString([(0, 3.5), (0, 3), (0, 2.5)]).wkt + ) + assert ( + substring(self.line3, -0.125, 0.625, True).wkt + == LineString([(0, 3.5), (0, 3), (0, 2.5)]).wkt + ) + + def test_return_substring_with_vertices(self): + assert ( + substring(self.line2, 1, 7).wkt == LineString([(3, 1), (3, 6), (4, 6)]).wkt + ) + assert ( + substring(self.line2, 0.2, 0.9, True).wkt + == LineString([(3, 1.5), (3, 6), (3.75, 6)]).wkt + ) + assert ( + substring(self.line2, 0, 0.9, True).wkt + == LineString([(3, 0), (3, 6), (3.75, 6)]).wkt + ) + assert ( + substring(self.line2, 0.2, 1, True).wkt + == LineString([(3, 1.5), (3, 6), (4.5, 6)]).wkt + ) + + def test_return_substring_issue682(self): + assert list(substring(self.line2, 0.1, 0).coords) == [(3.0, 0.1), (3.0, 0.0)] + + def test_return_substring_issue848(self): + line = shape(json.loads(data_issue_848)) + cut_line = substring(line, 0.7, 0.8, normalized=True) + assert len(cut_line.coords) == 53 + + def test_raise_type_error(self): + with pytest.raises(GeometryTypeError): + substring(Point(0, 0), 0, 0) + + def test_return_z_coord_issue1699(self): + line_z = LineString([(0, 0, 0), (2, 0, 0)]) + assert ( + substring(line_z, 0, 0.5, True).wkt + == LineString([(0, 0, 0), (1, 0, 0)]).wkt + ) + assert ( + substring(line_z, 0.5, 0, True).wkt + == LineString([(1, 0, 0), (0, 0, 0)]).wkt + ) + + +data_issue_848 = '{"type": "LineString", "coordinates": [[-87.71314, 41.96793], [-87.71312, 41.96667], [-87.71311, 41.96643], [-87.7131, 41.96635], [-87.71309, 41.9663], [-87.71303, 41.96621], [-87.71298, 41.96615], [-87.71292, 41.96611], [-87.7128, 41.96607], [-87.71268, 41.96605], [-87.71255, 41.96605], [-87.7124, 41.96605], [-87.71219, 41.96605], [-87.71173, 41.96606], [-87.71108, 41.96607], [-87.71027, 41.96607], [-87.70884, 41.96609], [-87.70763, 41.96611], [-87.70645, 41.96612], [-87.70399, 41.96613], [-87.70267, 41.96614], [-87.70166, 41.96615], [-87.70075, 41.96615], [-87.69954, 41.96615], [-87.69873, 41.96616], [-87.69789, 41.96618], [-87.69675, 41.9662], [-87.69502, 41.96621], [-87.69411, 41.96621], [-87.69145, 41.96623], [-87.69026, 41.96624], [-87.68946, 41.96625], [-87.6885, 41.96625], [-87.68718, 41.96628], [-87.68545, 41.96631], [-87.68399, 41.96632], [-87.68271, 41.96635], [-87.68159, 41.96636], [-87.68034, 41.96638], [-87.67863, 41.96641], [-87.67766, 41.96642], [-87.67741, 41.96641], [-87.67722, 41.9664], [-87.67695, 41.96638], [-87.67665, 41.96632], [-87.67638, 41.96623], [-87.67613, 41.96612], [-87.67589, 41.96596], [-87.6757, 41.96579], [-87.67557, 41.96565], [-87.67544, 41.96547], [-87.67539, 41.96536], [-87.6753, 41.96519], [-87.67524, 41.96503], [-87.67523, 41.96491], [-87.67522, 41.96477], [-87.67521, 41.96457], [-87.6752, 41.96434], [-87.67519, 41.96371], [-87.67517, 41.96175], [-87.67513, 41.96077], [-87.67505, 41.95798], [-87.67501, 41.95666], [-87.67497, 41.95513], [-87.67496, 41.95452], [-87.67491, 41.95392], [-87.67487, 41.95302], [-87.67485, 41.95202], [-87.67484, 41.95101], [-87.67479, 41.94959], [-87.67476, 41.94859], [-87.67474, 41.94703], [-87.67468, 41.94596], [-87.67466, 41.94513], [-87.67463, 41.94494], [-87.67457, 41.94474], [-87.6745, 41.94455], [-87.67442, 41.94438], [-87.6743, 41.94424], [-87.67419, 41.94414], [-87.67405, 41.94404], [-87.67386, 41.94393], [-87.67367, 41.94386], [-87.67348, 41.9438], [-87.67334, 41.94376], [-87.67311, 41.94373], [-87.67289, 41.9437], [-87.67263, 41.94369], [-87.67234, 41.94369], [-87.6715, 41.9437], [-87.67088, 41.94371], [-87.66938, 41.94373], [-87.66749, 41.94377], [-87.66585, 41.94378], [-87.66508, 41.94379], [-87.66361, 41.94381], [-87.6591, 41.94391], [-87.65767, 41.94391], [-87.65608, 41.94393], [-87.6555, 41.94394], [-87.65521, 41.94394], [-87.65503, 41.94393], [-87.65488, 41.9439], [-87.6547, 41.94386], [-87.65454, 41.9438], [-87.65441, 41.94375], [-87.65425, 41.94364], [-87.6541, 41.94351], [-87.654, 41.94342], [-87.65392, 41.94331], [-87.65382, 41.94319], [-87.65375, 41.94306], [-87.65367, 41.94292], [-87.65361, 41.9428], [-87.65355, 41.94269], [-87.65351, 41.94257], [-87.65347, 41.94238], [-87.65345, 41.94218], [-87.65338, 41.93975], [-87.65337, 41.93939], [-87.65337, 41.93893], [-87.65336, 41.93865], [-87.65333, 41.93763], [-87.65331, 41.93717], [-87.65328, 41.93627], [-87.65327, 41.93603], [-87.65323, 41.93532], [-87.65322, 41.93491], [-87.6532, 41.93445], [-87.65314, 41.93312], [-87.65313, 41.93273], [-87.6531, 41.93218], [-87.65307, 41.93151], [-87.65305, 41.9309], [-87.65302, 41.9303], [-87.65299, 41.92951], [-87.65296, 41.9287], [-87.65295, 41.92842], [-87.65294, 41.92768], [-87.65292, 41.92715], [-87.65289, 41.92599], [-87.65288, 41.92537], [-87.65287, 41.92505], [-87.65282, 41.92352], [-87.65276, 41.92172], [-87.65274, 41.92113], [-87.65264, 41.91822], [-87.65264, 41.91808], [-87.65262, 41.91763], [-87.65261, 41.91718], [-87.65255, 41.91563], [-87.6525, 41.91406], [-87.65242, 41.91377], [-87.65234, 41.91362], [-87.65223, 41.91351], [-87.65208, 41.91339], [-87.65183, 41.91322], [-87.65093, 41.9126], [-87.65017, 41.91203], [-87.64985, 41.9118], [-87.64971, 41.91171], [-87.64957, 41.91164], [-87.64948, 41.9116], [-87.64939, 41.91158], [-87.6492, 41.91153], [-87.649, 41.9115], [-87.64883, 41.9115], [-87.64863, 41.9115], [-87.64792, 41.91151], [-87.64781, 41.9115], [-87.64768, 41.91146], [-87.64756, 41.91139], [-87.64745, 41.91122], [-87.6474, 41.91112], [-87.64739, 41.91101], [-87.64738, 41.91086], [-87.64736, 41.91071], [-87.64734, 41.91061], [-87.64728, 41.91051], [-87.64718, 41.91044], [-87.64709, 41.9104], [-87.64697, 41.91036], [-87.64682, 41.91034], [-87.64664, 41.91033], [-87.64646, 41.91033], [-87.6458, 41.91034], [-87.64523, 41.91034], [-87.64348, 41.91036], [-87.64255, 41.91039], [-87.641, 41.9104], [-87.64038, 41.9104], [-87.63975, 41.9104], [-87.6393, 41.91041], [-87.63814, 41.91042], [-87.63798, 41.91041], [-87.63787, 41.91039], [-87.63771, 41.91034], [-87.63757, 41.91027], [-87.63746, 41.91021], [-87.63736, 41.91011], [-87.6373, 41.90999], [-87.63727, 41.90986], [-87.63726, 41.90973], [-87.63725, 41.90951], [-87.63723, 41.90874], [-87.63718, 41.90758], [-87.63713, 41.90607], [-87.63711, 41.90543], [-87.63702, 41.90381], [-87.63702, 41.90368], [-87.63701, 41.90334], [-87.63699, 41.90322], [-87.63694, 41.90312], [-87.63688, 41.90299], [-87.63682, 41.90292], [-87.63671, 41.90279], [-87.63659, 41.90265], [-87.63653, 41.90255], [-87.63649, 41.90245], [-87.63646, 41.90235], [-87.63647, 41.90221], [-87.63647, 41.90211], [-87.6365, 41.90202], [-87.63653, 41.9019], [-87.63659, 41.90177], [-87.63666, 41.90156], [-87.63669, 41.90143], [-87.6367, 41.90131], [-87.6367, 41.90119], [-87.63664, 41.90029], [-87.63664, 41.90008], [-87.63662, 41.89975], [-87.63658, 41.89892], [-87.63657, 41.89867], [-87.63654, 41.89761], [-87.63654, 41.89738], [-87.63649, 41.89726], [-87.63641, 41.89715], [-87.63634, 41.89708], [-87.63623, 41.89699], [-87.63595, 41.89677], [-87.63583, 41.89667], [-87.63574, 41.89654], [-87.63569, 41.89645], [-87.63568, 41.89633], [-87.63565, 41.89542], [-87.63563, 41.89434], [-87.6356, 41.89327], [-87.63558, 41.89261], [-87.63554, 41.89147], [-87.63553, 41.89051], [-87.63548, 41.8903], [-87.6354, 41.89021], [-87.63533, 41.89012], [-87.63524, 41.89007], [-87.63508, 41.89001], [-87.63493, 41.88997], [-87.63475, 41.88994], [-87.63462, 41.88991], [-87.63447, 41.88989], [-87.63436, 41.88984], [-87.63425, 41.88979], [-87.63414, 41.8897], [-87.63407, 41.88962], [-87.63402, 41.88952], [-87.63399, 41.88943], [-87.63397, 41.88897], [-87.63396, 41.88707], [-87.63391, 41.88572], [-87.63389, 41.88441], [-87.63385, 41.8827], [-87.63384, 41.88144], [-87.63378, 41.88014], [-87.63374, 41.87872], [-87.63369, 41.87726], [-87.63369, 41.87706], [-87.63365, 41.87695], [-87.63359, 41.87691], [-87.63353, 41.87688], [-87.63345, 41.87686], [-87.63338, 41.87685], [-87.63263, 41.87685], [-87.63173, 41.87686], [-87.62925, 41.87689], [-87.62821, 41.87691], [-87.62757, 41.87693], [-87.6265, 41.87696], [-87.62635, 41.87696], [-87.62603, 41.87697], [-87.62605, 41.87831], [-87.6261, 41.87951], [-87.62616, 41.88203], [-87.62619, 41.88322], [-87.62622, 41.88443], [-87.62626, 41.88534], [-87.62625, 41.88552], [-87.62625, 41.88557], [-87.62627, 41.88562], [-87.6263, 41.88566], [-87.62635, 41.88569], [-87.62642, 41.88572], [-87.6265, 41.88573], [-87.62655, 41.88574], [-87.62661, 41.88574], [-87.62683, 41.88574], [-87.62784, 41.88574], [-87.62887, 41.88574], [-87.62948, 41.88574], [-87.62982, 41.88574], [-87.62992, 41.88574], [-87.63011, 41.88574], [-87.6302, 41.88574], [-87.63089, 41.88574], [-87.63204, 41.88574], [-87.63285, 41.88573], [-87.63391, 41.88572], [-87.63396, 41.88707], [-87.63397, 41.88897], [-87.63399, 41.88943], [-87.63402, 41.88952], [-87.63407, 41.88962], [-87.63414, 41.8897], [-87.63425, 41.88979], [-87.63436, 41.88984], [-87.63447, 41.88989], [-87.63462, 41.88991], [-87.63475, 41.88994], [-87.63493, 41.88997], [-87.63508, 41.89001], [-87.63524, 41.89007], [-87.63533, 41.89012], [-87.6354, 41.89021], [-87.63548, 41.8903], [-87.63553, 41.89051], [-87.63554, 41.89147], [-87.63558, 41.89261], [-87.6356, 41.89327], [-87.63563, 41.89434], [-87.63565, 41.89542], [-87.63568, 41.89633], [-87.63569, 41.89645], [-87.63574, 41.89654], [-87.63583, 41.89667], [-87.63595, 41.89677], [-87.63623, 41.89699], [-87.63634, 41.89708], [-87.63641, 41.89715], [-87.63649, 41.89726], [-87.63654, 41.89738], [-87.63654, 41.89761], [-87.63657, 41.89867], [-87.63658, 41.89892], [-87.63662, 41.89975], [-87.63664, 41.90008], [-87.63664, 41.90029], [-87.6367, 41.90119], [-87.6367, 41.90131], [-87.63669, 41.90143], [-87.63666, 41.90156], [-87.63659, 41.90177], [-87.63653, 41.9019], [-87.6365, 41.90202], [-87.63647, 41.90211], [-87.63647, 41.90221], [-87.63646, 41.90235], [-87.63649, 41.90245], [-87.63653, 41.90255], [-87.63659, 41.90265], [-87.63671, 41.90279], [-87.63682, 41.90292], [-87.63688, 41.90299], [-87.63694, 41.90312], [-87.63699, 41.90322], [-87.63701, 41.90334], [-87.63702, 41.90368], [-87.63702, 41.90381], [-87.63711, 41.90543], [-87.63713, 41.90607], [-87.63718, 41.90758], [-87.63723, 41.90874], [-87.63725, 41.90951], [-87.63726, 41.90973], [-87.63727, 41.90986], [-87.6373, 41.90999], [-87.63736, 41.91011], [-87.63746, 41.91021], [-87.63757, 41.91027], [-87.63771, 41.91034], [-87.63787, 41.91039], [-87.63798, 41.91041], [-87.63814, 41.91042], [-87.6393, 41.91041], [-87.63975, 41.9104], [-87.64038, 41.9104], [-87.641, 41.9104], [-87.64255, 41.91039], [-87.64348, 41.91036], [-87.64523, 41.91034], [-87.6458, 41.91034], [-87.64646, 41.91033], [-87.64664, 41.91033], [-87.64682, 41.91034], [-87.64697, 41.91036], [-87.64709, 41.9104], [-87.64718, 41.91044], [-87.64728, 41.91051], [-87.64734, 41.91061], [-87.64736, 41.91071], [-87.64738, 41.91086], [-87.64739, 41.91101], [-87.6474, 41.91112], [-87.64745, 41.91122], [-87.64756, 41.91139], [-87.64768, 41.91146], [-87.64781, 41.9115], [-87.64792, 41.91151], [-87.64863, 41.9115], [-87.64883, 41.9115], [-87.649, 41.9115], [-87.6492, 41.91153], [-87.64939, 41.91158], [-87.64948, 41.9116], [-87.64957, 41.91164], [-87.64971, 41.91171], [-87.64985, 41.9118], [-87.65017, 41.91203], [-87.65093, 41.9126], [-87.65183, 41.91322], [-87.65208, 41.91339], [-87.65223, 41.91351], [-87.65234, 41.91362], [-87.65242, 41.91377], [-87.6525, 41.91406], [-87.65255, 41.91563], [-87.65261, 41.91718], [-87.65262, 41.91763], [-87.65264, 41.91808], [-87.65264, 41.91822], [-87.65274, 41.92113], [-87.65276, 41.92172], [-87.65282, 41.92352], [-87.65287, 41.92505], [-87.65288, 41.92537], [-87.65289, 41.92599], [-87.65292, 41.92715], [-87.65294, 41.92768], [-87.65295, 41.92842], [-87.65296, 41.9287], [-87.65299, 41.92951], [-87.65302, 41.9303], [-87.65305, 41.9309], [-87.65307, 41.93151], [-87.6531, 41.93218], [-87.65313, 41.93273], [-87.65314, 41.93312], [-87.6532, 41.93445], [-87.65322, 41.93491], [-87.65323, 41.93532], [-87.65327, 41.93603], [-87.65328, 41.93627], [-87.65331, 41.93717], [-87.65333, 41.93763], [-87.65336, 41.93865], [-87.65337, 41.93893], [-87.65337, 41.93939], [-87.65338, 41.93975], [-87.65345, 41.94218], [-87.65347, 41.94238], [-87.65351, 41.94257], [-87.65355, 41.94269], [-87.65361, 41.9428], [-87.65367, 41.94292], [-87.65375, 41.94306], [-87.65382, 41.94319], [-87.65392, 41.94331], [-87.654, 41.94342], [-87.6541, 41.94351], [-87.65425, 41.94364], [-87.65441, 41.94375], [-87.65454, 41.9438], [-87.6547, 41.94386], [-87.65488, 41.9439], [-87.65503, 41.94393], [-87.65521, 41.94394], [-87.6555, 41.94394], [-87.65608, 41.94393], [-87.65767, 41.94391], [-87.6591, 41.94391], [-87.66361, 41.94381], [-87.66508, 41.94379], [-87.66585, 41.94378], [-87.66749, 41.94377], [-87.66938, 41.94373], [-87.67088, 41.94371], [-87.6715, 41.9437], [-87.67234, 41.94369], [-87.67263, 41.94369], [-87.67289, 41.9437], [-87.67311, 41.94373], [-87.67334, 41.94376], [-87.67348, 41.9438], [-87.67367, 41.94386], [-87.67386, 41.94393], [-87.67405, 41.94404], [-87.67419, 41.94414], [-87.6743, 41.94424], [-87.67442, 41.94438], [-87.6745, 41.94455], [-87.67457, 41.94474], [-87.67463, 41.94494], [-87.67466, 41.94513], [-87.67468, 41.94596], [-87.67474, 41.94703], [-87.67476, 41.94859], [-87.67479, 41.94959], [-87.67484, 41.95101], [-87.67485, 41.95202], [-87.67487, 41.95302], [-87.67491, 41.95392], [-87.67496, 41.95452], [-87.67497, 41.95513], [-87.67501, 41.95666], [-87.67505, 41.95798], [-87.67513, 41.96077], [-87.67517, 41.96175], [-87.67519, 41.96371], [-87.6752, 41.96434], [-87.67521, 41.96457], [-87.67522, 41.96477], [-87.67523, 41.96491], [-87.67524, 41.96503], [-87.6753, 41.96519], [-87.67539, 41.96536], [-87.67544, 41.96547], [-87.67557, 41.96565], [-87.6757, 41.96579], [-87.67589, 41.96596], [-87.67613, 41.96612], [-87.67638, 41.96623], [-87.67665, 41.96632], [-87.67695, 41.96638], [-87.67722, 41.9664], [-87.67741, 41.96641], [-87.67766, 41.96642], [-87.67863, 41.96641], [-87.68034, 41.96638], [-87.68159, 41.96636], [-87.68271, 41.96635], [-87.68399, 41.96632], [-87.68545, 41.96631], [-87.68718, 41.96628], [-87.6885, 41.96625], [-87.68946, 41.96625], [-87.69026, 41.96624], [-87.69145, 41.96623], [-87.69411, 41.96621], [-87.69502, 41.96621], [-87.69675, 41.9662], [-87.69789, 41.96618], [-87.69873, 41.96616], [-87.69954, 41.96615], [-87.70075, 41.96615], [-87.70166, 41.96615], [-87.70267, 41.96614], [-87.70399, 41.96613], [-87.70645, 41.96612], [-87.70763, 41.96611], [-87.70884, 41.96609], [-87.71027, 41.96607], [-87.71108, 41.96607], [-87.71173, 41.96606], [-87.71219, 41.96605], [-87.7124, 41.96605], [-87.71255, 41.96605], [-87.71268, 41.96605], [-87.7128, 41.96607], [-87.71292, 41.96611], [-87.71298, 41.96615], [-87.71303, 41.96621], [-87.71309, 41.9663], [-87.7131, 41.96635], [-87.71311, 41.96643], [-87.71312, 41.96667], [-87.71314, 41.96793]]}' # noqa: E501 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_svg.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_svg.py new file mode 100644 index 0000000000000000000000000000000000000000..c1c6e7f44aee757305e35e4293f4d192d8c20fd3 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_svg.py @@ -0,0 +1,213 @@ +# Tests SVG output and validity +import os +import unittest +from xml.dom.minidom import parseString as parse_xml_string + +from shapely.geometry import ( + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.geometry.collection import GeometryCollection + + +class SvgTestCase(unittest.TestCase): + def assertSVG(self, geom, expected, **kwrds): + """Helper function to check XML and debug SVG""" + svg_elem = geom.svg(**kwrds) + try: + parse_xml_string(svg_elem) + except Exception: + raise AssertionError("XML is not valid for SVG element: " + str(svg_elem)) + svg_doc = geom._repr_svg_() + try: + doc = parse_xml_string(svg_doc) + except Exception: + raise AssertionError("XML is not valid for SVG document: " + str(svg_doc)) + svg_output_dir = None + # svg_output_dir = '.' # useful for debugging SVG files + if svg_output_dir: + fname = geom.geom_type + if geom.is_empty: + fname += "_empty" + if not geom.is_valid: + fname += "_invalid" + if kwrds: + fname += "_" + ",".join(str(k) + "=" + str(kwrds[k]) for k in kwrds) + svg_path = os.path.join(svg_output_dir, fname + ".svg") + with open(svg_path, "w") as fp: + fp.write(doc.toprettyxml()) + assert svg_elem == expected + + def test_point(self): + # Empty + self.assertSVG(Point(), "") + # Valid + g = Point(6, 7) + self.assertSVG( + g, + '', + ) + self.assertSVG( + g, + '', + scale_factor=5, + ) + + def test_multipoint(self): + # Empty + self.assertSVG(MultiPoint(), "") + # Valid + g = MultiPoint([(6, 7), (3, 4)]) + self.assertSVG( + g, + '' + '', + ) + self.assertSVG( + g, + '' + '', + scale_factor=5, + ) + + def test_linestring(self): + # Empty + self.assertSVG(LineString(), "") + # Valid + g = LineString([(5, 8), (496, -6), (530, 20)]) + self.assertSVG( + g, + '', + ) + self.assertSVG( + g, + '', + scale_factor=5, + ) + # Invalid + self.assertSVG( + LineString([(0, 0), (0, 0)]), + '', + ) + + def test_multilinestring(self): + # Empty + self.assertSVG(MultiLineString(), "") + # Valid + self.assertSVG( + MultiLineString([[(6, 7), (3, 4)], [(2, 8), (9, 1)]]), + '' + '', + ) + # Invalid + self.assertSVG( + MultiLineString([[(2, 3), (2, 3)], [(2, 8), (9, 1)]]), + '' + '', + ) + + def test_polygon(self): + # Empty + self.assertSVG(Polygon(), "") + # Valid + g = Polygon( + [(35, 10), (45, 45), (15, 40), (10, 20), (35, 10)], + [[(20, 30), (35, 35), (30, 20), (20, 30)]], + ) + self.assertSVG( + g, + '', + ) + self.assertSVG( + g, + '', + scale_factor=5, + ) + # Invalid + self.assertSVG( + Polygon([(0, 40), (0, 0), (40, 40), (40, 0), (0, 40)]), + '', + ) + + def test_multipolygon(self): + # Empty + self.assertSVG(MultiPolygon(), "") + # Valid + self.assertSVG( + MultiPolygon( + [ + Polygon([(40, 40), (20, 45), (45, 30), (40, 40)]), + Polygon( + [(20, 35), (10, 30), (10, 10), (30, 5), (45, 20), (20, 35)], + [[(30, 20), (20, 15), (20, 25), (30, 20)]], + ), + ] + ), + '' + '', + ) + # Invalid + self.assertSVG( + MultiPolygon( + [ + Polygon([(140, 140), (120, 145), (145, 130), (140, 140)]), + Polygon([(0, 40), (0, 0), (40, 40), (40, 0), (0, 40)]), + ] + ), + '' + '', + ) + + def test_collection(self): + # Empty + self.assertSVG(GeometryCollection(), "") + # Valid + self.assertSVG( + GeometryCollection([Point(7, 3), LineString([(4, 2), (8, 4)])]), + '' + '', + ) + # Invalid + self.assertSVG( + Point(7, 3).union(LineString([(4, 2), (4, 2)])), + '' + '', + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_transform.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..26a6f85486d2421c2ff66d95ec5a25f6c9b9ddb5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_transform.py @@ -0,0 +1,80 @@ +import unittest + +import pytest + +from shapely import geometry +from shapely.ops import transform + + +class IdentityTestCase(unittest.TestCase): + """New geometry/coordseq method 'xy' makes numpy interop easier""" + + def func(self, x, y, z=None): + return tuple(c for c in [x, y, z] if c) + + def test_empty(self): + g = geometry.Point() + h = transform(self.func, g) + assert h.is_empty + + def test_point(self): + g = geometry.Point(0, 1) + h = transform(self.func, g) + assert h.geom_type == "Point" + assert list(h.coords) == [(0, 1)] + + def test_line(self): + g = geometry.LineString([(0, 1), (2, 3)]) + h = transform(self.func, g) + assert h.geom_type == "LineString" + assert list(h.coords) == [(0, 1), (2, 3)] + + def test_linearring(self): + g = geometry.LinearRing([(0, 1), (2, 3), (2, 2), (0, 1)]) + h = transform(self.func, g) + assert h.geom_type == "LinearRing" + assert list(h.coords) == [(0, 1), (2, 3), (2, 2), (0, 1)] + + def test_polygon(self): + g = geometry.Point(0, 1).buffer(1.0) + h = transform(self.func, g) + assert h.geom_type == "Polygon" + assert g.area == pytest.approx(h.area) + + def test_multipolygon(self): + g = geometry.MultiPoint([(0, 1), (0, 4)]).buffer(1.0) + h = transform(self.func, g) + assert h.geom_type == "MultiPolygon" + assert g.area == pytest.approx(h.area) + + +class LambdaTestCase(unittest.TestCase): + """New geometry/coordseq method 'xy' makes numpy interop easier""" + + def test_point(self): + g = geometry.Point(0, 1) + h = transform(lambda x, y, z=None: (x + 1.0, y + 1.0), g) + assert h.geom_type == "Point" + assert list(h.coords) == [(1.0, 2.0)] + + def test_line(self): + g = geometry.LineString([(0, 1), (2, 3)]) + h = transform(lambda x, y, z=None: (x + 1.0, y + 1.0), g) + assert h.geom_type == "LineString" + assert list(h.coords) == [(1.0, 2.0), (3.0, 4.0)] + + def test_polygon(self): + g = geometry.Point(0, 1).buffer(1.0) + h = transform(lambda x, y, z=None: (x + 1.0, y + 1.0), g) + assert h.geom_type == "Polygon" + assert g.area == pytest.approx(h.area) + assert h.centroid.x == pytest.approx(1.0) + assert h.centroid.y == pytest.approx(2.0) + + def test_multipolygon(self): + g = geometry.MultiPoint([(0, 1), (0, 4)]).buffer(1.0) + h = transform(lambda x, y, z=None: (x + 1.0, y + 1.0), g) + assert h.geom_type == "MultiPolygon" + assert g.area == pytest.approx(h.area) + assert h.centroid.x == pytest.approx(1.0) + assert h.centroid.y == pytest.approx(3.5) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_union.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_union.py new file mode 100644 index 0000000000000000000000000000000000000000..9221daf51e358329ec2e610d7d75c173000d854a --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_union.py @@ -0,0 +1,66 @@ +import random +import unittest +from functools import partial +from itertools import islice + +import pytest + +from shapely.geometry import MultiPolygon, Point +from shapely.ops import unary_union + + +def halton(base): + """Returns an iterator over an infinite Halton sequence""" + + def value(index): + result = 0.0 + f = 1.0 / base + i = index + while i > 0: + result += f * (i % base) + i = i // base + f = f / base + return result + + i = 1 + while i > 0: + yield value(i) + i += 1 + + +class UnionTestCase(unittest.TestCase): + def test_unary_union_partial(self): + # Use a partial function to make 100 points uniformly distributed + # in a 40x40 box centered on 0,0. + + r = partial(random.uniform, -20.0, 20.0) + points = [Point(r(), r()) for i in range(100)] + + # Buffer the points, producing 100 polygon spots + spots = [p.buffer(2.5) for p in points] + + # Perform a cascaded union of the polygon spots, dissolving them + # into a collection of polygon patches + u = unary_union(spots) + assert u.geom_type in ("Polygon", "MultiPolygon") + + def setUp(self): + # Instead of random points, use deterministic, pseudo-random Halton + # sequences for repeatability sake. + self.coords = zip( + list(islice(halton(5), 20, 120)), + list(islice(halton(7), 20, 120)), + ) + + def test_unary_union(self): + patches = [Point(xy).buffer(0.05) for xy in self.coords] + u = unary_union(patches) + assert u.geom_type == "MultiPolygon" + assert u.area == pytest.approx(0.718572540569) + + def test_unary_union_multi(self): + # Test of multipart input based on comment by @schwehr at + # https://github.com/shapely/shapely/issues/47#issuecomment-21809308 + patches = MultiPolygon([Point(xy).buffer(0.05) for xy in self.coords]) + assert unary_union(patches).area == pytest.approx(0.71857254056) + assert unary_union([patches, patches]).area == pytest.approx(0.71857254056) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_validation.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec8663c7061904069b0a5d41f24e1d31619260c --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_validation.py @@ -0,0 +1,9 @@ +import unittest + +from shapely.geometry import Point +from shapely.validation import explain_validity + + +class ValidationTestCase(unittest.TestCase): + def test_valid(self): + assert explain_validity(Point(0, 0)) == "Valid Geometry" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_vectorized.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_vectorized.py new file mode 100644 index 0000000000000000000000000000000000000000..c42a6fb9e5c1714f95ec2ed56198ad775c79f0b8 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_vectorized.py @@ -0,0 +1,108 @@ +import unittest + +import numpy as np +import pytest + +from shapely.geometry import MultiPolygon, Point, box + + +@pytest.mark.filterwarnings("ignore:The 'shapely.vectorized:") +class VectorizedContainsTestCase(unittest.TestCase): + def assertContainsResults(self, geom, x, y): + from shapely.vectorized import contains + + result = contains(geom, x, y) + x = np.asanyarray(x) + y = np.asanyarray(y) + + self.assertIsInstance(result, np.ndarray) + self.assertEqual(result.dtype, bool) + + result_flat = result.flat + x_flat, y_flat = x.flat, y.flat + + # Do the equivalent operation, only slowly, comparing the result + # as we go. + for idx in range(x.size): + assert result_flat[idx] == geom.contains(Point(x_flat[idx], y_flat[idx])) + return result + + def construct_torus(self): + point = Point(0, 0) + return point.buffer(5).symmetric_difference(point.buffer(2.5)) + + def test_contains_poly(self): + y, x = np.mgrid[-10:10:5j], np.mgrid[-5:15:5j] + self.assertContainsResults(self.construct_torus(), x, y) + + def test_contains_point(self): + y, x = np.mgrid[-10:10:5j], np.mgrid[-5:15:5j] + self.assertContainsResults(Point(x[0], y[0]), x, y) + + def test_contains_linestring(self): + y, x = np.mgrid[-10:10:5j], np.mgrid[-5:15:5j] + self.assertContainsResults(Point(x[0], y[0]), x, y) + + def test_contains_multipoly(self): + y, x = np.mgrid[-10:10:5j], np.mgrid[-5:15:5j] + # Construct a geometry of the torus cut in half vertically. + cut_poly = box(-1, -10, -2.5, 10) + geom = self.construct_torus().difference(cut_poly) + assert isinstance(geom, MultiPolygon) + self.assertContainsResults(geom, x, y) + + def test_y_array_order(self): + y, x = np.mgrid[-10:10:5j, -5:15:5j] + y = y.copy("f") + self.assertContainsResults(self.construct_torus(), x, y) + + def test_x_array_order(self): + y, x = np.mgrid[-10:10:5j, -5:15:5j] + x = x.copy("f") + self.assertContainsResults(self.construct_torus(), x, y) + + def test_xy_array_order(self): + y, x = np.mgrid[-10:10:5j, -5:15:5j] + x = x.copy("f") + y = y.copy("f") + result = self.assertContainsResults(self.construct_torus(), x, y) + # Preserve the order + assert result.flags["F_CONTIGUOUS"] + + def test_array_dtype(self): + y, x = np.mgrid[-10:10:5j], np.mgrid[-5:15:5j] + x = x.astype(np.int16) + self.assertContainsResults(self.construct_torus(), x, y) + + def test_array_2d(self): + y, x = np.mgrid[-10:10:15j, -5:15:16j] + result = self.assertContainsResults(self.construct_torus(), x, y) + assert result.shape == x.shape + + def test_shapely_xy_attr_contains(self): + g = Point(0, 0).buffer(10.0) + self.assertContainsResults(self.construct_torus(), *g.exterior.xy) + + +@pytest.mark.filterwarnings("ignore:The 'shapely.vectorized:") +class VectorizedTouchesTestCase(unittest.TestCase): + def test_touches(self): + from shapely.vectorized import touches + + y, x = np.mgrid[-2:3:6j, -1:3:5j] + geom = box(0, -1, 2, 2) + result = touches(geom, x, y) + expected = np.array( + [ + [False, False, False, False, False], + [False, True, True, True, False], + [False, True, False, True, False], + [False, True, False, True, False], + [False, True, True, True, False], + [False, False, False, False, False], + ], + dtype=bool, + ) + from numpy.testing import assert_array_equal + + assert_array_equal(result, expected) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_voronoi_diagram.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_voronoi_diagram.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5ef0ca660c48eb75e9df7781b3129baa797a6f --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_voronoi_diagram.py @@ -0,0 +1,129 @@ +""" +Test cases for Voronoi Diagram creation. + +Overall, I'm trying less to test the correctness of the result +and more to cover input cases and behavior, making sure +that we return a sane result without error or raise a useful one. +""" + +import numpy as np +import pytest + +from shapely.geometry import MultiPoint +from shapely.ops import voronoi_diagram +from shapely.wkt import loads as load_wkt + + +def test_no_regions(): + mp = MultiPoint(points=[(0.5, 0.5)]) + with np.errstate(invalid="ignore"): + regions = voronoi_diagram(mp) + + assert len(regions.geoms) == 0 + + +def test_two_regions(): + mp = MultiPoint(points=[(0.5, 0.5), (1.0, 1.0)]) + regions = voronoi_diagram(mp) + + assert len(regions.geoms) == 2 + + +def test_edges(): + mp = MultiPoint(points=[(0.5, 0.5), (1.0, 1.0)]) + regions = voronoi_diagram(mp, edges=True) + + assert len(regions.geoms) == 1 + # can be LineString or MultiLineString depending on the GEOS version + assert all(r.geom_type.endswith("LineString") for r in regions.geoms) + + +def test_smaller_envelope(): + mp = MultiPoint(points=[(0.5, 0.5), (1.0, 1.0)]) + poly = load_wkt("POLYGON ((0 0, 0.5 0, 0.5 0.5, 0 0.5, 0 0))") + + regions = voronoi_diagram(mp, envelope=poly) + + assert len(regions.geoms) == 2 + assert sum(r.area for r in regions.geoms) > poly.area + + +def test_larger_envelope(): + """When the envelope we specify is larger than the + area of the input feature, the created regions should + expand to fill that area.""" + mp = MultiPoint(points=[(0.5, 0.5), (1.0, 1.0)]) + poly = load_wkt("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))") + + regions = voronoi_diagram(mp, envelope=poly) + + assert len(regions.geoms) == 2 + assert sum(r.area for r in regions.geoms) == poly.area + + +def test_from_polygon(): + poly = load_wkt("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))") + regions = voronoi_diagram(poly) + + assert len(regions.geoms) == 4 + + +def test_from_polygon_with_enough_tolerance(): + poly = load_wkt("POLYGON ((0 0, 0.5 0, 0.5 0.5, 0 0.5, 0 0))") + regions = voronoi_diagram(poly, tolerance=1.0) + + assert len(regions.geoms) == 2 + + +def test_from_polygon_without_enough_tolerance(): + poly = load_wkt("POLYGON ((0 0, 0.5 0, 0.5 0.5, 0 0.5, 0 0))") + with pytest.raises(ValueError) as exc: + voronoi_diagram(poly, tolerance=0.6) + + assert "Could not create Voronoi Diagram with the specified inputs" in str( + exc.value + ) + assert "Try running again with default tolerance value." in str(exc.value) + + +def test_from_polygon_without_floating_point_coordinates(): + poly = load_wkt("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))") + with pytest.raises(ValueError) as exc: + voronoi_diagram(poly, tolerance=0.1) + + assert "Could not create Voronoi Diagram with the specified inputs" in str( + exc.value + ) + assert "Try running again with default tolerance value." in str(exc.value) + + +def test_from_multipoint_without_floating_point_coordinates(): + """A Multipoint with the same "shape" as the above Polygon raises the same error.""" + mp = load_wkt("MULTIPOINT (0 0, 1 0, 1 1, 0 1)") + + with pytest.raises(ValueError) as exc: + voronoi_diagram(mp, tolerance=0.1) + + assert "Could not create Voronoi Diagram with the specified inputs" in str( + exc.value + ) + assert "Try running again with default tolerance value." in str(exc.value) + + +def test_from_multipoint_with_tolerace_without_floating_point_coordinates(): + """This multipoint will not work with a tolerance value.""" + mp = load_wkt("MULTIPOINT (0 0, 1 0, 1 2, 0 1)") + with pytest.raises(ValueError) as exc: + voronoi_diagram(mp, tolerance=0.1) + + assert "Could not create Voronoi Diagram with the specified inputs" in str( + exc.value + ) + assert "Try running again with default tolerance value." in str(exc.value) + + +def test_from_multipoint_without_tolerace_without_floating_point_coordinates(): + """But it's fine without it.""" + mp = load_wkt("MULTIPOINT (0 0, 1 0, 1 2, 0 1)") + regions = voronoi_diagram(mp) + assert len(regions.geoms) == 4 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_wkb.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_wkb.py new file mode 100644 index 0000000000000000000000000000000000000000..b5993d9044ac6fde3a61eea1c80066e2c547639e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_wkb.py @@ -0,0 +1,176 @@ +import binascii +import math +import struct +import sys + +import pytest + +from shapely import wkt +from shapely.geometry import Point +from shapely.tests.legacy.conftest import shapely20_todo +from shapely.wkb import dump, dumps, load, loads + + +@pytest.fixture(scope="module") +def some_point(): + return Point(1.2, 3.4) + + +def bin2hex(value): + return binascii.b2a_hex(value).upper().decode("utf-8") + + +def hex2bin(value): + return binascii.a2b_hex(value) + + +def hostorder(fmt, value): + """Re-pack a hex WKB value to native endianness if needed + + This routine does not understand WKB format, so it must be provided a + struct module format string, without initial indicator character ("@=<>!"), + which will be interpreted as big- or little-endian with standard sizes + depending on the endian flag in the first byte of the value. + """ + + if fmt and fmt[0] in "@=<>!": + raise ValueError("Initial indicator character, one of @=<>!, in fmt") + if not fmt or fmt[0] not in "cbB": + raise ValueError("Missing endian flag in fmt") + + (hexendian,) = struct.unpack(fmt[0], hex2bin(value[:2])) + hexorder = {0: ">", 1: "<"}[hexendian] + sysorder = {"little": "<", "big": ">"}[sys.byteorder] + if hexorder == sysorder: + return value # Nothing to do + + return bin2hex( + struct.pack( + sysorder + fmt, + {">": 0, "<": 1}[sysorder], + *struct.unpack(hexorder + fmt, hex2bin(value))[1:], + ) + ) + + +def test_dumps_srid(some_point): + result = dumps(some_point) + assert bin2hex(result) == hostorder( + "BIdd", "0101000000333333333333F33F3333333333330B40" + ) + result = dumps(some_point, srid=4326) + assert bin2hex(result) == hostorder( + "BIIdd", "0101000020E6100000333333333333F33F3333333333330B40" + ) + + +def test_dumps_endianness(some_point): + result = dumps(some_point) + assert bin2hex(result) == hostorder( + "BIdd", "0101000000333333333333F33F3333333333330B40" + ) + result = dumps(some_point, big_endian=False) + assert bin2hex(result) == "0101000000333333333333F33F3333333333330B40" + result = dumps(some_point, big_endian=True) + assert bin2hex(result) == "00000000013FF3333333333333400B333333333333" + + +def test_dumps_hex(some_point): + result = dumps(some_point, hex=True) + assert result == hostorder("BIdd", "0101000000333333333333F33F3333333333330B40") + + +def test_loads_srid(): + # load a geometry which includes an srid + geom = loads(hex2bin("0101000020E6100000333333333333F33F3333333333330B40")) + assert isinstance(geom, Point) + assert geom.coords[:] == [(1.2, 3.4)] + # by default srid is not exported + result = dumps(geom) + assert bin2hex(result) == hostorder( + "BIdd", "0101000000333333333333F33F3333333333330B40" + ) + # include the srid in the output + result = dumps(geom, include_srid=True) + assert bin2hex(result) == hostorder( + "BIIdd", "0101000020E6100000333333333333F33F3333333333330B40" + ) + # replace geometry srid with another + result = dumps(geom, srid=27700) + assert bin2hex(result) == hostorder( + "BIIdd", "0101000020346C0000333333333333F33F3333333333330B40" + ) + + +def test_loads_hex(some_point): + assert loads(dumps(some_point, hex=True), hex=True) == some_point + + +def test_dump_load_binary(some_point, tmpdir): + file = tmpdir.join("test.wkb") + with open(file, "wb") as file_pointer: + dump(some_point, file_pointer) + with open(file, "rb") as file_pointer: + restored = load(file_pointer) + + assert some_point == restored + + +def test_dump_load_hex(some_point, tmpdir): + file = tmpdir.join("test.wkb") + with open(file, "w") as file_pointer: + dump(some_point, file_pointer, hex=True) + with open(file) as file_pointer: + restored = load(file_pointer, hex=True) + + assert some_point == restored + + +# pygeos handles both bytes and str +@shapely20_todo +def test_dump_hex_load_binary(some_point, tmpdir): + """Asserts that reading a binary file as text (hex mode) fails.""" + file = tmpdir.join("test.wkb") + with open(file, "w") as file_pointer: + dump(some_point, file_pointer, hex=True) + + with pytest.raises(TypeError): + with open(file, "rb") as file_pointer: + load(file_pointer) + + +def test_dump_binary_load_hex(some_point, tmpdir): + """Asserts that reading a text file (hex mode) as binary fails.""" + file = tmpdir.join("test.wkb") + with open(file, "wb") as file_pointer: + dump(some_point, file_pointer) + + # TODO(shapely-2.0) on windows this doesn't seem to error with pygeos, + # but you get back a point with garbage coordinates + if sys.platform == "win32": + with open(file) as file_pointer: + restored = load(file_pointer, hex=True) + assert some_point != restored + return + + with pytest.raises((UnicodeEncodeError, UnicodeDecodeError)): + with open(file) as file_pointer: + load(file_pointer, hex=True) + + +def test_point_empty(): + g = wkt.loads("POINT EMPTY") + result = dumps(g, big_endian=False) + # Use math.isnan for second part of the WKB representation there are + # many byte representations for NaN) + assert result[: -2 * 8] == b"\x01\x01\x00\x00\x00" + coords = struct.unpack("<2d", result[-2 * 8 :]) + assert len(coords) == 2 + assert all(math.isnan(val) for val in coords) + + +def test_point_z_empty(): + g = wkt.loads("POINT Z EMPTY") + assert g.wkb_hex == hostorder( + "BIddd", "0101000080000000000000F87F000000000000F87F000000000000F87F" + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_wkt.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_wkt.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb15b60275e18e0640b2f909fed4e9c81ebcf64 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/test_wkt.py @@ -0,0 +1,61 @@ +from math import pi + +import pytest + +from shapely.geometry import Point +from shapely.wkt import dump, dumps, load, loads + + +@pytest.fixture(scope="module") +def some_point(): + return Point(pi, -pi) + + +@pytest.fixture(scope="module") +def empty_geometry(): + return Point() + + +def test_wkt(some_point): + """.wkt and wkt.dumps() both do not trim by default.""" + assert some_point.wkt == f"POINT ({pi:.15f} {-pi:.15f})" + + +def test_wkt_null(empty_geometry): + assert empty_geometry.wkt == "POINT EMPTY" + + +def test_dump_load(some_point, tmpdir): + file = tmpdir.join("test.wkt") + with open(file, "w") as file_pointer: + dump(some_point, file_pointer) + with open(file) as file_pointer: + restored = load(file_pointer) + + assert some_point == restored + + +def test_dump_load_null_geometry(empty_geometry, tmpdir): + file = tmpdir.join("test.wkt") + with open(file, "w") as file_pointer: + dump(empty_geometry, file_pointer) + with open(file) as file_pointer: + restored = load(file_pointer) + + # This is does not work with __eq__(): + assert empty_geometry.equals(restored) + + +def test_dumps_loads(some_point): + assert dumps(some_point) == f"POINT ({pi:.16f} {-pi:.16f})" + assert loads(dumps(some_point)) == some_point + + +def test_dumps_loads_null_geometry(empty_geometry): + assert dumps(empty_geometry) == "POINT EMPTY" + # This is does not work with __eq__(): + assert loads(dumps(empty_geometry)).equals(empty_geometry) + + +def test_dumps_precision(some_point): + assert dumps(some_point, rounding_precision=4) == f"POINT ({pi:.4f} {-pi:.4f})" diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/threading_test.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/threading_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f03fb5523102f11dea4f0ac15cfe4d2a069324cb --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/legacy/threading_test.py @@ -0,0 +1,44 @@ +import threading +from binascii import b2a_hex + + +def main(): + num_threads = 10 + use_threads = True + + if not use_threads: + # Run core code + runShapelyBuilding() + else: + threads = [ + threading.Thread(target=runShapelyBuilding, name=str(i), args=(i,)) + for i in range(num_threads) + ] + for t in threads: + t.start() + for t in threads: + t.join() + + +def runShapelyBuilding(num): + print(f"{num}: Running shapely tests on wkb") + import shapely.geos + + print(f"{num} GEOS Handle: {shapely.geos.lgeos.geos_handle}") + import shapely.wkb + import shapely.wkt + + p = shapely.wkt.loads("POINT (0 0)") + print(f"{num} WKT: {shapely.wkt.dumps(p)}") + wkb = shapely.wkb.dumps(p) + print(f"{num} WKB: {b2a_hex(wkb)}") + + for i in range(10): + shapely.wkb.loads(wkb) + + print(f"{num} GEOS Handle: {shapely.geos.lgeos.geos_handle}") + print(f"Done {num}") + + +if __name__ == "__main__": + main() diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_constructive.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_constructive.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2c1380f0cd5475a40a562b5e796aa970158f51 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_constructive.py @@ -0,0 +1,1390 @@ +import numpy as np +import pytest + +import shapely +from shapely import ( + Geometry, + GeometryCollection, + GEOSException, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, + geos_version, +) +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + ArrayLike, + all_types, + empty, + empty_line_string, + empty_point, + empty_polygon, + ignore_invalid, + line_string, + multi_point, + point, + point_z, +) + +geos39 = geos_version[0:2] == (3, 9) +geos310 = geos_version[0:2] == (3, 10) +geos311 = geos_version[0:2] == (3, 11) + +CONSTRUCTIVE_NO_ARGS = ( + shapely.boundary, + shapely.centroid, + shapely.convex_hull, + pytest.param( + shapely.concave_hull, + marks=pytest.mark.skipif( + shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11" + ), + ), + shapely.envelope, + shapely.extract_unique_points, + shapely.minimum_clearance_line, + shapely.node, + shapely.normalize, + shapely.point_on_surface, + pytest.param( + shapely.constrained_delaunay_triangles, + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10" + ), + ), +) + +CONSTRUCTIVE_FLOAT_ARG = ( + shapely.buffer, + shapely.offset_curve, + shapely.delaunay_triangles, + shapely.simplify, + shapely.voronoi_polygons, +) + + +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("func", CONSTRUCTIVE_NO_ARGS) +def test_no_args_array(geometry, func): + if ( + geometry.is_empty + and shapely.get_num_geometries(geometry) > 0 + and func is shapely.node + and ( + (geos39 and geos_version < (3, 9, 3)) + or (geos310 and geos_version < (3, 10, 3)) + ) + ): # GEOS GH-601 + pytest.xfail("GEOS < 3.9.3 or GEOS < 3.10.3 crashes with empty geometries") + actual = func([geometry, geometry]) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("func", CONSTRUCTIVE_FLOAT_ARG) +def test_float_arg_array(geometry, func): + if ( + func is shapely.offset_curve + and shapely.get_type_id(geometry) not in [1, 2] + and shapely.geos_version < (3, 11, 0) + ): + with pytest.raises(GEOSException, match="only accept linestrings"): + func([geometry, geometry], 0.0) + return + # voronoi_polygons emits an "invalid" warning when supplied with an empty + # point (see https://github.com/libgeos/geos/issues/515) + with ignore_invalid( + func is shapely.voronoi_polygons + and shapely.get_type_id(geometry) == 0 + and shapely.geos_version < (3, 12, 0) + ): + actual = func([geometry, geometry], 0.0) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("reference", all_types) +def test_snap_array(geometry, reference): + actual = shapely.snap([geometry, geometry], [reference, reference], tolerance=1.0) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + +@pytest.mark.parametrize("func", CONSTRUCTIVE_NO_ARGS) +def test_no_args_missing(func): + actual = func(None) + assert actual is None + + +@pytest.mark.parametrize("func", CONSTRUCTIVE_FLOAT_ARG) +def test_float_arg_missing(func): + actual = func(None, 1.0) + assert actual is None + + +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("func", CONSTRUCTIVE_FLOAT_ARG) +def test_float_arg_nan(geometry, func): + actual = func(geometry, float("nan")) + assert actual is None + + +def test_buffer_cap_style_invalid(): + with pytest.raises(ValueError, match="'invalid' is not a valid option"): + shapely.buffer(point, 1, cap_style="invalid") + + +def test_buffer_join_style_invalid(): + with pytest.raises(ValueError, match="'invalid' is not a valid option"): + shapely.buffer(point, 1, join_style="invalid") + + +def test_snap_none(): + actual = shapely.snap(None, point, tolerance=1.0) + assert actual is None + + +@pytest.mark.parametrize("geometry", all_types) +def test_snap_nan_float(geometry): + actual = shapely.snap(geometry, point, tolerance=np.nan) + assert actual is None + + +def test_build_area_none(): + actual = shapely.build_area(None) + assert actual is None + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, empty), # a point has no area + (line_string, empty), # a line string has no area + # geometry collection of two polygons are combined into one + ( + GeometryCollection( + [ + Polygon([(0, 0), (0, 3), (3, 3), (3, 0), (0, 0)]), + Polygon([(1, 1), (2, 2), (1, 2), (1, 1)]), + ] + ), + Polygon( + [(0, 0), (0, 3), (3, 3), (3, 0), (0, 0)], + holes=[[(1, 1), (2, 2), (1, 2), (1, 1)]], + ), + ), + (empty, empty), + ([empty], [empty]), + ], +) +def test_build_area(geom, expected): + actual = shapely.build_area(geom) + assert actual is not expected + assert actual == expected + + +def test_make_valid_none(): + actual = shapely.make_valid(None) + assert actual is None + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), # a valid geometry stays the same (but is copied) + # an L shaped polygon without area is converted to a multilinestring + ( + Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]), + MultiLineString([((1, 1), (1, 2)), ((0, 0), (1, 1))]), + ), + # a polygon with self-intersection (bowtie) is converted into polygons + ( + Polygon([(0, 0), (2, 2), (2, 0), (0, 2), (0, 0)]), + MultiPolygon( + [ + Polygon([(1, 1), (2, 2), (2, 0), (1, 1)]), + Polygon([(0, 0), (0, 2), (1, 1), (0, 0)]), + ] + ), + ), + (empty, empty), + ([empty], [empty]), + ], +) +def test_make_valid(geom, expected): + actual = shapely.make_valid(geom) + assert actual is not expected + # normalize needed to handle variation in output across GEOS versions + assert shapely.normalize(actual) == expected + + +@pytest.mark.parametrize( + "geom,expected", + [ + (all_types, all_types), + # first polygon is valid, second polygon has self-intersection + ( + [ + Polygon([(0, 0), (2, 2), (0, 2), (0, 0)]), + Polygon([(0, 0), (2, 2), (2, 0), (0, 2), (0, 0)]), + ], + [ + Polygon([(0, 0), (2, 2), (0, 2), (0, 0)]), + MultiPolygon( + [ + Polygon([(1, 1), (0, 0), (0, 2), (1, 1)]), + Polygon([(1, 1), (2, 2), (2, 0), (1, 1)]), + ] + ), + ], + ), + ([point, None, empty], [point, None, empty]), + ], +) +def test_make_valid_1d(geom, expected): + actual = shapely.make_valid(geom) + # normalize needed to handle variation in output across GEOS versions + assert np.all(shapely.normalize(actual) == shapely.normalize(expected)) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), # a valid geometry stays the same (but is copied) + # an L shaped polygon without area is converted to a linestring + ( + Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]), + LineString([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]), + ), + # a polygon with self-intersection (bowtie) is converted into polygons + ( + Polygon([(0, 0), (2, 2), (2, 0), (0, 2), (0, 0)]), + MultiPolygon( + [ + Polygon([(1, 1), (2, 2), (2, 0), (1, 1)]), + Polygon([(0, 0), (0, 2), (1, 1), (0, 0)]), + ] + ), + ), + (empty, empty), + ([empty], [empty]), + ], +) +def test_make_valid_structure(geom, expected): + actual = shapely.make_valid(geom, method="structure") + assert actual is not expected + # normalize needed to handle variation in output across GEOS versions + assert shapely.normalize(actual) == expected + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), # a valid geometry stays the same (but is copied) + # an L shaped polygon without area is converted to Empty Polygon + ( + Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]), + Polygon(), + ), + # a polygon with self-intersection (bowtie) is converted into polygons + ( + Polygon([(0, 0), (2, 2), (2, 0), (0, 2), (0, 0)]), + MultiPolygon( + [ + Polygon([(1, 1), (2, 2), (2, 0), (1, 1)]), + Polygon([(0, 0), (0, 2), (1, 1), (0, 0)]), + ] + ), + ), + (empty, empty), + ([empty], [empty]), + ], +) +def test_make_valid_structure_keep_collapsed_false(geom, expected): + actual = shapely.make_valid(geom, method="structure", keep_collapsed=False) + assert actual is not expected + # normalize needed to handle variation in output across GEOS versions + assert shapely.normalize(actual) == expected + + +@pytest.mark.skipif(shapely.geos_version >= (3, 10, 0), reason="GEOS >= 3.10") +def test_make_valid_structure_unsupported_geos(): + with pytest.raises( + ValueError, match="The 'structure' method is only available in GEOS >= 3.10.0" + ): + _ = shapely.make_valid(Point(), method="structure") + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "method, keep_collapsed, error_type, error", + [ + ( + np.array(["linework", "structure"]), + True, + TypeError, + "method only accepts scalar values", + ), + ( + "linework", + [True, False], + TypeError, + "keep_collapsed only accepts scalar values", + ), + ("unknown", True, ValueError, "Unknown method: unknown"), + ( + "linework", + False, + ValueError, + "The 'linework' method does not support 'keep_collapsed=False'", + ), + ], +) +def test_make_valid_invalid_params(method, keep_collapsed, error_type, error): + with pytest.raises(error_type, match=error): + _ = shapely.make_valid(Point(), method=method, keep_collapsed=keep_collapsed) + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), # a point is always in normalized form + # order coordinates of linestrings and parts of multi-linestring + ( + MultiLineString([((1, 1), (0, 0)), ((1, 1), (1, 2))]), + MultiLineString([((1, 1), (1, 2)), ((0, 0), (1, 1))]), + ), + ], +) +def test_normalize(geom, expected): + actual = shapely.normalize(geom) + assert actual == expected + + +def test_offset_curve_empty(): + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Empty geometries emit an "invalid" warning + # (see https://github.com/libgeos/geos/issues/515) + actual = shapely.offset_curve(empty_line_string, 2.0) + assert shapely.is_empty(actual) + + +def test_offset_curve_distance_array(): + # check that kwargs are passed through + result = shapely.offset_curve([line_string, line_string], [-2.0, -3.0]) + assert result[0] == shapely.offset_curve(line_string, -2.0) + assert result[1] == shapely.offset_curve(line_string, -3.0) + + +def test_offset_curve_kwargs(): + # check that kwargs are passed through + result1 = shapely.offset_curve( + line_string, -2.0, quad_segs=2, join_style="mitre", mitre_limit=2.0 + ) + result2 = shapely.offset_curve(line_string, -2.0) + assert result1 != result2 + + +def test_offset_curve_non_scalar_kwargs(): + msg = "only accepts scalar values" + with pytest.raises(TypeError, match=msg): + shapely.offset_curve([line_string, line_string], 1, quad_segs=np.array([8, 9])) + + with pytest.raises(TypeError, match=msg): + shapely.offset_curve( + [line_string, line_string], 1, join_style=["round", "bevel"] + ) + + with pytest.raises(TypeError, match=msg): + shapely.offset_curve([line_string, line_string], 1, mitre_limit=[5.0, 6.0]) + + +def test_offset_curve_join_style_invalid(): + with pytest.raises(ValueError, match="'invalid' is not a valid option"): + shapely.offset_curve(line_string, 1.0, join_style="invalid") + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11") +@pytest.mark.parametrize( + "geom,expected", + [ + (LineString([(0, 0), (0, 0), (1, 0)]), LineString([(0, 0), (1, 0)])), + ( + LinearRing([(0, 0), (1, 2), (1, 2), (1, 3), (0, 0)]), + LinearRing([(0, 0), (1, 2), (1, 3), (0, 0)]), + ), + ( + Polygon([(0, 0), (0, 0), (1, 0), (1, 1), (1, 0), (0, 0)]), + Polygon([(0, 0), (1, 0), (1, 1), (1, 0), (0, 0)]), + ), + ( + Polygon( + [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)], + holes=[[(2, 2), (2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ), + Polygon( + [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ), + ), + ( + MultiPolygon( + [ + Polygon([(0, 0), (0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(2, 2), (2, 2), (2, 3), (3, 3), (3, 2), (2, 2)]), + ] + ), + MultiPolygon( + [ + Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(2, 2), (2, 3), (3, 3), (3, 2), (2, 2)]), + ] + ), + ), + # points are unchanged + (point, point), + (point_z, point_z), + (multi_point, multi_point), + # empty geometries are unchanged + (empty_point, empty_point), + (empty_line_string, empty_line_string), + (empty, empty), + (empty_polygon, empty_polygon), + ], +) +def test_remove_repeated_points(geom, expected): + assert_geometries_equal(shapely.remove_repeated_points(geom, 0), expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize( + "geom, tolerance", [[Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), 2]] +) +def test_remove_repeated_points_invalid_result(geom, tolerance): + # Requiring GEOS 3.12 instead of 3.11 + # (GEOS 3.11 had a bug causing this to intermittently not fail) + with pytest.raises(shapely.GEOSException, match="Invalid number of points"): + shapely.remove_repeated_points(geom, tolerance) + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11") +def test_remove_repeated_points_none(): + assert shapely.remove_repeated_points(None, 1) is None + assert shapely.remove_repeated_points([None], 1).tolist() == [None] + + geometry = LineString([(0, 0), (0, 0), (1, 1)]) + expected = LineString([(0, 0), (1, 1)]) + result = shapely.remove_repeated_points([None, geometry], 1) + assert result[0] is None + assert_geometries_equal(result[1], expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11") +@pytest.mark.parametrize("geom, tolerance", [("Not a geometry", 1), (1, 1)]) +def test_remove_repeated_points_invalid_type(geom, tolerance): + with pytest.raises(TypeError, match="One of the arguments is of incorrect type"): + shapely.remove_repeated_points(geom, tolerance) + + +@pytest.mark.parametrize( + "geom,expected", + [ + (LineString([(0, 0), (1, 2)]), LineString([(1, 2), (0, 0)])), + ( + LinearRing([(0, 0), (1, 2), (1, 3), (0, 0)]), + LinearRing([(0, 0), (1, 3), (1, 2), (0, 0)]), + ), + ( + Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + ), + ( + Polygon( + [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ), + Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (4, 2), (4, 4), (2, 4), (2, 2)]], + ), + ), + ( + MultiLineString([[(0, 0), (1, 2)], [(3, 3), (4, 4)]]), + MultiLineString([[(1, 2), (0, 0)], [(4, 4), (3, 3)]]), + ), + ( + MultiPolygon( + [ + Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(2, 2), (2, 3), (3, 3), (3, 2), (2, 2)]), + ] + ), + MultiPolygon( + [ + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + Polygon([(2, 2), (3, 2), (3, 3), (2, 3), (2, 2)]), + ] + ), + ), + # points are unchanged + (point, point), + (point_z, point_z), + (multi_point, multi_point), + # empty geometries are unchanged + (empty_point, empty_point), + (empty_line_string, empty_line_string), + (empty, empty), + (empty_polygon, empty_polygon), + ], +) +def test_reverse(geom, expected): + assert_geometries_equal(shapely.reverse(geom), expected) + + +def test_reverse_none(): + assert shapely.reverse(None) is None + assert shapely.reverse([None]).tolist() == [None] + + geometry = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + expected = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + result = shapely.reverse([None, geometry]) + assert result[0] is None + assert_geometries_equal(result[1], expected) + + +@pytest.mark.parametrize("geom", ["Not a geometry", 1]) +def test_reverse_invalid_type(geom): + with pytest.raises(TypeError, match="One of the arguments is of incorrect type"): + shapely.reverse(geom) + + +@pytest.mark.parametrize( + "geom,expected", + [ + # Point outside + (Point(0, 0), GeometryCollection()), + # Point inside + (Point(15, 15), Point(15, 15)), + # Point on boundary + (Point(15, 10), GeometryCollection()), + # Line outside + (LineString([(0, 0), (-5, 5)]), GeometryCollection()), + # Line inside + (LineString([(15, 15), (16, 15)]), LineString([(15, 15), (16, 15)])), + # Line on boundary + (LineString([(10, 15), (10, 10), (15, 10)]), GeometryCollection()), + # Line splitting rectangle + (LineString([(10, 5), (25, 20)]), LineString([(15, 10), (20, 15)])), + ], +) +def test_clip_by_rect(geom, expected): + actual = shapely.clip_by_rect(geom, 10, 10, 20, 20) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "geom, rect, expected", + [ + # Polygon hole (CCW) fully on rectangle boundary""" + ( + Polygon( + ((0, 0), (0, 30), (30, 30), (30, 0), (0, 0)), + holes=[((10, 10), (20, 10), (20, 20), (10, 20), (10, 10))], + ), + (10, 10, 20, 20), + GeometryCollection(), + ), + # Polygon hole (CW) fully on rectangle boundary""" + ( + Polygon( + ((0, 0), (0, 30), (30, 30), (30, 0), (0, 0)), + holes=[((10, 10), (10, 20), (20, 20), (20, 10), (10, 10))], + ), + (10, 10, 20, 20), + GeometryCollection(), + ), + # Polygon fully within rectangle""" + ( + Polygon( + ((1, 1), (1, 30), (30, 30), (30, 1), (1, 1)), + holes=[((10, 10), (20, 10), (20, 20), (10, 20), (10, 10))], + ), + (0, 0, 40, 40), + Polygon( + ((1, 1), (1, 30), (30, 30), (30, 1), (1, 1)), + holes=[((10, 10), (20, 10), (20, 20), (10, 20), (10, 10))], + ), + ), + # Polygon overlapping rectanglez + ( + Polygon( + [(0, 0), (0, 30), (30, 30), (30, 0), (0, 0)], + holes=[[(10, 10), (20, 10), (20, 20), (10, 20), (10, 10)]], + ), + (5, 5, 15, 15), + Polygon([(5, 5), (5, 15), (10, 15), (10, 10), (15, 10), (15, 5), (5, 5)]), + ), + ], +) +def test_clip_by_rect_polygon(geom, rect, expected): + actual = shapely.clip_by_rect(geom, *rect) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("geometry", all_types) +def test_clip_by_rect_array(geometry): + if ( + geometry.is_empty + and shapely.get_type_id(geometry) == shapely.GeometryType.POINT + and ( + (geos39 and geos_version < (3, 9, 5)) + or (geos310 and geos_version < (3, 10, 6)) + or (geos311 and geos_version < (3, 11, 3)) + ) + ): + # GEOS GH-913 + with pytest.raises(GEOSException): + shapely.clip_by_rect([geometry, geometry], 0.0, 0.0, 1.0, 1.0) + return + actual = shapely.clip_by_rect([geometry, geometry], 0.0, 0.0, 1.0, 1.0) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + +def test_clip_by_rect_missing(): + actual = shapely.clip_by_rect(None, 0, 0, 1, 1) + assert actual is None + + +@pytest.mark.parametrize("geom", [empty, empty_line_string, empty_polygon]) +def test_clip_by_rect_empty(geom): + # TODO empty point + actual = shapely.clip_by_rect(geom, 0, 0, 1, 1) + assert actual == GeometryCollection() + + +def test_clip_by_rect_non_scalar_kwargs(): + msg = "only accepts scalar values" + with pytest.raises(TypeError, match=msg): + shapely.clip_by_rect([line_string, line_string], 0, 0, 1, np.array([0, 1])) + + +def test_polygonize(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + LineString([(1, 1), (1, 0)]), + LineString([(1, 0), (0, 0)]), + LineString([(5, 5), (6, 6)]), + Point(0, 0), + None, + ] + result = shapely.polygonize(lines) + assert shapely.get_type_id(result) == 7 # GeometryCollection + expected = GeometryCollection( + [ + Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), + Polygon([(1, 1), (0, 0), (0, 1), (1, 1)]), + ] + ) + assert result == expected + + +def test_polygonize_array(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + ] + expected = GeometryCollection([Polygon([(1, 1), (0, 0), (0, 1), (1, 1)])]) + result = shapely.polygonize(np.array(lines)) + assert isinstance(result, shapely.Geometry) + assert result == expected + + result = shapely.polygonize(np.array([lines])) + assert isinstance(result, np.ndarray) + assert result.shape == (1,) + assert result[0] == expected + + arr = np.array([lines, lines]) + assert arr.shape == (2, 3) + result = shapely.polygonize(arr) + assert isinstance(result, np.ndarray) + assert result.shape == (2,) + assert result[0] == expected + assert result[1] == expected + + arr = np.array([[lines, lines], [lines, lines], [lines, lines]]) + assert arr.shape == (3, 2, 3) + result = shapely.polygonize(arr) + assert isinstance(result, np.ndarray) + assert result.shape == (3, 2) + for res in result.flatten(): + assert res == expected + + +def test_polygonize_array_axis(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + ] + arr = np.array([lines, lines]) # shape (2, 3) + result = shapely.polygonize(arr, axis=1) + assert result.shape == (2,) + result = shapely.polygonize(arr, axis=0) + assert result.shape == (3,) + + +def test_polygonize_missing(): + # set of geometries that is all missing + result = shapely.polygonize([None, None]) + assert result == GeometryCollection() + + +def test_polygonize_full(): + lines = [ + None, + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + LineString([(1, 1), (1, 0)]), + None, + LineString([(1, 0), (0, 0)]), + LineString([(5, 5), (6, 6)]), + LineString([(1, 1), (100, 100)]), + Point(0, 0), + None, + ] + result = shapely.polygonize_full(lines) + assert len(result) == 4 + assert all(shapely.get_type_id(geom) == 7 for geom in result) # GeometryCollection + polygons, cuts, dangles, invalid = result + expected_polygons = GeometryCollection( + [ + Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), + Polygon([(1, 1), (0, 0), (0, 1), (1, 1)]), + ] + ) + assert polygons == expected_polygons + assert cuts == GeometryCollection() + expected_dangles = GeometryCollection( + [LineString([(1, 1), (100, 100)]), LineString([(5, 5), (6, 6)])] + ) + assert dangles == expected_dangles + assert invalid == GeometryCollection() + + +def test_polygonize_full_array(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + ] + expected = GeometryCollection([Polygon([(1, 1), (0, 0), (0, 1), (1, 1)])]) + result = shapely.polygonize_full(np.array(lines)) + assert len(result) == 4 + assert all(isinstance(geom, shapely.Geometry) for geom in result) + assert result[0] == expected + assert all(geom == GeometryCollection() for geom in result[1:]) + + result = shapely.polygonize_full(np.array([lines])) + assert len(result) == 4 + assert all(isinstance(geom, np.ndarray) for geom in result) + assert all(geom.shape == (1,) for geom in result) + assert result[0][0] == expected + assert all(geom[0] == GeometryCollection() for geom in result[1:]) + + arr = np.array([lines, lines]) + assert arr.shape == (2, 3) + result = shapely.polygonize_full(arr) + assert len(result) == 4 + assert all(isinstance(arr, np.ndarray) for arr in result) + assert all(arr.shape == (2,) for arr in result) + assert result[0][0] == expected + assert result[0][1] == expected + assert all(g == GeometryCollection() for geom in result[1:] for g in geom) + + arr = np.array([[lines, lines], [lines, lines], [lines, lines]]) + assert arr.shape == (3, 2, 3) + result = shapely.polygonize_full(arr) + assert len(result) == 4 + assert all(isinstance(arr, np.ndarray) for arr in result) + assert all(arr.shape == (3, 2) for arr in result) + for res in result[0].flatten(): + assert res == expected + for arr in result[1:]: + for res in arr.flatten(): + assert res == GeometryCollection() + + +def test_polygonize_full_array_axis(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + ] + arr = np.array([lines, lines]) # shape (2, 3) + result = shapely.polygonize_full(arr, axis=1) + assert len(result) == 4 + assert all(arr.shape == (2,) for arr in result) + result = shapely.polygonize_full(arr, axis=0) + assert len(result) == 4 + assert all(arr.shape == (3,) for arr in result) + + +def test_polygonize_full_missing(): + # set of geometries that is all missing + result = shapely.polygonize_full([None, None]) + assert len(result) == 4 + assert all(geom == GeometryCollection() for geom in result) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("max_segment_length", [-1, 0]) +def test_segmentize_invalid_max_segment_length(geometry, max_segment_length): + with pytest.raises(GEOSException, match="IllegalArgumentException"): + shapely.segmentize(geometry, max_segment_length=max_segment_length) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize("geometry", all_types) +def test_segmentize_max_segment_length_nan(geometry): + actual = shapely.segmentize(geometry, max_segment_length=np.nan) + assert actual is None + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry", [empty, empty_point, empty_line_string, empty_polygon] +) +def test_segmentize_empty(geometry): + actual = shapely.segmentize(geometry, max_segment_length=5) + assert_geometries_equal(actual, geometry) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize("geometry", [point, point_z, multi_point]) +def test_segmentize_no_change(geometry): + actual = shapely.segmentize(geometry, max_segment_length=5) + assert_geometries_equal(actual, geometry) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_segmentize_none(): + assert shapely.segmentize(None, max_segment_length=5) is None + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,tolerance, expected", + [ + # tolerance greater than max edge length, no change + ( + LineString([(0, 0), (0, 10)]), + 20, + LineString([(0, 0), (0, 10)]), + ), + ( + Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]), + 20, + Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]), + ), + # tolerance causes one vertex per segment + ( + LineString([(0, 0), (0, 10)]), + 5, + LineString([(0, 0), (0, 5), (0, 10)]), + ), + ( + Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]), + 5, + Polygon( + [ + (0, 0), + (5, 0), + (10, 0), + (10, 5), + (10, 10), + (5, 10), + (0, 10), + (0, 5), + (0, 0), + ] + ), + ), + # ensure input arrays are broadcast correctly + ( + [ + LineString([(0, 0), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + 5, + [ + LineString([(0, 0), (0, 5), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + ), + ( + [ + LineString([(0, 0), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + [5], + [ + LineString([(0, 0), (0, 5), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + ), + ( + [ + LineString([(0, 0), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + [5, 1.5], + [ + LineString([(0, 0), (0, 5), (0, 10)]), + LineString([(0, 0), (0, 1), (0, 2)]), + ], + ), + ], +) +def test_segmentize(geometry, tolerance, expected): + actual = shapely.segmentize(geometry, tolerance) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("geometry", all_types) +def test_minimum_bounding_circle_all_types(geometry): + actual = shapely.minimum_bounding_circle([geometry, geometry]) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + actual = shapely.minimum_bounding_circle(None) + assert actual is None + + +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + Polygon([(0, 5), (5, 10), (10, 5), (5, 0), (0, 5)]), + shapely.buffer(Point(5, 5), 5), + ), + ( + LineString([(1, 0), (1, 10)]), + shapely.buffer(Point(1, 5), 5), + ), + ( + MultiPoint([(2, 2), (4, 2)]), + shapely.buffer(Point(3, 2), 1), + ), + ( + Point(2, 2), + Point(2, 2), + ), + ( + GeometryCollection(), + Polygon(), + ), + ], +) +def test_minimum_bounding_circle(geometry, expected): + actual = shapely.minimum_bounding_circle(geometry) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("geometry", all_types) +def test_oriented_envelope_all_types(geometry): + actual = shapely.oriented_envelope([geometry, geometry]) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + actual = shapely.oriented_envelope(None) + assert actual is None + + +@pytest.mark.parametrize( + "func", [shapely.oriented_envelope, shapely.minimum_rotated_rectangle] +) +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + MultiPoint([(1.0, 1.0), (1.0, 5.0), (3.0, 6.0), (4.0, 2.0), (5.0, 5.0)]), + Polygon([(1.0, 1.0), (1.0, 6.0), (5.0, 6.0), (5.0, 1.0), (1.0, 1.0)]), + ), + ( + LineString([(1, 1), (5, 1), (10, 10)]), + Polygon([(1, 1), (3, -1), (12, 8), (10, 10), (1, 1)]), + ), + ( + Polygon([(1, 1), (15, 1), (5, 9), (1, 1)]), + Polygon([(1.0, 1.0), (5.0, 9.0), (16.2, 3.4), (12.2, -4.6), (1.0, 1.0)]), + ), + ( + LineString([(1, 1), (10, 1)]), + LineString([(1, 1), (10, 1)]), + ), + ( + Point(2, 2), + Point(2, 2), + ), + ( + GeometryCollection(), + Polygon(), + ), + ], +) +def test_oriented_envelope(geometry, expected, func): + actual = func(geometry) + assert_geometries_equal(actual, expected, normalize=True, tolerance=1e-3) + + +@pytest.mark.skipif(shapely.geos_version >= (3, 12, 0), reason="GEOS >= 3.12") +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + MultiPoint([(1.0, 1.0), (1.0, 5.0), (3.0, 6.0), (4.0, 2.0), (5.0, 5.0)]), + Polygon([(-0.2, 1.4), (1.5, 6.5), (5.1, 5.3), (3.4, 0.2), (-0.2, 1.4)]), + ), + ( + LineString([(1, 1), (5, 1), (10, 10)]), + Polygon([(1, 1), (3, -1), (12, 8), (10, 10), (1, 1)]), + ), + ( + Polygon([(1, 1), (15, 1), (5, 9), (1, 1)]), + Polygon([(1.0, 1.0), (1.0, 9.0), (15.0, 9.0), (15.0, 1.0), (1.0, 1.0)]), + ), + ( + LineString([(1, 1), (10, 1)]), + LineString([(1, 1), (10, 1)]), + ), + ( + Point(2, 2), + Point(2, 2), + ), + ( + GeometryCollection(), + Polygon(), + ), + ], +) +def test_oriented_envelope_pre_geos_312(geometry, expected): + # use private method (similar as direct shapely.lib.oriented_envelope) + # to cover the C code for older GEOS versions + actual = shapely.constructive._oriented_envelope_geos(geometry) + assert_geometries_equal(actual, expected, normalize=True, tolerance=1e-3) + + +def test_oriented_evelope_array_like(): + # https://github.com/shapely/shapely/issues/1929 + # because we have a custom python implementation, need to ensure this has + # the same capabilities as numpy ufuncs to work with array-likes + geometries = [Point(1, 1).buffer(1), Point(2, 2).buffer(1)] + actual = shapely.oriented_envelope(ArrayLike(geometries)) + assert isinstance(actual, ArrayLike) + expected = shapely.oriented_envelope(geometries) + assert_geometries_equal(np.asarray(actual), expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11") +def test_concave_hull_kwargs(): + p = Point(10, 10) + mp = MultiPoint(p.buffer(5).exterior.coords[:] + p.buffer(4).exterior.coords[:]) + + result1 = shapely.concave_hull(mp, ratio=0.5) + assert len(result1.interiors) == 0 + result2 = shapely.concave_hull(mp, ratio=0.5, allow_holes=True) + assert len(result2.interiors) == 1 + + result3 = shapely.concave_hull(mp, ratio=0) + result4 = shapely.concave_hull(mp, ratio=1) + assert shapely.get_num_coordinates(result4) < shapely.get_num_coordinates(result3) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +class TestConstrainedDelaunayTriangulation: + """ + Only testing the number of triangles and their type here. + This doesn't actually test the points in the resulting geometries. + + """ + + def test_poly(self): + polys = shapely.constrained_delaunay_triangles( + Polygon([(10, 10), (20, 40), (90, 90), (90, 10), (10, 10)]) + ) + assert len(polys.geoms) == 2 + for p in polys.geoms: + assert isinstance(p, Polygon) + + def test_multi_polygon(self): + multipoly = MultiPolygon( + [ + Polygon(((50, 30), (60, 30), (100, 100), (50, 30))), + Polygon(((10, 10), (20, 40), (90, 90), (90, 10), (10, 10))), + ] + ) + polys = shapely.constrained_delaunay_triangles(multipoly) + assert len(polys.geoms) == 3 + for p in polys.geoms: + assert isinstance(p, Polygon) + + def test_point(self): + p = Point(1, 1) + polys = shapely.constrained_delaunay_triangles(p) + assert len(polys.geoms) == 0 + + def test_empty_poly(self): + polys = shapely.constrained_delaunay_triangles(Polygon()) + assert len(polys.geoms) == 0 + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_voronoi_polygons_ordered(): + mp = MultiPoint([(3.0, 1.0), (3.0, 2.0), (1.0, 2.0), (1.0, 1.0)]) + result = shapely.voronoi_polygons(mp, ordered=False) + assert result.geoms[0].equals( + Polygon([(-1, -1), (-1, 1.5), (2, 1.5), (2, -1), (-1, -1)]) + ) + + result_ordered = shapely.voronoi_polygons(mp, ordered=True) + assert result_ordered.geoms[0].equals( + Polygon([(5, -1), (2, -1), (2, 1.5), (5, 1.5), (5, -1)]) + ) + + +@pytest.mark.skipif(shapely.geos_version >= (3, 12, 0), reason="GEOS >= 3.12") +def test_voronoi_polygons_ordered_raise(): + mp = MultiPoint([(3.0, 1.0), (3.0, 2.0), (1.0, 2.0), (1.0, 1.0)]) + with pytest.raises( + UnsupportedGEOSVersionError, match="Ordered Voronoi polygons require GEOS" + ): + shapely.voronoi_polygons(mp, ordered=True) + + +@pytest.mark.parametrize("geometry", all_types) +def test_maximum_inscribed_circle_all_types(geometry): + if shapely.get_type_id(geometry) not in [3, 6]: + # Maximum Inscribed Circle is only supported for (Multi)Polygon input + with pytest.raises( + GEOSException, + match=( + "Argument must be Polygonal or LinearRing|" # GEOS < 3.10.4 + "must be a Polygon or MultiPolygon|" + "Operation not supported by GeometryCollection" + ), + ): + shapely.maximum_inscribed_circle(geometry) + return + + if geometry.is_empty: + with pytest.raises( + GEOSException, match="Empty input(?: geometry)? is not supported" + ): + shapely.maximum_inscribed_circle(geometry) + return + + actual = shapely.maximum_inscribed_circle([geometry, geometry]) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + actual = shapely.maximum_inscribed_circle(None) + assert actual is None + + +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + "POLYGON ((0 5, 5 10, 10 5, 5 0, 0 5))", + "LINESTRING (5 5, 2.5 7.5)", + ), + ], +) +def test_maximum_inscribed_circle(geometry, expected): + geometry, expected = shapely.from_wkt(geometry), shapely.from_wkt(expected) + actual = shapely.maximum_inscribed_circle(geometry) + assert_geometries_equal(actual, expected) + + +def test_maximum_inscribed_circle_empty(): + geometry = shapely.from_wkt("POINT EMPTY") + with pytest.raises( + GEOSException, + match=( + "Argument must be Polygonal or LinearRing|" # GEOS < 3.10.4 + "must be a Polygon or MultiPolygon" + ), + ): + shapely.maximum_inscribed_circle(geometry) + + geometry = shapely.from_wkt("POLYGON EMPTY") + with pytest.raises( + GEOSException, match="Empty input(?: geometry)? is not supported" + ): + shapely.maximum_inscribed_circle(geometry) + + +def test_maximum_inscribed_circle_invalid_tolerance(): + geometry = shapely.from_wkt("POLYGON ((0 5, 5 10, 10 5, 5 0, 0 5))") + with pytest.raises(ValueError, match="'tolerance' should be positive"): + shapely.maximum_inscribed_circle(geometry, tolerance=-1) + + +@pytest.mark.parametrize("geometry", all_types) +def test_orient_polygons_all_types(geometry): + actual = shapely.orient_polygons([geometry, geometry]) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + actual = shapely.orient_polygons(None) + assert actual is None + + +def test_orient_polygons(): + # polygon with both shell and hole having clockwise orientation + polygon = Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ) + + result = shapely.orient_polygons(polygon) + assert result.exterior.is_ccw + assert not result.interiors[0].is_ccw + + result = shapely.orient_polygons(polygon, exterior_cw=True) + assert not result.exterior.is_ccw + assert result.interiors[0].is_ccw + + # in a MultiPolygon + mp = MultiPolygon([polygon, polygon]) + result = shapely.orient_polygons(mp) + assert len(result.geoms) == 2 + for geom in result.geoms: + assert geom.exterior.is_ccw + assert not geom.interiors[0].is_ccw + + result = shapely.orient_polygons([mp], exterior_cw=True)[0] + assert len(result.geoms) == 2 + for geom in result.geoms: + assert not geom.exterior.is_ccw + assert geom.interiors[0].is_ccw + + # in a GeometryCollection + gc = GeometryCollection([Point(1, 1), polygon, mp]) + result = shapely.orient_polygons(gc) + assert len(result.geoms) == 3 + assert result.geoms[0] == Point(1, 1) + assert result.geoms[1] == shapely.orient_polygons(polygon) + assert result.geoms[2] == shapely.orient_polygons(mp) + + +def test_orient_polygons_non_polygonal_input(): + arr = np.array([Point(0, 0), LineString([(0, 0), (1, 1)]), None]) + result = shapely.orient_polygons(arr) + assert_geometries_equal(result, arr) + + +def test_orient_polygons_array(): + # because we have a custom python implementation for older GEOS, need to + # ensure this has the same capabilities as numpy ufuncs to work with array-likes + polygon = Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ) + geometries = np.array([[polygon] * 3] * 2) + actual = shapely.orient_polygons(geometries) + assert isinstance(actual, np.ndarray) + assert actual.shape == (2, 3) + expected = shapely.orient_polygons(polygon) + assert (actual == expected).all() + + +def test_orient_polygons_array_like(): + # because we have a custom python implementation for older GEOS, need to + # ensure this has the same capabilities as numpy ufuncs to work with array-likes + polygon = Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ) + geometries = [polygon, Point(2, 2).buffer(1)] + actual = shapely.orient_polygons(ArrayLike(geometries)) + assert isinstance(actual, ArrayLike) + expected = shapely.orient_polygons(geometries) + assert_geometries_equal(np.asarray(actual), expected) + + +def test_buffer_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `quad_segs` for `buffer` is deprecated" + ): + shapely.buffer(point, 1.0, 8) + with pytest.deprecated_call( + match="positional arguments `quad_segs` and `cap_style` " + "for `buffer` are deprecated" + ): + shapely.buffer(point, 1.0, 8, "round") + with pytest.deprecated_call( + match="positional arguments `quad_segs`, `cap_style`, and `join_style` " + "for `buffer` are deprecated" + ): + shapely.buffer(point, 1.0, 8, "round", "round") + with pytest.deprecated_call(): + shapely.buffer(point, 1.0, 8, "round", "round", 5.0) + with pytest.deprecated_call(): + shapely.buffer(point, 1.0, 8, "round", "round", 5.0, False) + + +def test_offset_curve_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `quad_segs` for `offset_curve` is deprecated" + ): + shapely.offset_curve(line_string, 1.0, 8) + with pytest.deprecated_call( + match="positional arguments `quad_segs` and `join_style` " + "for `offset_curve` are deprecated" + ): + shapely.offset_curve(line_string, 1.0, 8, "round") + with pytest.deprecated_call( + match="positional arguments `quad_segs`, `join_style`, and `mitre_limit` " + "for `offset_curve` are deprecated" + ): + shapely.offset_curve(line_string, 1.0, 8, "round", 5.0) + + +def test_simplify_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `preserve_topology` for `simplify` is deprecated" + ): + shapely.simplify(line_string, 1.0, True) + + +def test_voronoi_polygons_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `extend_to` for `voronoi_polygons` is deprecated" + ): + shapely.voronoi_polygons(multi_point, 0.0, None) + with pytest.deprecated_call( + match="positional arguments `extend_to` and `only_edges` " + "for `voronoi_polygons` are deprecated" + ): + shapely.voronoi_polygons(multi_point, 0.0, None, False) + with pytest.deprecated_call( + match="positional arguments `extend_to`, `only_edges`, and `ordered` " + "for `voronoi_polygons` are deprecated" + ): + shapely.voronoi_polygons(multi_point, 0.0, None, False, False) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_coordinates.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_coordinates.py new file mode 100644 index 0000000000000000000000000000000000000000..a72d5a3cd733a54ed403e590fd3916e634af5e8e --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_coordinates.py @@ -0,0 +1,422 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_equal + +import shapely +from shapely import count_coordinates, get_coordinates, set_coordinates, transform +from shapely.tests.common import ( + empty, + empty_line_string_z, + empty_point, + empty_point_m, + empty_point_z, + empty_point_zm, + geometry_collection, + geometry_collection_z, + geometry_collection_zm, + line_string, + line_string_m, + line_string_z, + line_string_zm, + linear_ring, + multi_line_string, + multi_point, + multi_polygon, + point, + point_m, + point_z, + point_zm, + polygon, + polygon_with_hole, + polygon_z, +) + +nested_2 = shapely.geometrycollections([geometry_collection, point]) +nested_3 = shapely.geometrycollections([nested_2, point]) + + +@pytest.mark.parametrize( + "geoms,count", + [ + ([], 0), + ([empty], 0), + ([point, empty], 1), + ([empty, point, empty], 1), + ([point, None], 1), + ([None, point, None], 1), + ([point, point], 2), + ([point, point_z], 2), + ([line_string, linear_ring], 8), + ([polygon], 5), + ([polygon_with_hole], 10), + ([multi_point, multi_line_string], 4), + ([multi_polygon], 10), + ([geometry_collection], 3), + ([nested_2], 4), + ([nested_3], 5), + ], +) +def test_count_coords(geoms, count): + actual = count_coordinates(np.array(geoms, np.object_)) + assert actual == count + + +@pytest.mark.parametrize("include_m", [True, False]) +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms,x,y", + [ + ([], [], []), + ([empty], [], []), + ([point, empty], [2], [3]), + ([empty, point, empty], [2], [3]), + ([point, None], [2], [3]), + ([None, point, None], [2], [3]), + ([point, point], [2, 2], [3, 3]), + ( + [line_string, linear_ring], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 1, 0], + ), + ([polygon], [0, 2, 2, 0, 0], [0, 0, 2, 2, 0]), + ( + [polygon_with_hole], + [0, 0, 10, 10, 0, 2, 2, 4, 4, 2], + [0, 10, 10, 0, 0, 2, 4, 4, 2, 2], + ), + ([multi_point, multi_line_string], [0, 1, 0, 1], [0, 2, 0, 2]), + ( + [multi_polygon], + [0, 1, 1, 0, 0, 2.1, 2.2, 2.2, 2.1, 2.1], + [0, 0, 1, 1, 0, 2.1, 2.1, 2.2, 2.2, 2.1], + ), + ([geometry_collection], [51, 52, 49], [-1, -1, 2]), + ([nested_2], [51, 52, 49, 2], [-1, -1, 2, 3]), + ([nested_3], [51, 52, 49, 2, 2], [-1, -1, 2, 3, 3]), + ], +) +def test_get_coords(geoms, x, y, include_z, include_m): + actual = get_coordinates(geoms, include_z=include_z, include_m=include_m) + expected = [x, y] + if include_z: + expected.append([np.nan] * len(x)) + if include_m: + expected.append([np.nan] * len(x)) + assert_equal(actual, np.array(expected, np.float64).T) + + +@pytest.mark.parametrize( + "geoms,index", + [ + ([], []), + ([empty], []), + ([point, empty], [0]), + ([empty, point, empty], [1]), + ([point, None], [0]), + ([None, point, None], [1]), + ([point, point], [0, 1]), + ([point, line_string], [0, 1, 1, 1]), + ([line_string, point], [0, 0, 0, 1]), + ([line_string, linear_ring], [0, 0, 0, 1, 1, 1, 1, 1]), + ], +) +def test_get_coords_index(geoms, index): + _, actual = get_coordinates(np.array(geoms, np.object_), return_index=True) + expected = np.array(index, dtype=np.intp) + assert_equal(actual, expected) + + +@pytest.mark.parametrize("order", ["C", "F"]) +def test_get_coords_index_multidim(order): + geometry = np.array([[point, line_string], [empty, empty]], order=order) + expected = [0, 1, 1, 1] # would be [0, 2, 2, 2] with fortran order + _, actual = get_coordinates(geometry, return_index=True) + assert_equal(actual, expected) + + +@pytest.mark.parametrize("include_m", [True, False]) +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms,x,y,z", + [ + ([point, point_z], [2, 2], [3, 3], [np.nan, 4]), + ([line_string_z], [0, 1, 1], [0, 0, 1], [4, 4, 4]), + ([polygon_z], [0, 2, 2, 0, 0], [0, 0, 2, 2, 0], [4, 4, 4, 4, 4]), + ([geometry_collection_z], [2, 0, 1, 1], [3, 0, 0, 1], [4, 4, 4, 4]), + ([point, empty_point], [2], [3], [np.nan]), + ], +) +def test_get_coords_z(geoms, x, y, z, include_z, include_m): + actual = get_coordinates(geoms, include_z=include_z, include_m=include_m) + expected = [x, y] + if include_z: + expected.append(z) + if include_m: + expected.append([np.nan] * len(x)) + assert_equal(actual, np.array(expected, np.float64).T) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize("include_m", [True, False]) +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms,x,y,z,m", + [ + ( + [point, point_z, point_m, point_zm], + [2, 2, 2, 2], + [3, 3, 3, 3], + [np.nan, 4, np.nan, 4], + [np.nan, np.nan, 5, 5], + ), + ( + [line_string, line_string_z, line_string_m, line_string_zm], + [0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], + [np.nan, np.nan, np.nan, 4, 4, 4] * 2, + [np.nan] * 6 + [1, 2, 3, 1, 2, 3], + ), + ( + [geometry_collection_zm], + [2, 0, 1, 1], + [3, 0, 0, 1], + [4, 4, 4, 4], + [5, 1, 2, 3], + ), + ( + [point, empty_point, empty_point_z, empty_point_m, empty_point_zm], + [2], + [3], + [np.nan], + [np.nan], + ), + ], +) +def test_get_coords_zm(geoms, x, y, z, m, include_z, include_m): + actual = get_coordinates(geoms, include_z=include_z, include_m=include_m) + expected = [x, y] + if include_z: + expected.append(z) + if include_m: + expected.append(m) + assert_equal(actual, np.array(expected, np.float64).T) + + +def test_get_coords_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `include_z` for `get_coordinates` is deprecated" + ): + get_coordinates(point, False) + with pytest.deprecated_call( + match="positional arguments `include_z` and `return_index` " + "for `get_coordinates` are deprecated" + ): + get_coordinates(point, False, False) + + +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms,count,has_ring", + [ + ([], 0, False), + ([empty], 0, False), + ([empty_point], 0, False), + ([point, empty], 1, False), + ([empty, point, empty], 1, False), + ([point, None], 1, False), + ([None, point, None], 1, False), + ([point, point], 2, False), + ([point, point_z], 2, False), + ([line_string, linear_ring], 8, True), + ([line_string_z], 3, True), + ([polygon], 5, True), + ([polygon_z], 5, True), + ([polygon_with_hole], 10, True), + ([multi_point, multi_line_string], 4, False), + ([multi_polygon], 10, True), + ([geometry_collection], 3, False), + ([geometry_collection_z], 3, False), + ([nested_2], 4, False), + ([nested_3], 5, False), + ], +) +def test_set_coords(geoms, count, has_ring, include_z): + arr_geoms = np.array(geoms, np.object_) + n = 3 if include_z else 2 + coords = get_coordinates(arr_geoms, include_z=include_z) + np.random.random((1, n)) + new_geoms = set_coordinates(arr_geoms, coords) + assert_equal(coords, get_coordinates(new_geoms, include_z=include_z)) + + +def test_set_coords_nan(): + geoms = np.array([point]) + coords = np.array([[np.nan, np.inf]]) + new_geoms = set_coordinates(geoms, coords) + assert_equal(coords, get_coordinates(new_geoms)) + + +def test_set_coords_breaks_ring(): + with pytest.raises(shapely.GEOSException): + set_coordinates(linear_ring, np.random.random((5, 2))) + + +def test_set_coords_0dim(): + # a geometry input returns a geometry + actual = set_coordinates(point, [[1, 1]]) + assert isinstance(actual, shapely.Geometry) + # a 0-dim array input returns a 0-dim array + actual = set_coordinates(np.asarray(point), [[1, 1]]) + assert isinstance(actual, np.ndarray) + assert actual.ndim == 0 + + +@pytest.mark.parametrize("include_z", [True, False]) +def test_set_coords_mixed_dimension(include_z): + geoms = np.array([point, point_z], dtype=object) + coords = get_coordinates(geoms, include_z=include_z) + new_geoms = set_coordinates(geoms, coords * 2) + if include_z: + # preserve original dimensionality + assert not shapely.has_z(new_geoms[0]) + assert shapely.has_z(new_geoms[1]) + else: + # all 2D + assert not shapely.has_z(new_geoms).any() + + +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms", + [[], [empty], [None, point, None], [nested_3], [point, point_z], [line_string_z]], +) +@pytest.mark.parametrize("interleaved", [True, False]) +def test_transform(geoms, include_z, interleaved): + geoms = np.array(geoms, np.object_) + coordinates_before = get_coordinates(geoms, include_z=include_z) + if interleaved: + transformation = lambda coords: coords + 1 + elif not include_z: + transformation = lambda x, y: (x + 1, y + 1) + else: + transformation = lambda x, y, z: (x + 1, y + 1, z + 1) + new_geoms = transform( + geoms, transformation, include_z=include_z, interleaved=interleaved + ) + assert new_geoms is not geoms + coordinates_after = get_coordinates(new_geoms, include_z=include_z) + assert_allclose(coordinates_before + 1, coordinates_after, equal_nan=True) + + +def test_transform_0dim(): + # a geometry input returns a geometry + actual = transform(point, lambda x: x + 1) + assert isinstance(actual, shapely.Geometry) + # a 0-dim array input returns a 0-dim array + actual = transform(np.asarray(point), lambda x: x + 1) + assert isinstance(actual, np.ndarray) + assert actual.ndim == 0 + + +def test_transform_no_geoms(): + # a geometry input returns a geometry + actual = transform([], lambda x: x + 1) + assert actual.shape == (0,) + + +def test_transform_check_shape(): + def remove_coord(arr): + return arr[:-1] + + with pytest.raises(ValueError): + transform(linear_ring, remove_coord) + + +def test_transform_correct_coordinate_dimension(): + # ensure that new geometry is 2D with include_z=False + geom = line_string_z + assert shapely.get_coordinate_dimension(geom) == 3 + new_geom = transform(geom, lambda x: x + 1, include_z=False) + assert shapely.get_coordinate_dimension(new_geom) == 2 + + +@pytest.mark.parametrize( + "geom", + [ + empty_point_z, + empty_line_string_z, + ], +) +def test_transform_empty_preserve_z(geom): + assert shapely.get_coordinate_dimension(geom) == 3 + new_geom = transform(geom, lambda x: x + 1, include_z=True) + assert shapely.get_coordinate_dimension(new_geom) == 3 + + +@pytest.mark.parametrize( + "geom", + [ + empty_point_z, + empty_line_string_z, + ], +) +def test_transform_remove_z(geom): + assert shapely.get_coordinate_dimension(geom) == 3 + new_geom = transform(geom, lambda x: x + 1, include_z=False) + assert shapely.get_coordinate_dimension(new_geom) == 2 + + +@pytest.mark.parametrize( + "geom,expected", + [ + (line_string, 2), + (line_string_z, 3), + ], +) +def test_transform_auto_coordinate_dimension(geom, expected): + new_geom = transform(geom, lambda x: x + 1, include_z=None) + assert (shapely.get_coordinate_dimension(new_geom) == expected).all() + + +def test_transform_auto_coordinate_dimension_mixed(): + new_geom = transform([line_string, line_string_z], lambda x: x + 1, include_z=None) + assert_equal(shapely.get_coordinate_dimension(new_geom), [2, 3]) + assert_equal( + shapely.get_coordinates(line_string, include_z=False) + 1, + shapely.get_coordinates(new_geom[0], include_z=False), + ) + assert_equal( + shapely.get_coordinates(line_string_z, include_z=True) + 1, + shapely.get_coordinates(new_geom[1], include_z=True), + ) + + +def transform_non_interleaved(x, y, z=None): + if z is None: + return [x + 1, y + 2] + else: + return [x + 1, y + 2, z + 3] + + +def test_transform_auto_coordinate_dimension_mixed_interleaved(): + new_geom = transform( + [line_string, line_string_z], + transform_non_interleaved, + include_z=None, + interleaved=False, + ) + assert_equal(shapely.get_coordinate_dimension(new_geom), [2, 3]) + assert_equal( + shapely.get_coordinates(line_string, include_z=False) + [1, 2], + shapely.get_coordinates(new_geom[0], include_z=False), + ) + assert_equal( + shapely.get_coordinates(line_string_z, include_z=True) + [1, 2, 3], + shapely.get_coordinates(new_geom[1], include_z=True), + ) + + +def test_transform_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `include_z` for `transform` is deprecated" + ): + transform(line_string_z, lambda x: x + 1, False) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_coverage.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..db6f370ede58ce0505ee89de297de62a6dc5482d --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_coverage.py @@ -0,0 +1,249 @@ +import numpy as np +import pytest + +import shapely +from shapely import ( + Geometry, + LineString, + MultiPolygon, + Polygon, +) +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + all_types, + all_types_z, + empty_line_string, +) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +@pytest.mark.parametrize("geometry", all_types + all_types_z) +def test_coverage_is_valid(geometry): + actual = shapely.coverage_is_valid([geometry]) + assert actual.ndim == 0 + assert actual.dtype == np.bool_ + assert actual.item() is True + + actual = shapely.coverage_invalid_edges([geometry]) + expected = np.array([empty_line_string], dtype=object) + assert_geometries_equal(actual, expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +def test_coverage_is_valid_non_polygonal(): + # non-polygonal geometries are ignored to validate the coverage + # (e.g. even if you have crossing linestrings) + geoms = [ + LineString([(0, 0), (1, 1)]), + LineString([(1, 0), (0, 1)]), + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + ] + assert shapely.coverage_is_valid(geoms) + assert (shapely.coverage_invalid_edges(geoms) == empty_line_string).all() + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +def test_coverage_is_valid_polygonal(): + # adjacent triangles + poly1 = Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]) + poly2 = Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]) + assert shapely.coverage_is_valid([poly1, poly2]) + assert shapely.is_empty(shapely.coverage_invalid_edges([poly1, poly2])).all() + + # shared egde but without identical vertices + poly2b = Polygon([(0, 0), (0.5, 0.5), (1, 1), (0, 1), (0, 0)]) + assert not shapely.coverage_is_valid([poly1, poly2b]) + result = shapely.coverage_invalid_edges([poly1, poly2b]) + expected = [LineString([(0, 0), (1, 1)]), LineString([(0, 0), (0.5, 0.5), (1, 1)])] + assert_geometries_equal(result, expected) + + # overlap + poly3 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + assert not shapely.coverage_is_valid([poly1, poly3]) + result = shapely.coverage_invalid_edges([poly1, poly3]) + assert not shapely.is_empty(result).any() + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +def test_coverage_is_valid_gap_width(): + # shared edge of boxes with multiple vertices + poly1 = shapely.from_wkt("POLYGON ((0 10, 10 10, 10 7, 10 3, 10 0, 0 0, 0 10))") + poly2 = shapely.from_wkt("POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 10 7, 10 10))") + + # extra vertex in middle of shared edge + poly2_extra = shapely.from_wkt( + "POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 10 5, 10 7, 10 10))" + ) + # extra vertex shifted -> gap of max 1 wide + poly2_shift = shapely.from_wkt( + "POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 11 5, 10 7, 10 10))" + ) + + # valid coverage -> gap_width value does not matter + assert shapely.coverage_is_valid([poly1, poly2], gap_width=0.0) + assert shapely.coverage_is_valid([poly1, poly2], gap_width=2.0) + + result = shapely.coverage_invalid_edges([poly1, poly2], gap_width=0.0) + assert_geometries_equal(result, [empty_line_string] * 2) + result = shapely.coverage_invalid_edges([poly1, poly2], gap_width=2.0) + assert_geometries_equal(result, [empty_line_string] * 2) + + # invalid coverage -> gap_width value does not matter + assert not shapely.coverage_is_valid([poly1, poly2_extra], gap_width=0.0) + assert not shapely.coverage_is_valid([poly1, poly2_extra], gap_width=2.0) + + expected = shapely.from_wkt( + ["LINESTRING (10 7, 10 3)", "LINESTRING (10 3, 10 5, 10 7)"] + ) + result = shapely.coverage_invalid_edges([poly1, poly2_extra], gap_width=0.0) + assert_geometries_equal(result, expected) + result = shapely.coverage_invalid_edges([poly1, poly2_extra], gap_width=2.0) + assert_geometries_equal(result, expected) + + # coverage with gap of 1 unit wide + assert shapely.coverage_is_valid([poly1, poly2_shift], gap_width=0.0) + assert shapely.coverage_is_valid([poly1, poly2_shift], gap_width=0.5) + assert not shapely.coverage_is_valid([poly1, poly2_shift], gap_width=1.0) + assert not shapely.coverage_is_valid([poly1, poly2_shift], gap_width=1.5) + # TODO why this behaviour? + assert shapely.coverage_is_valid([poly1, poly2_shift], gap_width=2.0) + + assert_geometries_equal( + shapely.coverage_invalid_edges([poly1, poly2_shift], gap_width=0.0), + [empty_line_string] * 2, + ) + assert_geometries_equal( + shapely.coverage_invalid_edges([poly1, poly2_shift], gap_width=1.0), + shapely.from_wkt(["LINESTRING (10 7, 10 3)", "LINESTRING (10 3, 11 5, 10 7)"]), + ) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +def test_coverage_invalid_edges_gufunc(): + poly1 = shapely.from_wkt("POLYGON ((0 10, 10 10, 10 7, 10 3, 10 0, 0 0, 0 10))") + poly2 = shapely.from_wkt("POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 10 7, 10 10))") + poly2_extra = shapely.from_wkt( + "POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 10 5, 10 7, 10 10))" + ) + poly3 = shapely.from_wkt("POLYGON ((20 10, 30 10, 30 7, 30 3, 30 0, 20 0, 20 10))") + + arr = np.array([[poly1, poly2, poly3], [poly1, poly2_extra, poly3]]) + result = shapely.lib.coverage_invalid_edges(arr, 0.0) + expected = shapely.from_wkt( + [ + ["LINESTRING EMPTY"] * 3, + [ + "LINESTRING (10 7, 10 3)", + "LINESTRING (10 3, 10 5, 10 7)", + "LINESTRING EMPTY", + ], + ] + ) + assert_geometries_equal(result, expected) + + arr2 = np.array(arr, order="F") + result = shapely.lib.coverage_invalid_edges(arr2, 0.0) + assert_geometries_equal(result, expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize("geometry", all_types) +def test_coverage_simplify_scalars(geometry): + if geometry.geom_type in ("Polygon", "MultiPolygon"): + actual = shapely.coverage_simplify(geometry, 0.0) + assert isinstance(actual, Geometry) + assert shapely.get_type_id(actual) == shapely.get_type_id(geometry) + assert actual.equals(geometry) + else: + with pytest.raises(TypeError, match="incorrect geometry type"): + shapely.coverage_simplify(geometry, 0.0) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize("geometry", all_types) +def test_coverage_simplify_geom_types(geometry): + if geometry.geom_type in ("Polygon", "MultiPolygon"): + actual = shapely.coverage_simplify([geometry, geometry], 0.0) + assert isinstance(actual, np.ndarray) + assert actual.shape == (2,) + assert (shapely.get_type_id(actual) == shapely.get_type_id(geometry)).all() + else: + with pytest.raises(TypeError, match="incorrect geometry type"): + shapely.coverage_simplify([geometry, geometry], 0.0) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_coverage_simplify_multipolygon(): + mp = MultiPolygon( + [ + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + Polygon([(2, 2), (2, 3), (3, 3), (3, 2), (2, 2)]), + ] + ) + actual = shapely.coverage_simplify(mp, 1) + assert actual.equals( + shapely.from_wkt( + "MULTIPOLYGON (((0 1, 1 1, 1 0, 0 1)), ((2 3, 3 3, 3 2, 2 3)))" + ) + ) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_coverage_simplify_array(): + polygons = np.array( + [ + shapely.Polygon([(0, 0), (20, 0), (20, 10), (10, 5), (0, 10), (0, 0)]), + shapely.Polygon([(0, 10), (10, 5), (20, 10), (20, 20), (0, 20), (0, 10)]), + ] + ) + low_tolerance = shapely.coverage_simplify(polygons, 1) + mid_tolerance = shapely.coverage_simplify(polygons, 8) + high_tolerance = shapely.coverage_simplify(polygons, 10) + + assert shapely.equals(low_tolerance, shapely.normalize(polygons)).all() + assert shapely.equals( + mid_tolerance, + shapely.from_wkt( + [ + "POLYGON ((20 10, 0 10, 0 0, 20 0, 20 10))", + "POLYGON ((20 10, 0 10, 0 20, 20 20, 20 10))", + ] + ), + ).all() + assert shapely.equals( + high_tolerance, + shapely.from_wkt( + [ + "POLYGON ((20 10, 0 10, 20 0, 20 10))", + "POLYGON ((20 10, 0 10, 0 20, 20 10))", + ] + ), + ).all() + + no_boundary = shapely.coverage_simplify(polygons, 10, simplify_boundary=False) + assert shapely.equals( + no_boundary, + shapely.from_wkt( + [ + "POLYGON ((20 10, 0 10, 0 0, 20 0, 20 10))", + "POLYGON ((20 10, 0 10, 0 20, 20 20, 20 10))", + ] + ), + ).all() + + +@pytest.mark.skipif(shapely.geos_version >= (3, 12, 0), reason="requires >= 3.12") +def test_coverage_unsupported_geos(): + geoms = [ + Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), + Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]), + ] + with pytest.raises(UnsupportedGEOSVersionError): + shapely.coverage_is_valid(geoms) + + with pytest.raises(UnsupportedGEOSVersionError): + shapely.coverage_invalid_edges(geoms) + + with pytest.raises(UnsupportedGEOSVersionError): + shapely.coverage_simplify(geoms, 1.0) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_creation.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_creation.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7d08f445f59cdd31b157c01e01d187f5c8ae83 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_creation.py @@ -0,0 +1,742 @@ +"""See test_creation_indices.py for tests with 'indices' parameter.""" + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import shapely + +# Note: Point is not imported because it is overridden for testing +from shapely import ( + GeometryCollection, + GeometryType, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Polygon, +) +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + empty_polygon, + geometry_collection, + ignore_invalid, + line_string, + linear_ring, + multi_line_string, + multi_point, + multi_polygon, + point, + polygon, +) + + +def box_tpl(x1, y1, x2, y2): + return (x2, y1), (x2, y2), (x1, y2), (x1, y1), (x2, y1) + + +def test_points_from_coords(): + actual = shapely.points([[0, 0], [2, 2]]) + assert_geometries_equal(actual, [shapely.Point(0, 0), shapely.Point(2, 2)]) + + +def test_points_from_xy(): + actual = shapely.points(2, [0, 1]) + assert_geometries_equal(actual, [shapely.Point(2, 0), shapely.Point(2, 1)]) + + +def test_points_from_xyz(): + actual = shapely.points(1, 1, [0, 1]) + assert_geometries_equal(actual, [shapely.Point(1, 1, 0), shapely.Point(1, 1, 1)]) + + +def test_points_invalid_ndim(): + with pytest.raises(ValueError, match="dimension should be 2 or 3, got 4"): + shapely.points([0, 1, 2, 3]) + + with pytest.raises(ValueError, match="dimension should be 2 or 3, got 1"): + shapely.points([0]) + + +@pytest.mark.skipif( + shapely.geos_version[:2] not in ((3, 10), (3, 11), (3, 12)), + reason="GEOS not in 3.10, 3.11, 3.12", +) +def test_points_nan_all_nan_becomes_empty(): + actual = shapely.points(np.nan, np.nan) + assert actual.wkt == "POINT EMPTY" + + +@pytest.mark.skipif( + shapely.geos_version[:2] not in ((3, 10), (3, 11)), + reason="GEOS not in 3.10, 3.11", +) +def test_points_nan_3D_all_nan_becomes_empty_2D(): + actual = shapely.points(np.nan, np.nan, np.nan) + assert actual.wkt == "POINT EMPTY" + + +@pytest.mark.skipif(shapely.geos_version[:2] != (3, 12), reason="GEOS != 3.12") +def test_points_nan_3D_all_nan_becomes_empty(): + actual = shapely.points(np.nan, np.nan, np.nan) + assert actual.wkt == "POINT Z EMPTY" + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize( + "coords,expected_wkt", + [ + pytest.param( + [np.nan, np.nan], + "POINT (NaN NaN)", + marks=pytest.mark.skipif( + shapely.geos_version < (3, 13, 0), reason="GEOS < 3.13" + ), + ), + pytest.param( + [np.nan, np.nan, np.nan], + "POINT Z (NaN NaN NaN)", + marks=pytest.mark.skipif( + shapely.geos_version < (3, 13, 0), reason="GEOS < 3.13" + ), + ), + ([1, np.nan], "POINT (1 NaN)"), + ([np.nan, 1], "POINT (NaN 1)"), + ([np.nan, 1, np.nan], "POINT Z (NaN 1 NaN)"), + ([np.nan, np.nan, 1], "POINT Z (NaN NaN 1)"), + ], +) +def test_points_handle_nan_allow(coords, expected_wkt): + actual = shapely.points(coords, handle_nan="allow") + assert actual.wkt == expected_wkt + + +@pytest.mark.parametrize( + "coords,handle_nan,expected_wkt", + [ + ([0, np.nan], "skip", "POINT EMPTY"), + ([np.nan, 0], "skip", "POINT EMPTY"), + ([0, np.nan, 1], "skip", "POINT Z EMPTY"), + ([0, 1, np.nan], "skip", "POINT Z EMPTY"), + ([0, 1], "error", "POINT (0 1)"), + ([0, 1, 2], "error", "POINT Z (0 1 2)"), + ([0, np.inf], "skip", "POINT EMPTY"), + ], +) +def test_points_handle_nan(coords, handle_nan, expected_wkt): + actual = shapely.points(coords, handle_nan=handle_nan) + assert actual.wkt in expected_wkt + + +@pytest.mark.parametrize( + "coords", + [ + [0, np.nan], + [np.nan, 0], + [0, 0, np.nan], + [0, np.inf], + [0, -np.inf], + ], +) +def test_points_handle_nan_error(coords): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.points(coords, handle_nan="error") + + +def test_linestrings_from_coords(): + actual = shapely.linestrings([[[0, 0], [1, 1]], [[0, 0], [2, 2]]]) + assert_geometries_equal( + actual, + [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (2, 2)]), + ], + ) + + +def test_linestrings_from_xy(): + actual = shapely.linestrings([0, 1], [2, 3]) + assert_geometries_equal(actual, LineString([(0, 2), (1, 3)])) + + +def test_linestrings_from_xy_broadcast(): + x = [0, 1] # the same X coordinates for both linestrings + y = [2, 3], [4, 5] # each linestring has a different set of Y coordinates + actual = shapely.linestrings(x, y) + assert_geometries_equal( + actual, + [ + LineString([(0, 2), (1, 3)]), + LineString([(0, 4), (1, 5)]), + ], + ) + + +def test_linestrings_from_xyz(): + actual = shapely.linestrings([0, 1], [2, 3], 0) + assert_geometries_equal(actual, LineString([(0, 2, 0), (1, 3, 0)])) + + +@pytest.mark.parametrize("dim", [2, 3]) +def test_linestrings_buffer(dim): + coords = np.random.randn(10, 3, dim) + coords1 = np.asarray(coords, order="C") + result1 = shapely.linestrings(coords1) + + coords2 = np.asarray(coords1, order="F") + result2 = shapely.linestrings(coords2) + assert_geometries_equal(result1, result2) + + # creating (.., 8, 8*3) strided array so it uses copyFromArrays + coords3 = np.asarray(np.swapaxes(np.swapaxes(coords, 0, 2), 1, 0), order="F") + coords3 = np.swapaxes(np.swapaxes(coords3, 0, 2), 1, 2) + result3 = shapely.linestrings(coords3) + assert_geometries_equal(result1, result3) + + +def test_linestrings_empty(): + actual = shapely.linestrings(np.empty((0, 2))) + assert actual.is_empty + + +def test_linestrings_invalid_shape_scalar(): + with pytest.raises(ValueError): + shapely.linestrings((1, 1)) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 1, 2), # 2 linestrings of 1 2D point + (1, 1, 2), # 1 linestring of 1 2D point + (1, 2), # 1 linestring of 1 2D point (scalar) + ], +) +def test_linestrings_invalid_shape(shape): + with pytest.raises(shapely.GEOSException): + shapely.linestrings(np.ones(shape)) + + +def test_linestrings_invalid_ndim(): + msg = r"The ordinate \(last\) dimension should be 2 or 3, got {}" + + coords = np.ones((10, 2, 4), order="C") + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linestrings(coords) + + coords = np.ones((10, 2, 4), order="F") + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linestrings(coords) + + coords = np.swapaxes(np.swapaxes(np.ones((10, 2, 4)), 0, 2), 1, 0) + coords = np.swapaxes(np.swapaxes(np.asarray(coords, order="F"), 0, 2), 1, 2) + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linestrings(coords) + + # too few ordinates + coords = np.ones((10, 2, 1)) + with pytest.raises(ValueError, match=msg.format(1)): + shapely.linestrings(coords) + + +@pytest.mark.parametrize( + "coords", + [ + [[0, 1], [2, float("nan")]], + [[0, 1, float("nan")], [2, 2, float("nan")]], + [[0, 1, 2], [2, 2, float("nan")]], + [[0, 1, float("nan")], [2, 2, 3]], + [[float("nan"), float("nan")], [float("nan"), float("nan")]], + ], +) +def test_linestrings_handle_nan_allow(coords): + with ignore_invalid(): + actual = shapely.linestrings(coords, handle_nan="allow") + actual = shapely.get_coordinates(actual, include_z=len(coords[0]) == 3) + + assert_array_equal(actual, coords) + + +@pytest.mark.parametrize( + "coords", + [ + [[2, float("nan")], [0, 1], [2, 3]], + [[0, 1], [2, float("nan")], [2, 3]], + [[0, 1], [2, 3], [2, float("nan")]], + ], +) +def test_linestrings_handle_nan_skip(coords): + actual = shapely.linestrings(coords, handle_nan="skip") + assert_geometries_equal(actual, LineString([(0, 1), (2, 3)])) + + +def test_linestrings_handle_nan_skip_invalid(): + with pytest.raises(shapely.GEOSException): + shapely.linestrings([[0, 1], [2, float("nan")]], handle_nan="skip") + + +def test_linestrings_handle_nan_skip_only_nan(): + # all-nan becomes an empty linestring + actual = shapely.linestrings(np.full((3, 2), fill_value=np.nan), handle_nan="skip") + assert actual.is_empty + + +def test_linestrings_handle_nan_error(): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.linestrings([[0, 1], [2, float("nan")], [2, 3]], handle_nan="error") + + +def test_linearrings(): + actual = shapely.linearrings(box_tpl(0, 0, 1, 1)) + assert_geometries_equal( + actual, LinearRing([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)]) + ) + + +def test_linearrings_empty(): + actual = shapely.linearrings(np.empty((0, 2))) + assert actual.is_empty + + +def test_linearrings_from_xy(): + actual = shapely.linearrings([0, 1, 2, 0], [3, 4, 5, 3]) + assert_geometries_equal(actual, LinearRing([(0, 3), (1, 4), (2, 5), (0, 3)])) + + +def test_linearrings_unclosed(): + actual = shapely.linearrings(box_tpl(0, 0, 1, 1)[:-1]) + assert_geometries_equal( + actual, LinearRing([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)]) + ) + + +def test_linearrings_unclosed_all_coords_equal(): + actual = shapely.linearrings([(0, 0), (0, 0), (0, 0)]) + assert_geometries_equal(actual, LinearRing([(0, 0), (0, 0), (0, 0), (0, 0)])) + + +def test_linearrings_invalid_shape_scalar(): + with pytest.raises(ValueError): + shapely.linearrings((1, 1)) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 1, 2), # 2 linearrings of 1 2D point + (1, 1, 2), # 1 linearring of 1 2D point + (1, 2), # 1 linearring of 1 2D point (scalar) + (2, 2, 2), # 2 linearrings of 2 2D points + (1, 2, 2), # 1 linearring of 2 2D points + (2, 2), # 1 linearring of 2 2D points (scalar) + ], +) +def test_linearrings_invalid_shape(shape): + coords = np.ones(shape) + with pytest.raises(ValueError): + shapely.linearrings(coords) + + # make sure the first coordinate != second coordinate + coords[..., 1] += 1 + with pytest.raises(ValueError): + shapely.linearrings(coords) + + +def test_linearrings_invalid_ndim(): + msg = r"The ordinate \(last\) dimension should be 2 or 3, got {}" + + coords1 = np.random.randn(10, 3, 4) + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linearrings(coords1) + + coords2 = np.hstack((coords1, coords1[:, [0], :])) + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linearrings(coords2) + + # too few ordinates + coords3 = np.random.randn(10, 3, 1) + with pytest.raises(ValueError, match=msg.format(1)): + shapely.linearrings(coords3) + + +def test_linearrings_all_nan(): + coords = np.full((4, 2), np.nan) + with pytest.raises(shapely.GEOSException): + shapely.linearrings(coords) + + +@pytest.mark.parametrize("dim", [2, 3]) +@pytest.mark.parametrize("order", ["C", "F"]) +def test_linearrings_buffer(dim, order): + coords1 = np.random.randn(10, 4, dim) + coords1 = np.asarray(coords1, order=order) + result1 = shapely.linearrings(coords1) + + # with manual closure -> can directly copy from buffer if C order + coords2 = np.hstack((coords1, coords1[:, [0], :])) + coords2 = np.asarray(coords2, order=order) + result2 = shapely.linearrings(coords2) + assert_geometries_equal(result1, result2) + + # create scalar -> can also directly copy from buffer if F order + coords3 = np.asarray(coords2[0], order=order) + result3 = shapely.linearrings(coords3) + assert_geometries_equal(result3, result1[0]) + + +@pytest.mark.parametrize( + "coords", + [ + [[0, 2], [1, float("nan")], [1, 3], [0, 2]], + [[0, 2], [float("nan"), 0], [1, 3], [0, 2]], + [[0, 2, 5], [float("nan"), 2, 5], [1, 3, 5], [0, 2, 5]], + [[0, 2, 5], [1, 2, float("nan")], [1, 3, 5], [0, 2, 5]], + ], +) +def test_linearrings_handle_nan_allow(coords): + with ignore_invalid(): + actual = shapely.linearrings(coords, handle_nan="allow") + actual = shapely.get_coordinates(actual, include_z=len(coords[0]) == 3) + + assert_array_equal(actual, coords) + + +@pytest.mark.parametrize( + "x,y", + [ + ([0, 1, float("nan"), 2, 0], [3, 4, 5, 5, 3]), + ([0, 1, 1, 2, 0], [3, 4, float("nan"), 5, 3]), + ([0, 1, 2, 0, float("nan")], [3, 4, 5, 3, 3]), + ([float("nan"), 0, 1, 2, 0], [3, 3, 4, 5, 3]), + ], +) +def test_linearrings_handle_nan_skip(x, y): + actual = shapely.linearrings(x, y, handle_nan="skip") + assert_geometries_equal(actual, LinearRing([(0, 3), (1, 4), (2, 5), (0, 3)])) + + +def test_linearrings_handle_nan_skip_invalid(): + with pytest.raises(ValueError): + shapely.linearrings([0, float("nan"), 0], [3, 4, 3], handle_nan="skip") + + +def test_linearrings_handle_nan_skip_only_nan(): + actual = shapely.linearrings(np.full((5, 2), fill_value=np.nan), handle_nan="skip") + assert actual.is_empty + + +def test_linearrings_handle_nan_error(): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.linearrings( + [0, 1, float("nan"), 2, 0], [3, 4, 5, 5, 3], handle_nan="error" + ) + + +def test_polygon_from_linearring(): + actual = shapely.polygons(shapely.linearrings(box_tpl(0, 0, 1, 1))) + assert_geometries_equal(actual, Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)])) + + +def test_polygons_none(): + assert_geometries_equal(shapely.polygons(None), empty_polygon) + assert_geometries_equal(shapely.polygons(None, holes=[linear_ring]), empty_polygon) + + +def test_polygons(): + actual = shapely.polygons(box_tpl(0, 0, 1, 1)) + assert_geometries_equal(actual, Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)])) + + +def test_polygon_no_hole_list_raises(): + with pytest.raises(ValueError): + shapely.polygons(box_tpl(0, 0, 10, 10), box_tpl(1, 1, 2, 2)) + + +def test_polygon_no_hole_wrong_type(): + with pytest.raises((TypeError, shapely.GEOSException)): + shapely.polygons(point) + + +def test_polygon_with_hole_wrong_type(): + with pytest.raises((TypeError, shapely.GEOSException)): + shapely.polygons(point, [linear_ring]) + + +def test_polygon_wrong_hole_type(): + with pytest.raises((TypeError, shapely.GEOSException)): + shapely.polygons(linear_ring, [point]) + + +def test_polygon_with_1_hole(): + actual = shapely.polygons(box_tpl(0, 0, 10, 10), [box_tpl(1, 1, 2, 2)]) + assert shapely.area(actual) == 99.0 + + +def test_polygon_with_2_holes(): + actual = shapely.polygons( + box_tpl(0, 0, 10, 10), [box_tpl(1, 1, 2, 2), box_tpl(3, 3, 4, 4)] + ) + assert shapely.area(actual) == 98.0 + + +def test_polygon_with_none_hole(): + actual = shapely.polygons( + shapely.linearrings(box_tpl(0, 0, 10, 10)), + [ + shapely.linearrings(box_tpl(1, 1, 2, 2)), + None, + shapely.linearrings(box_tpl(3, 3, 4, 4)), + ], + ) + assert shapely.area(actual) == 98.0 + + +def test_2_polygons_with_same_hole(): + actual = shapely.polygons( + [box_tpl(0, 0, 10, 10), box_tpl(0, 0, 5, 5)], [box_tpl(1, 1, 2, 2)] + ) + assert shapely.area(actual).tolist() == [99.0, 24.0] + + +def test_2_polygons_with_2_same_holes(): + actual = shapely.polygons( + [box_tpl(0, 0, 10, 10), box_tpl(0, 0, 5, 5)], + [box_tpl(1, 1, 2, 2), box_tpl(3, 3, 4, 4)], + ) + assert shapely.area(actual).tolist() == [98.0, 23.0] + + +def test_2_polygons_with_different_holes(): + actual = shapely.polygons( + [box_tpl(0, 0, 10, 10), box_tpl(0, 0, 5, 5)], + [[box_tpl(1, 1, 3, 3)], [box_tpl(1, 1, 2, 2)]], + ) + assert shapely.area(actual).tolist() == [96.0, 24.0] + + +def test_polygons_not_enough_points_in_shell_scalar(): + with pytest.raises(ValueError): + shapely.polygons((1, 1)) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 1, 2), # 2 linearrings of 1 2D point + (1, 1, 2), # 1 linearring of 1 2D point + (1, 2), # 1 linearring of 1 2D point (scalar) + (2, 2, 2), # 2 linearrings of 2 2D points + (1, 2, 2), # 1 linearring of 2 2D points + (2, 2), # 1 linearring of 2 2D points (scalar) + ], +) +def test_polygons_not_enough_points_in_shell(shape): + coords = np.ones(shape) + with pytest.raises(ValueError): + shapely.polygons(coords) + + # make sure the first coordinate != second coordinate + coords[..., 1] += 1 + with pytest.raises(ValueError): + shapely.polygons(coords) + + +def test_polygons_not_enough_points_in_holes_scalar(): + with pytest.raises(ValueError): + shapely.polygons(np.ones((1, 4, 2)), (1, 1)) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 1, 2), # 2 linearrings of 1 2D point + (1, 1, 2), # 1 linearring of 1 2D point + (1, 2), # 1 linearring of 1 2D point (scalar) + (2, 2, 2), # 2 linearrings of 2 2D points + (1, 2, 2), # 1 linearring of 2 2D points + (2, 2), # 1 linearring of 2 2D points (scalar) + ], +) +def test_polygons_not_enough_points_in_holes(shape): + coords = np.ones(shape) + with pytest.raises(ValueError): + shapely.polygons(np.ones((1, 4, 2)), coords) + + # make sure the first coordinate != second coordinate + coords[..., 1] += 1 + with pytest.raises(ValueError): + shapely.polygons(np.ones((1, 4, 2)), coords) + + +@pytest.mark.parametrize( + "func,expected", + [ + (shapely.multipoints, MultiPoint()), + (shapely.multilinestrings, MultiLineString()), + (shapely.multipolygons, MultiPolygon()), + (shapely.geometrycollections, GeometryCollection()), + ], +) +def test_create_collection_only_none(func, expected): + actual = func(np.array([None], dtype=object)) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "func,sub_geom", + [ + (shapely.multipoints, point), + (shapely.multilinestrings, line_string), + (shapely.multilinestrings, linear_ring), + (shapely.multipolygons, polygon), + (shapely.geometrycollections, point), + (shapely.geometrycollections, line_string), + (shapely.geometrycollections, linear_ring), + (shapely.geometrycollections, polygon), + (shapely.geometrycollections, multi_point), + (shapely.geometrycollections, multi_line_string), + (shapely.geometrycollections, multi_polygon), + (shapely.geometrycollections, geometry_collection), + ], +) +def test_create_collection(func, sub_geom): + actual = func([sub_geom, sub_geom]) + assert shapely.get_num_geometries(actual) == 2 + + +@pytest.mark.parametrize( + "func,sub_geom", + [ + (shapely.multipoints, point), + (shapely.multilinestrings, line_string), + (shapely.multipolygons, polygon), + (shapely.geometrycollections, polygon), + ], +) +def test_create_collection_skips_none(func, sub_geom): + actual = func([sub_geom, None, None, sub_geom]) + assert shapely.get_num_geometries(actual) == 2 + + +@pytest.mark.parametrize( + "func,sub_geom", + [ + (shapely.multipoints, line_string), + (shapely.multipoints, geometry_collection), + (shapely.multipoints, multi_point), + (shapely.multilinestrings, point), + (shapely.multilinestrings, polygon), + (shapely.multilinestrings, multi_line_string), + (shapely.multipolygons, linear_ring), + (shapely.multipolygons, multi_point), + (shapely.multipolygons, multi_polygon), + ], +) +def test_create_collection_wrong_geom_type(func, sub_geom): + with pytest.raises(TypeError): + func([sub_geom]) + + +@pytest.mark.parametrize( + "coords,ccw,expected", + [ + ((0, 0, 1, 1), True, Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)])), + ( + (0, 0, 1, 1), + False, + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + ), + ], +) +def test_box(coords, ccw, expected): + actual = shapely.box(*coords, ccw=ccw) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "coords,ccw,expected", + [ + ( + (0, 0, [1, 2], [1, 2]), + True, + [ + Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)]), + Polygon([(2, 0), (2, 2), (0, 2), (0, 0), (2, 0)]), + ], + ), + ( + (0, 0, [1, 2], [1, 2]), + [True, False], + [ + Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)]), + Polygon([(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]), + ], + ), + ], +) +def test_box_array(coords, ccw, expected): + actual = shapely.box(*coords, ccw=ccw) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "coords", + [ + [np.nan, np.nan, np.nan, np.nan], + [np.nan, 0, 1, 1], + [0, np.nan, 1, 1], + [0, 0, np.nan, 1], + [0, 0, 1, np.nan], + ], +) +def test_box_nan(coords): + assert shapely.box(*coords) is None + + +def test_box_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `ccw` for `box` is deprecated" + ): + shapely.box(0, 0, 1, 1, True) + + +def test_prepare(): + arr = np.array([shapely.points(1, 1), None, shapely.box(0, 0, 1, 1)]) + assert arr[0]._geom_prepared == 0 + assert arr[2]._geom_prepared == 0 + shapely.prepare(arr) + assert arr[0]._geom_prepared != 0 + assert arr[1] is None + assert arr[2]._geom_prepared != 0 + + # preparing again actually does nothing + original = arr[0]._geom_prepared + shapely.prepare(arr) + assert arr[0]._geom_prepared == original + + +def test_destroy_prepared(): + arr = np.array([shapely.points(1, 1), None, shapely.box(0, 0, 1, 1)]) + shapely.prepare(arr) + assert arr[0]._geom_prepared != 0 + assert arr[2]._geom_prepared != 0 + shapely.destroy_prepared(arr) + assert arr[0]._geom_prepared == 0 + assert arr[1] is None + assert arr[2]._geom_prepared == 0 + shapely.destroy_prepared(arr) # does not error + + +@pytest.mark.parametrize("geom_type", [None, GeometryType.MISSING, -1]) +def test_empty_missing(geom_type): + actual = shapely.empty((2,), geom_type=geom_type) + assert shapely.is_missing(actual).all() + + +@pytest.mark.parametrize("geom_type", range(8)) +def test_empty(geom_type): + actual = shapely.empty((2,), geom_type=geom_type) + assert (~shapely.is_missing(actual)).all() + assert shapely.is_empty(actual).all() + assert (shapely.get_type_id(actual) == geom_type).all() diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_creation_indices.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_creation_indices.py new file mode 100644 index 0000000000000000000000000000000000000000..86d7e8625ecb8367c2ed7353b266bf4522eb3089 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_creation_indices.py @@ -0,0 +1,585 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import shapely +from shapely import LinearRing, Polygon +from shapely.testing import assert_geometries_equal +from shapely.tests.common import empty_point, line_string, linear_ring, point, polygon + +pnts = shapely.points +lstrs = shapely.linestrings +geom_coll = shapely.geometrycollections + + +@pytest.mark.parametrize( + "func", [shapely.points, shapely.linestrings, shapely.linearrings] +) +@pytest.mark.parametrize( + "coordinates", + [ + np.empty((2,)), # not enough dimensions + np.empty((2, 4, 1)), # too many dimensions + np.empty((2, 4)), # wrong inner dimension size + None, + np.full((2, 2), "foo", dtype=object), # wrong type + ], +) +def test_invalid_coordinates(func, coordinates): + with pytest.raises((TypeError, ValueError)): + func(coordinates, indices=[0, 1]) + + +@pytest.mark.parametrize( + "func", + [ + shapely.multipoints, + shapely.multilinestrings, + shapely.multipolygons, + shapely.geometrycollections, + ], +) +@pytest.mark.parametrize( + "geometries", [np.array([1, 2], dtype=np.intp), None, np.array([[point]]), "hello"] +) +def test_invalid_geometries(func, geometries): + with pytest.raises((TypeError, ValueError)): + func(geometries, indices=[0, 1]) + + +@pytest.mark.parametrize( + "func", [shapely.points, shapely.linestrings, shapely.linearrings] +) +@pytest.mark.parametrize("indices", [[point], " hello", [0, 1], [-1]]) +def test_invalid_indices_simple(func, indices): + with pytest.raises((TypeError, ValueError)): + func([[0.2, 0.3]], indices=indices) + + +non_writeable = np.empty(3, dtype=object) +non_writeable.flags.writeable = False + + +@pytest.mark.parametrize( + "func", [shapely.points, shapely.linestrings, shapely.geometrycollections] +) +@pytest.mark.parametrize( + "out", + [ + [None, None, None], # not an ndarray + np.empty(3), # wrong dtype + non_writeable, # not writeable + np.empty((3, 2), dtype=object), # too many dimensions + np.empty((), dtype=object), # too few dimensions + np.empty((2,), dtype=object), # too small + ], +) +def test_invalid_out(func, out): + if func is shapely.points: + x = [[0.2, 0.3], [0.4, 0.5]] + indices = [0, 2] + elif func is shapely.linestrings: + x = [[1, 1], [2, 1], [2, 2], [3, 3], [3, 4], [4, 4]] + indices = [0, 0, 0, 2, 2, 2] + else: + x = [point, line_string] + indices = [0, 2] + with pytest.raises((TypeError, ValueError)): + func(x, indices=indices, out=out) + + +def test_points_invalid(): + # attempt to construct a point with 2 coordinates + with pytest.raises(shapely.GEOSException): + shapely.points([[1, 1], [2, 2]], indices=[0, 0]) + + +def test_points(): + actual = shapely.points( + np.array([[2, 3], [2, 3]], dtype=float), + indices=np.array([0, 1], dtype=np.intp), + ) + assert_geometries_equal(actual, [point, point]) + + +def test_points_no_index_raises(): + with pytest.raises(ValueError): + shapely.points( + np.array([[2, 3], [2, 3]], dtype=float), + indices=np.array([0, 2], dtype=np.intp), + ) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 1], [point, point, empty_point, None]), + ([0, 3], [point, None, empty_point, point]), + ([2, 3], [None, None, point, point]), + ], +) +def test_points_out(indices, expected): + out = np.empty(4, dtype=object) + out[2] = empty_point + actual = shapely.points( + [[2, 3], [2, 3]], + indices=indices, + out=out, + ) + assert_geometries_equal(out, expected) + assert actual is out + + +@pytest.mark.parametrize( + "coordinates,indices,expected", + [ + ([[1, 1], [2, 2]], [0, 0], [lstrs([[1, 1], [2, 2]])]), + ([[1, 1, 1], [2, 2, 2]], [0, 0], [lstrs([[1, 1, 1], [2, 2, 2]])]), + ( + [[1, 1], [2, 2], [2, 2], [3, 3]], + [0, 0, 1, 1], + [lstrs([[1, 1], [2, 2]]), lstrs([[2, 2], [3, 3]])], + ), + ], +) +def test_linestrings(coordinates, indices, expected): + actual = shapely.linestrings( + np.array(coordinates, dtype=float), indices=np.array(indices, dtype=np.intp) + ) + assert_geometries_equal(actual, expected) + + +def test_linestrings_invalid(): + # attempt to construct linestrings with 1 coordinate + with pytest.raises(shapely.GEOSException): + shapely.linestrings([[1, 1], [2, 2]], indices=[0, 1]) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 0, 0, 1, 1, 1], [line_string, line_string, empty_point, None]), + ([0, 0, 0, 3, 3, 3], [line_string, None, empty_point, line_string]), + ([2, 2, 2, 3, 3, 3], [None, None, line_string, line_string]), + ], +) +def test_linestrings_out(indices, expected): + out = np.empty(4, dtype=object) + out[2] = empty_point + actual = shapely.linestrings( + [(0, 0), (1, 0), (1, 1), (0, 0), (1, 0), (1, 1)], + indices=indices, + out=out, + ) + assert_geometries_equal(out, expected) + assert actual is out + + +@pytest.mark.parametrize( + "coordinates", + [ + [[1, 1], [1, float("nan")], [2, 2]], + ], +) +def test_linestrings_allow_nan(coordinates): + actual = shapely.linestrings( + np.array(coordinates, dtype=float), + indices=np.zeros(len(coordinates), dtype=np.intp), + ) + assert_array_equal(shapely.get_coordinates(actual), coordinates) + + +@pytest.mark.parametrize( + "coordinates,indices,expected", + [ + ([[1, 1], [1, float("nan")], [2, 2]], [0, 0, 0], [lstrs([[1, 1], [2, 2]])]), + ], +) +def test_linestrings_handle_nan_skip(coordinates, indices, expected): + actual = shapely.linestrings( + np.array(coordinates, dtype=float), + indices=np.array(indices, dtype=np.intp), + handle_nan="skip", + ) + assert_geometries_equal(actual, expected) + + +def test_linestrings_handle_nan_skip_invalid(): + # the NaN makes the linestring too short + with pytest.raises(shapely.GEOSException): + shapely.linestrings( + [[1, 1], [2, float("nan")]], indices=[0, 0], handle_nan="skip" + ) + + +def test_linestrings_handle_nan_skip_only_nan(): + actual = shapely.linestrings( + np.full((3, 2), fill_value=np.nan), indices=[0, 0, 0], handle_nan="skip" + ) + assert actual[0].is_empty + + +def test_linestrings_handle_nan_error(): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.linestrings( + [[0, 0], [float("nan"), 0], [1, 1]], indices=[0, 0, 0], handle_nan="error" + ) + + +@pytest.mark.parametrize( + "coordinates", [([[1, 1], [2, 1], [2, 2], [1, 1]]), ([[1, 1], [2, 1], [2, 2]])] +) +def test_linearrings(coordinates): + actual = shapely.linearrings( + np.array(coordinates, dtype=np.float64), + indices=np.zeros(len(coordinates), dtype=np.intp), + ) + assert_geometries_equal(actual, shapely.linearrings(coordinates)) + + +@pytest.mark.parametrize( + "coordinates", + [ + ([[1, 1], [1, 1]]), # too short + ([[1, np.nan], [2, 1], [2, 2], [1, 1]]), # starting with nan + ], +) +def test_linearrings_invalid(coordinates): + with pytest.raises((shapely.GEOSException, ValueError)): + shapely.linearrings(coordinates, indices=np.zeros(len(coordinates))) + + +def test_linearrings_unclosed_all_coords_equal(): + actual = shapely.linearrings([(0, 0), (0, 0), (0, 0)], indices=np.zeros(3)) + assert_geometries_equal(actual, LinearRing([(0, 0), (0, 0), (0, 0), (0, 0)])) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 0, 0, 0, 0], [linear_ring, None, None, empty_point]), + ([1, 1, 1, 1, 1], [None, linear_ring, None, empty_point]), + ([3, 3, 3, 3, 3], [None, None, None, linear_ring]), + ], +) +def test_linearrings_out(indices, expected): + out = np.empty(4, dtype=object) + out[3] = empty_point + actual = shapely.linearrings( + [(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], + indices=indices, + out=out, + ) + assert_geometries_equal(out, expected) + assert actual is out + + +@pytest.mark.parametrize("dim", [2, 3]) +@pytest.mark.parametrize("order", ["C", "F"]) +def test_linearrings_buffer(dim, order): + coords = np.random.randn(10, 4, dim) + coords1 = np.asarray(coords.reshape(10 * 4, dim), order=order) + indices1 = np.repeat(range(10), 4) + result1 = shapely.linearrings(coords1, indices=indices1) + + # with manual closure -> can directly copy from buffer if C order + coords2 = np.hstack((coords, coords[:, [0], :])) + coords2 = np.asarray(coords2.reshape(10 * 5, dim), order=order) + indices2 = np.repeat(range(10), 5) + result2 = shapely.linearrings(coords2, indices=indices2) + assert_geometries_equal(result1, result2) + + +@pytest.mark.parametrize( + "coordinates", + [ + [[1, 1], [2, 1], [2, float("nan")], [1, 1]], + ], +) +def test_linearrings_allow_nan(coordinates): + actual = shapely.linearrings( + np.array(coordinates, dtype=float), + indices=np.zeros(len(coordinates), dtype=np.intp), + ) + assert_array_equal(shapely.get_coordinates(actual), coordinates) + + +@pytest.mark.parametrize( + "coordinates", + [ + [[1, 1], [2, 1], [2, 2], [2, float("nan")], [1, 1]], + [[1, 1], [2, 1], [2, float("nan")], [2, 2]], + [[1, 1], [2, 1], [2, 2], [1, 1], [2, float("nan")]], + [[2, float("nan")], [1, 1], [2, 1], [2, 2], [1, 1]], + [[1, 1], [2, 1], [2, 2], [2, float("nan")]], + [[2, float("nan")], [1, 1], [2, 1], [2, 2]], + ], +) +def test_linearrings_handle_nan_skip(coordinates): + actual = shapely.linearrings( + np.array(coordinates, dtype=np.float64), + indices=np.zeros(len(coordinates), dtype=np.intp), + handle_nan="skip", + ) + assert_geometries_equal(actual, shapely.linearrings(coordinates, handle_nan="skip")) + + +def test_linearrings_handle_nan_skip_invalid(): + # the NaN makes the linearring too short + with pytest.raises(ValueError): + shapely.linearrings( + [[1, 1], [float("nan"), 1], [1, 1]], indices=[0, 0, 0], handle_nan="skip" + ) + + +def test_linearrings_handle_nan_skip_only_nan(): + actual = shapely.linearrings( + np.full((5, 2), fill_value=np.nan), indices=[0] * 5, handle_nan="skip" + ) + + assert actual[0].is_empty + + +def test_linearrings_handle_nan_error(): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.linearrings( + [[1, 1], [2, 1], [2, 2], [2, float("nan")], [1, 1]], + indices=[0, 0, 0, 0, 0], + handle_nan="error", + ) + + +hole_1 = shapely.linearrings([(0.2, 0.2), (0.2, 0.4), (0.4, 0.4)]) +hole_2 = shapely.linearrings([(0.6, 0.6), (0.6, 0.8), (0.8, 0.8)]) +poly = shapely.polygons(linear_ring) +poly_empty = Polygon() +poly_hole_1 = shapely.polygons(linear_ring, holes=[hole_1]) +poly_hole_2 = shapely.polygons(linear_ring, holes=[hole_2]) +poly_hole_1_2 = shapely.polygons(linear_ring, holes=[hole_1, hole_2]) + + +@pytest.mark.parametrize( + "rings,indices,expected", + [ + ([linear_ring, linear_ring], [0, 1], [poly, poly]), + ([None, linear_ring], [0, 1], [poly_empty, poly]), + ([None, linear_ring, None, None], [0, 0, 1, 1], [poly, poly_empty]), + ([linear_ring, hole_1, linear_ring], [0, 0, 1], [poly_hole_1, poly]), + ([linear_ring, linear_ring, hole_1], [0, 1, 1], [poly, poly_hole_1]), + ([None, linear_ring, linear_ring, hole_1], [0, 0, 1, 1], [poly, poly_hole_1]), + ([linear_ring, None, linear_ring, hole_1], [0, 0, 1, 1], [poly, poly_hole_1]), + ([linear_ring, None, linear_ring, hole_1], [0, 1, 1, 1], [poly, poly_hole_1]), + ([linear_ring, linear_ring, None, hole_1], [0, 1, 1, 1], [poly, poly_hole_1]), + ([linear_ring, linear_ring, hole_1, None], [0, 1, 1, 1], [poly, poly_hole_1]), + ( + [linear_ring, hole_1, hole_2, linear_ring], + [0, 0, 0, 1], + [poly_hole_1_2, poly], + ), + ( + [linear_ring, hole_1, linear_ring, hole_2], + [0, 0, 1, 1], + [poly_hole_1, poly_hole_2], + ), + ( + [linear_ring, linear_ring, hole_1, hole_2], + [0, 1, 1, 1], + [poly, poly_hole_1_2], + ), + ( + [linear_ring, hole_1, None, hole_2, linear_ring], + [0, 0, 0, 0, 1], + [poly_hole_1_2, poly], + ), + ( + [linear_ring, hole_1, None, linear_ring, hole_2], + [0, 0, 0, 1, 1], + [poly_hole_1, poly_hole_2], + ), + ( + [linear_ring, hole_1, linear_ring, None, hole_2], + [0, 0, 1, 1, 1], + [poly_hole_1, poly_hole_2], + ), + ], +) +def test_polygons(rings, indices, expected): + actual = shapely.polygons( + np.array(rings, dtype=object), indices=np.array(indices, dtype=np.intp) + ) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 1], [poly, poly, empty_point, None]), + ([0, 3], [poly, None, empty_point, poly]), + ([2, 3], [None, None, poly, poly]), + ], +) +def test_polygons_out(indices, expected): + out = np.empty(4, dtype=object) + out[2] = empty_point + actual = shapely.polygons([linear_ring, linear_ring], indices=indices, out=out) + assert_geometries_equal(out, expected) + assert actual is out + + +@pytest.mark.parametrize( + "func", + [ + shapely.polygons, + shapely.multipoints, + shapely.multilinestrings, + shapely.multipolygons, + shapely.geometrycollections, + ], +) +@pytest.mark.parametrize("indices", [np.array([point]), " hello", [0, 1], [-1]]) +def test_invalid_indices_collections(func, indices): + with pytest.raises((TypeError, ValueError)): + func([point], indices=indices) + + +@pytest.mark.parametrize( + "geometries,indices,expected", + [ + ([point, line_string], [0, 0], [geom_coll([point, line_string])]), + ([point, line_string], [0, 1], [geom_coll([point]), geom_coll([line_string])]), + ([point, None], [0, 0], [geom_coll([point])]), + ([point, None], [0, 1], [geom_coll([point]), geom_coll([])]), + ([None, point, None, None], [0, 0, 1, 1], [geom_coll([point]), geom_coll([])]), + ([point, None, line_string], [0, 0, 0], [geom_coll([point, line_string])]), + ], +) +def test_geometrycollections(geometries, indices, expected): + actual = shapely.geometrycollections( + np.array(geometries, dtype=object), indices=indices + ) + assert_geometries_equal(actual, expected) + + +def test_geometrycollections_no_index_raises(): + with pytest.raises(ValueError): + shapely.geometrycollections( + np.array([point, line_string], dtype=object), indices=[0, 2] + ) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 0], [geom_coll([point, line_string]), None, None, empty_point]), + ([3, 3], [None, None, None, geom_coll([point, line_string])]), + ], +) +def test_geometrycollections_out(indices, expected): + out = np.empty(4, dtype=object) + out[3] = empty_point + actual = shapely.geometrycollections([point, line_string], indices=indices, out=out) + assert_geometries_equal(out, expected) + assert actual is out + + +def test_multipoints(): + actual = shapely.multipoints( + np.array([point], dtype=object), indices=np.zeros(1, dtype=np.intp) + ) + assert_geometries_equal(actual, shapely.multipoints([point])) + + +def test_multilinestrings(): + actual = shapely.multilinestrings( + np.array([line_string], dtype=object), indices=np.zeros(1, dtype=np.intp) + ) + assert_geometries_equal(actual, shapely.multilinestrings([line_string])) + + +def test_multilinearrings(): + actual = shapely.multilinestrings( + np.array([linear_ring], dtype=object), indices=np.zeros(1, dtype=np.intp) + ) + assert_geometries_equal(actual, shapely.multilinestrings([linear_ring])) + + +def test_multipolygons(): + actual = shapely.multipolygons( + np.array([polygon], dtype=object), indices=np.zeros(1, dtype=np.intp) + ) + assert_geometries_equal(actual, shapely.multipolygons([polygon])) + + +@pytest.mark.parametrize( + "geometries,func", + [ + ([point], shapely.polygons), + ([line_string], shapely.polygons), + ([polygon], shapely.polygons), + ([line_string], shapely.multipoints), + ([polygon], shapely.multipoints), + ([point], shapely.multilinestrings), + ([polygon], shapely.multilinestrings), + ([point], shapely.multipolygons), + ([line_string], shapely.multipolygons), + ], +) +def test_incompatible_types(geometries, func): + with pytest.raises(TypeError): + func(geometries, indices=[0]) + + +def test_points_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `points` is deprecated" + ): + shapely.points([[0, 1], [2, 3]], None, None, [0, 1]) + + +def test_linestrings_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `linestrings` is deprecated" + ): + shapely.linestrings([[0, 1], [2, 3], [4, 5], [6, 7]], None, None, [0, 0, 1, 1]) + + +def test_linearrings_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `linearrings` is deprecated" + ): + shapely.linearrings([[0, 1], [1, 1], [1, 0]], None, None, [0, 0, 0]) + + +def test_polygons_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `polygons` is deprecated" + ): + shapely.polygons([linear_ring, linear_ring], None, [0, 1]) + + +def test_multipoints_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `multipoints` is deprecated" + ): + shapely.multipoints([point, point], [0, 1]) + + +def test_multilinestrings_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `multilinestrings` is deprecated" + ): + shapely.multilinestrings([line_string, line_string], [0, 1]) + + +def test_multipolygons_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `multipolygons` is deprecated" + ): + shapely.multipolygons([polygon, polygon], [0, 1]) + + +def test_geometrycollections_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `geometrycollections` is deprecated" + ): + shapely.geometrycollections([point, polygon], [0, 1]) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_decorators.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..0ba8ba7182f2fa504351424e7b6e2e4dbde793dc --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_decorators.py @@ -0,0 +1,138 @@ +import pytest +from pytest import WarningsRecorder + +from shapely.decorators import deprecate_positional + + +@deprecate_positional(["b", "c"]) +def func_two(a, b=2, c=3): + return a, b, c + + +@deprecate_positional(["b", "c", "d"]) +def func_three(a, b=1, c=2, d=3): + return a, b, c, d + + +@deprecate_positional(["b", "d"]) +def func_noncontig(a, b=1, c=2, d=3): + return a, b, c, d + + +@deprecate_positional(["b"], category=UserWarning) +def func_custom_category(a, b=1): + return a, b + + +@deprecate_positional(["b"]) +def func_varargs(a, b=1, *args): + return a, b, args + + +@deprecate_positional([]) +def func_no_deprecations(a, b=1): + return a, b + + +def test_all_kwargs_no_warning(recwarn: WarningsRecorder) -> None: + assert func_two(a=10, b=20, c=30) == (10, 20, 30) + assert not recwarn.list + + +def test_only_required_arg_no_warning(recwarn: WarningsRecorder) -> None: + assert func_two(1) == (1, 2, 3) + assert not recwarn.list + + +def test_single_positional_warning() -> None: + with pytest.warns( + DeprecationWarning, match="positional argument `b` for `func_two` is deprecated" + ): + out = func_two(1, 4) + assert out == (1, 4, 3) + + +def test_multiple_positional_warning() -> None: + with pytest.warns( + DeprecationWarning, + match="positional arguments `b` and `c` for `func_two` are deprecated", + ): + out = func_two(1, 4, 5) + assert out == (1, 4, 5) + + +def test_three_positional_warning_oxford_comma() -> None: + with pytest.warns( + DeprecationWarning, + match="positional arguments `b`, `c`, and `d` for `func_three` are deprecated", + ): + out = func_three(1, 2, 3, 4) + assert out == (1, 2, 3, 4) + + +def test_noncontiguous_partial_warning() -> None: + with pytest.warns( + DeprecationWarning, + match="positional argument `b` for `func_noncontig` is deprecated", + ): + out = func_noncontig(1, 2, 3) + assert out == (1, 2, 3, 3) + + +def test_noncontiguous_full_warning() -> None: + with pytest.warns( + DeprecationWarning, + match="positional arguments `b` and `d` for `func_noncontig` are deprecated", + ): + out = func_noncontig(1, 2, 3, 4) + assert out == (1, 2, 3, 4) + + +def test_custom_warning_category() -> None: + with pytest.warns( + UserWarning, + match="positional argument `b` for `func_custom_category` is deprecated", + ): + out = func_custom_category(1, 2) + assert out == (1, 2) + + +def test_func_no_deprecations_never_warns(recwarn: WarningsRecorder) -> None: + out = func_no_deprecations(7, 8) + assert out == (7, 8) + assert not recwarn.list + + +def test_missing_required_arg_no_warning(recwarn: WarningsRecorder) -> None: + with pytest.raises(TypeError): + func_two() # missing required 'a' # type: ignore + assert not recwarn.list + + +def test_unknown_keyword_no_warning(recwarn: WarningsRecorder) -> None: + with pytest.raises(TypeError): + func_two(1, 4, d=5) # unknown keyword 'd' # type: ignore + assert not recwarn.list + + +def test_varargs_behavior_and_deprecation() -> None: + with pytest.warns( + DeprecationWarning, + match="positional argument `b` for `func_varargs` is deprecated", + ): + out = func_varargs(1, 2, 3, 4) + assert out == (1, 2, (3, 4)) + + +def test_varargs_no_warning(recwarn: WarningsRecorder) -> None: + out = func_varargs(1) + assert out == (1, 1, ()) + assert not recwarn.list + + +def test_repeated_warnings() -> None: + with pytest.warns(DeprecationWarning) as record: + func_two(1, 4, 5) + func_two(1, 4, 5) + assert len(record) == 2 + assert str(record[0].message) == str(record[1].message) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_geometry.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..8a255befe04c65c944207d473560c7e0e0fdcdd2 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_geometry.py @@ -0,0 +1,739 @@ +import warnings + +import numpy as np +import pytest + +import shapely +from shapely import LinearRing, LineString, MultiPolygon, Point, Polygon +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + all_types, + empty as empty_geometry_collection, + empty_line_string, + empty_line_string_z, + empty_point, + empty_point_z, + empty_polygon, + equal_geometries_abnormally_yield_unequal, + geometry_collection, + geometry_collection_z, + ignore_invalid, + ignore_warnings, + line_string, + line_string_nan, + line_string_z, + linear_ring, + multi_line_string, + multi_line_string_z, + multi_point, + multi_point_z, + multi_polygon, + multi_polygon_z, + point, + point_m, + point_z, + point_zm, + polygon, + polygon_with_hole, + polygon_with_hole_z, + polygon_z, +) + + +def test_get_num_points(): + actual = shapely.get_num_points(all_types + (None,)).tolist() + assert actual == [0, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + +def test_get_num_interior_rings(): + actual = shapely.get_num_interior_rings(all_types + (None,)).tolist() + assert actual == [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + +def test_get_num_geometries(): + actual = shapely.get_num_geometries(all_types + (None,)).tolist() + assert actual == [1, 1, 1, 1, 1, 2, 1, 2, 2, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0] + + +@pytest.mark.parametrize( + "geom", + [ + point, + polygon, + multi_point, + multi_line_string, + multi_polygon, + geometry_collection, + ], +) +def test_get_point_non_linestring(geom): + actual = shapely.get_point(geom, [0, 2, -1]) + assert shapely.is_missing(actual).all() + + +@pytest.mark.parametrize("geom", [line_string, linear_ring]) +def test_get_point(geom): + n = shapely.get_num_points(geom) + actual = shapely.get_point(geom, [0, -n, n, -(n + 1)]) + assert_geometries_equal(actual[0], actual[1]) + assert shapely.is_missing(actual[2:4]).all() + + +@pytest.mark.parametrize( + "geom", + [ + point, + line_string, + linear_ring, + multi_point, + multi_line_string, + multi_polygon, + geometry_collection, + ], +) +def test_get_exterior_ring_non_polygon(geom): + actual = shapely.get_exterior_ring(geom) + assert shapely.is_missing(actual).all() + + +def test_get_exterior_ring(): + actual = shapely.get_exterior_ring([polygon, polygon_with_hole]) + assert (shapely.get_type_id(actual) == shapely.GeometryType.LINEARRING).all() + + +@pytest.mark.parametrize( + "geom", + [ + point, + line_string, + linear_ring, + multi_point, + multi_line_string, + multi_polygon, + geometry_collection, + ], +) +def test_get_interior_ring_non_polygon(geom): + actual = shapely.get_interior_ring(geom, [0, 2, -1]) + assert shapely.is_missing(actual).all() + + +def test_get_interior_ring(): + actual = shapely.get_interior_ring(polygon_with_hole, [0, -1, 1, -2]) + assert_geometries_equal(actual[0], actual[1]) + assert shapely.is_missing(actual[2:4]).all() + + +@pytest.mark.parametrize("geom", [point, line_string, linear_ring, polygon]) +def test_get_geometry_simple(geom): + actual = shapely.get_geometry(geom, [0, -1, 1, -2]) + assert_geometries_equal(actual[0], actual[1]) + assert shapely.is_missing(actual[2:4]).all() + + +@pytest.mark.parametrize( + "geom", [multi_point, multi_line_string, multi_polygon, geometry_collection] +) +def test_get_geometry_collection(geom): + n = shapely.get_num_geometries(geom) + actual = shapely.get_geometry(geom, [0, -n, n, -(n + 1)]) + assert_geometries_equal(actual[0], actual[1]) + assert shapely.is_missing(actual[2:4]).all() + + +def test_get_type_id(): + actual = shapely.get_type_id(all_types + (None,)).tolist() + assert actual == [0, 1, 2, 3, 3, 4, 5, 6, 7, 7, 0, 1, 3, 4, 5, 6, 4, 5, 6, 7, -1] + + +def test_get_dimensions(): + actual = shapely.get_dimensions(all_types + (None,)).tolist() + assert actual == [0, 1, 1, 2, 2, 0, 1, 2, 1, -1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 1, -1] + + +def test_get_coordinate_dimension(): + actual = shapely.get_coordinate_dimension([point, point_z, None]).tolist() + assert actual == [2, 3, -1] + + +def test_get_num_coordinates(): + actual = shapely.get_num_coordinates(all_types + (None,)).tolist() + assert actual == [1, 3, 5, 5, 10, 2, 2, 10, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + +def test_get_srid(): + """All geometry types have no SRID by default; None returns -1""" + actual = shapely.get_srid(all_types + (None,)).tolist() + assert actual == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1] + + +def test_get_set_srid(): + actual = shapely.set_srid(point, 4326) + assert shapely.get_srid(point) == 0 + assert shapely.get_srid(actual) == 4326 + + +@pytest.mark.parametrize( + "func", + [ + shapely.get_x, + shapely.get_y, + shapely.get_z, + pytest.param( + shapely.get_m, + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + ], +) +@pytest.mark.parametrize( + "geom", + np.array(all_types)[shapely.get_type_id(all_types) != shapely.GeometryType.POINT], +) +def test_get_xyz_no_point(func, geom): + assert np.isnan(func(geom)) + + +def test_get_x(): + assert shapely.get_x([point, point_z]).tolist() == [2.0, 2.0] + + +def test_get_y(): + assert shapely.get_y([point, point_z]).tolist() == [3.0, 3.0] + + +def test_get_z(): + assert shapely.get_z([point_z]).tolist() == [4.0] + + +def test_get_z_2d(): + assert np.isnan(shapely.get_z(point)) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +def test_get_m(): + assert shapely.get_m([point_m, point_zm]).tolist() == [5.0, 5.0] + assert np.isnan(shapely.get_m(point)) + assert np.isnan(shapely.get_m(point_z)) + + +@pytest.mark.parametrize("geom", all_types) +def test_new_from_wkt(geom): + actual = shapely.from_wkt(str(geom)) + if equal_geometries_abnormally_yield_unequal(geom): + # abnormal test + with pytest.raises(AssertionError): + assert_geometries_equal(actual, geom) + else: + # normal test + assert_geometries_equal(actual, geom) + + +def test_adapt_ptr_raises(): + point = Point(2, 2) + with pytest.raises(AttributeError): + point._geom += 1 + + +@pytest.mark.parametrize("geom", all_types) +def test_set_unique(geom): + a = {geom, shapely.transform(geom, lambda x: x)} + assert len(a) == 1 + + +def test_set_nan(): + # Although NaN != NaN, you cannot have multiple "NaN" points in a set + # This is because "NaN" coordinates in a geometry are considered as equal. + with ignore_invalid(): + a = set(shapely.linestrings([[[np.nan, np.nan], [np.nan, np.nan]]] * 10)) + assert len(a) == 1 # same objects: NaN == NaN (as geometry coordinates) + + +def test_set_nan_same_objects(): + # You can't put identical objects in a set. + # x = float("nan"); set([x, x]) also returns a set with 1 element + a = set([line_string_nan] * 10) + assert len(a) == 1 + + +@pytest.mark.parametrize( + "geom", + [ + point, + multi_point, + line_string, + multi_line_string, + polygon, + multi_polygon, + geometry_collection, + empty_point, + empty_line_string, + empty_polygon, + empty_geometry_collection, + np.array([None]), + np.empty_like(np.array([None])), + ], +) +def test_get_parts(geom): + expected_num_parts = shapely.get_num_geometries(geom) + if expected_num_parts == 0: + expected_parts = [] + else: + expected_parts = shapely.get_geometry(geom, range(expected_num_parts)) + + parts = shapely.get_parts(geom) + assert len(parts) == expected_num_parts + assert_geometries_equal(parts, expected_parts) + + +def test_get_parts_array(): + # note: this also verifies that None is handled correctly + # in the mix; internally it returns -1 for count of geometries + geom = np.array([None, empty_line_string, multi_point, point, multi_polygon]) + expected_parts = [] + for g in geom: + for i in range(shapely.get_num_geometries(g)): + expected_parts.append(shapely.get_geometry(g, i)) + + parts = shapely.get_parts(geom) + assert len(parts) == len(expected_parts) + assert_geometries_equal(parts, expected_parts) + + +def test_get_parts_geometry_collection_multi(): + """On the first pass, the individual Multi* geometry objects are returned + from the collection. On the second pass, the individual singular geometry + objects within those are returned. + """ + geom = shapely.geometrycollections([multi_point, multi_line_string, multi_polygon]) + expected_num_parts = shapely.get_num_geometries(geom) + expected_parts = shapely.get_geometry(geom, range(expected_num_parts)) + + parts = shapely.get_parts(geom) + assert len(parts) == expected_num_parts + assert_geometries_equal(parts, expected_parts) + + expected_subparts = [] + for g in np.asarray(expected_parts): + for i in range(shapely.get_num_geometries(g)): + expected_subparts.append(shapely.get_geometry(g, i)) + + subparts = shapely.get_parts(parts) + assert len(subparts) == len(expected_subparts) + assert_geometries_equal(subparts, expected_subparts) + + +def test_get_parts_return_index(): + geom = np.array([multi_point, point, multi_polygon]) + expected_parts = [] + expected_index = [] + for i, g in enumerate(geom): + for j in range(shapely.get_num_geometries(g)): + expected_parts.append(shapely.get_geometry(g, j)) + expected_index.append(i) + + parts, index = shapely.get_parts(geom, return_index=True) + assert len(parts) == len(expected_parts) + assert_geometries_equal(parts, expected_parts) + assert np.array_equal(index, expected_index) + + +@pytest.mark.parametrize( + "geom", + ([[None]], [[empty_point]], [[multi_point]], [[multi_point, multi_line_string]]), +) +def test_get_parts_invalid_dimensions(geom): + """Only 1D inputs are supported""" + with pytest.raises(ValueError, match="Array should be one dimensional"): + shapely.get_parts(geom) + + +@pytest.mark.parametrize("geom", [point, line_string, polygon]) +def test_get_parts_non_multi(geom): + """Non-multipart geometries should be returned identical to inputs""" + assert_geometries_equal(geom, shapely.get_parts(geom)) + + +@pytest.mark.parametrize("geom", [None, [None], []]) +def test_get_parts_None(geom): + assert len(shapely.get_parts(geom)) == 0 + + +@pytest.mark.parametrize("geom", ["foo", ["foo"], 42]) +def test_get_parts_invalid_geometry(geom): + with pytest.raises(TypeError, match="One of the arguments is of incorrect type."): + shapely.get_parts(geom) + + +def test_get_parts_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `return_index` for `get_parts` is deprecated" + ): + shapely.get_parts(multi_point, False) + + +@pytest.mark.parametrize( + "geom", + [ + point, + multi_point, + line_string, + multi_line_string, + polygon, + multi_polygon, + geometry_collection, + empty_point, + empty_line_string, + empty_polygon, + empty_geometry_collection, + None, + ], +) +def test_get_rings(geom): + if (shapely.get_type_id(geom) != shapely.GeometryType.POLYGON) or shapely.is_empty( + geom + ): + rings = shapely.get_rings(geom) + assert len(rings) == 0 + else: + rings = shapely.get_rings(geom) + assert len(rings) == 1 + assert rings[0] == shapely.get_exterior_ring(geom) + + +def test_get_rings_holes(): + rings = shapely.get_rings(polygon_with_hole) + assert len(rings) == 2 + assert rings[0] == shapely.get_exterior_ring(polygon_with_hole) + assert rings[1] == shapely.get_interior_ring(polygon_with_hole, 0) + + +def test_get_rings_return_index(): + geom = np.array([polygon, None, empty_polygon, polygon_with_hole]) + expected_parts = [] + expected_index = [] + for i, g in enumerate(geom): + if g is None or shapely.is_empty(g): + continue + expected_parts.append(shapely.get_exterior_ring(g)) + expected_index.append(i) + for j in range(shapely.get_num_interior_rings(g)): + expected_parts.append(shapely.get_interior_ring(g, j)) + expected_index.append(i) + + parts, index = shapely.get_rings(geom, return_index=True) + assert len(parts) == len(expected_parts) + assert_geometries_equal(parts, expected_parts) + assert np.array_equal(index, expected_index) + + +@pytest.mark.parametrize("geom", [[[None]], [[polygon]]]) +def test_get_rings_invalid_dimensions(geom): + """Only 1D inputs are supported""" + with pytest.raises(ValueError, match="Array should be one dimensional"): + shapely.get_parts(geom) + + +def test_get_rings_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `return_index` for `get_rings` is deprecated" + ): + shapely.get_rings(polygon, False) + + +def test_get_precision(): + geometries = all_types + (point_z, empty_point, empty_line_string, empty_polygon) + # default is 0 + actual = shapely.get_precision(geometries).tolist() + assert actual == [0] * len(geometries) + + geometry = shapely.set_precision(geometries, 1) + actual = shapely.get_precision(geometry).tolist() + assert actual == [1] * len(geometries) + + +def test_get_precision_none(): + assert np.all(np.isnan(shapely.get_precision([None]))) + + +@pytest.mark.parametrize("mode", ("valid_output", "pointwise", "keep_collapsed")) +def test_set_precision(mode): + initial_geometry = Point(0.9, 0.9) + assert shapely.get_precision(initial_geometry) == 0 + + with ignore_warnings((3, 10, 0), UserWarning): + # GEOS < 3.10 emits warning for 'pointwise' + geometry = shapely.set_precision(initial_geometry, 0, mode=mode) + assert shapely.get_precision(geometry) == 0 + assert_geometries_equal(geometry, initial_geometry) + + with ignore_warnings((3, 10, 0), UserWarning): + geometry = shapely.set_precision(initial_geometry, 1, mode=mode) + assert shapely.get_precision(geometry) == 1 + assert_geometries_equal(geometry, Point(1, 1)) + # original should remain unchanged + assert_geometries_equal(initial_geometry, Point(0.9, 0.9)) + + +def test_set_precision_drop_coords(): + # setting precision of 0 will not drop duplicated points in original + geometry = shapely.set_precision(LineString([(0, 0), (0, 0), (0, 1), (1, 1)]), 0) + assert_geometries_equal(geometry, LineString([(0, 0), (0, 0), (0, 1), (1, 1)])) + + # setting precision will remove duplicated points + geometry = shapely.set_precision(geometry, 1) + assert_geometries_equal(geometry, LineString([(0, 0), (0, 1), (1, 1)])) + + +@pytest.mark.parametrize("mode", ("valid_output", "pointwise", "keep_collapsed")) +def test_set_precision_z(mode): + with ignore_warnings((3, 10, 0), UserWarning): + # GEOS < 3.10 emits warning for 'pointwise' + geometry = shapely.set_precision(Point(0.9, 0.9, 0.9), 1, mode=mode) + assert shapely.get_precision(geometry) == 1 + assert_geometries_equal(geometry, Point(1, 1, 0.9)) + + +@pytest.mark.parametrize("mode", ("valid_output", "pointwise", "keep_collapsed")) +def test_set_precision_nan(mode): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # GEOS emits warnings + actual = shapely.set_precision(line_string_nan, 1, mode=mode) + assert_geometries_equal(actual, line_string_nan) + + +def test_set_precision_none(): + assert shapely.set_precision(None, 0) is None + + +def test_set_precision_grid_size_nan(): + assert shapely.set_precision(Point(0.9, 0.9), np.nan) is None + + +@pytest.mark.parametrize( + "geometry,mode,expected", + [ + ( + Polygon([(2, 2), (4, 2), (3.2, 3), (4, 4), (2, 4), (2.8, 3), (2, 2)]), + "valid_output", + MultiPolygon( + [ + Polygon([(4, 2), (2, 2), (3, 3), (4, 2)]), + Polygon([(2, 4), (4, 4), (3, 3), (2, 4)]), + ] + ), + ), + pytest.param( + Polygon([(2, 2), (4, 2), (3.2, 3), (4, 4), (2, 4), (2.8, 3), (2, 2)]), + "pointwise", + Polygon([(2, 2), (4, 2), (3, 3), (4, 4), (2, 4), (3, 3), (2, 2)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="pointwise does not work pre-GEOS 3.10", + ), + ), + ( + Polygon([(2, 2), (4, 2), (3.2, 3), (4, 4), (2, 4), (2.8, 3), (2, 2)]), + "keep_collapsed", + MultiPolygon( + [ + Polygon([(4, 2), (2, 2), (3, 3), (4, 2)]), + Polygon([(2, 4), (4, 4), (3, 3), (2, 4)]), + ] + ), + ), + (LineString([(0, 0), (0.1, 0.1)]), "valid_output", LineString()), + pytest.param( + LineString([(0, 0), (0.1, 0.1)]), + "pointwise", + LineString([(0, 0), (0, 0)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="pointwise does not work pre-GEOS 3.10", + ), + ), + ( + LineString([(0, 0), (0.1, 0.1)]), + "keep_collapsed", + LineString([(0, 0), (0, 0)]), + ), + pytest.param( + LinearRing([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "valid_output", + LinearRing(), + marks=pytest.mark.skipif( + shapely.geos_version == (3, 10, 0), reason="Segfaults on GEOS 3.10.0" + ), + ), + pytest.param( + LinearRing([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "pointwise", + LinearRing([(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="pointwise does not work pre-GEOS 3.10", + ), + ), + pytest.param( + LinearRing([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "keep_collapsed", + # See https://trac.osgeo.org/geos/ticket/1135#comment:5 + LineString([(0, 0), (0, 0), (0, 0)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="this collapsed into an invalid linearring pre-GEOS 3.10", + ), + ), + ( + Polygon([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "valid_output", + Polygon(), + ), + pytest.param( + Polygon([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "pointwise", + Polygon([(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="pointwise does not work pre-GEOS 3.10", + ), + ), + ( + Polygon([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "keep_collapsed", + Polygon(), + ), + ], +) +def test_set_precision_collapse(geometry, mode, expected): + """Lines and polygons collapse to empty geometries if vertices are too close""" + actual = shapely.set_precision(geometry, 1, mode=mode) + assert_geometries_equal( + # force to 2D because of various dimension issues; GEOS GH-1152 + shapely.force_2d(actual), + expected, + normalize=shapely.geos_version == (3, 9, 0), + ) + + +def test_set_precision_intersection(): + """Operations should use the most precise precision grid size of the inputs""" + + box1 = shapely.normalize(shapely.box(0, 0, 0.9, 0.9)) + box2 = shapely.normalize(shapely.box(0.75, 0, 1.75, 0.75)) + + assert shapely.get_precision(shapely.intersection(box1, box2)) == 0 + + # GEOS will use and keep the most precise precision grid size + box1 = shapely.set_precision(box1, 0.5) + box2 = shapely.set_precision(box2, 1) + out = shapely.intersection(box1, box2) + assert shapely.get_precision(out) == 0.5 + assert_geometries_equal(out, LineString([(1, 1), (1, 0)])) + + +@pytest.mark.parametrize("preserve_topology", [False, True]) +def set_precision_preserve_topology(preserve_topology): + # the preserve_topology kwarg is deprecated (ignored) + with pytest.warns(UserWarning): + actual = shapely.set_precision( + LineString([(0, 0), (0.1, 0.1)]), + 1.0, + preserve_topology=preserve_topology, + ) + assert_geometries_equal(shapely.force_2d(actual), LineString()) + + +@pytest.mark.skipif(shapely.geos_version >= (3, 10, 0), reason="GEOS >= 3.10") +def set_precision_pointwise_pre_310(): + # using 'pointwise' emits a warning + with pytest.warns(UserWarning): + actual = shapely.set_precision( + LineString([(0, 0), (0.1, 0.1)]), + 1.0, + mode="pointwise", + ) + assert_geometries_equal(shapely.force_2d(actual), LineString()) + + +@pytest.mark.parametrize("flags", [np.array([0, 1]), 4, "foo"]) +def set_precision_illegal_flags(flags): + # the preserve_topology kwarg is deprecated (ignored) + with pytest.raises((ValueError, TypeError)): + shapely.lib.set_precision(line_string, 1.0, flags) + + +def test_empty(): + """Compatibility with empty_like, see GH373""" + g = np.empty_like(np.array([None, None])) + assert shapely.is_missing(g).all() + + +# corresponding to geometry_collection_z: +geometry_collection_2 = shapely.geometrycollections([point, line_string]) + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), + (point_z, point), + (empty_point, empty_point), + (empty_point_z, empty_point), + (line_string, line_string), + (line_string_z, line_string), + (empty_line_string, empty_line_string), + (empty_line_string_z, empty_line_string), + (polygon, polygon), + (polygon_z, polygon), + (polygon_with_hole, polygon_with_hole), + (polygon_with_hole_z, polygon_with_hole), + (multi_point, multi_point), + (multi_point_z, multi_point), + (multi_line_string, multi_line_string), + (multi_line_string_z, multi_line_string), + (multi_polygon, multi_polygon), + (multi_polygon_z, multi_polygon), + (geometry_collection_2, geometry_collection_2), + (geometry_collection_z, geometry_collection_2), + ], +) +def test_force_2d(geom, expected): + actual = shapely.force_2d(geom) + assert shapely.get_coordinate_dimension(actual) == 2 + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point_z), + (point_z, point_z), + (empty_point, empty_point_z), + (empty_point_z, empty_point_z), + (line_string, line_string_z), + (line_string_z, line_string_z), + (empty_line_string, empty_line_string_z), + (empty_line_string_z, empty_line_string_z), + (polygon, polygon_z), + (polygon_z, polygon_z), + (polygon_with_hole, polygon_with_hole_z), + (polygon_with_hole_z, polygon_with_hole_z), + (multi_point, multi_point_z), + (multi_point_z, multi_point_z), + (multi_line_string, multi_line_string_z), + (multi_line_string_z, multi_line_string_z), + (multi_polygon, multi_polygon_z), + (multi_polygon_z, multi_polygon_z), + (geometry_collection_2, geometry_collection_z), + (geometry_collection_z, geometry_collection_z), + ], +) +def test_force_3d(geom, expected): + actual = shapely.force_3d(geom, z=4) + assert shapely.get_coordinate_dimension(actual) == 3 + assert_geometries_equal(actual, expected) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_io.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..f41d61e7efbbc698549158d16d2fef9c9b6fa720 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_io.py @@ -0,0 +1,1351 @@ +import json +import pickle +import struct +import warnings +from contextlib import nullcontext + +import numpy as np +import pytest + +import shapely +from shapely import ( + GeometryCollection, + GEOSException, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + all_types, + all_types_m, + all_types_z, + all_types_zm, + empty_point, + empty_point_m, + empty_point_z, + empty_point_zm, + equal_geometries_abnormally_yield_unequal, + multi_point_empty, + multi_point_empty_m, + multi_point_empty_z, + multi_point_empty_zm, + point, + point_m, + point_z, + point_zm, + polygon_z, +) + +EWKBZ = 0x80000000 +EWKBM = 0x40000000 +EWKBZM = EWKBZ | EWKBM +ISOWKBZ = 1000 +ISOWKBM = 2000 +ISOWKBZM = ISOWKBZ + ISOWKBM +POINT11_WKB = struct.pack("1 elements"), + ("LINESTRING (0 0)", "warn", Warning, "must contain 0 or >1 elements"), + ("NOT A WKT STRING", "ignore", None, None), + ("NOT A WKT STRING", "warn", Warning, "Unknown type: 'NOT'"), + ("POLYGON ((0 0, 0 0))", "ignore", None, None), + ("POLYGON ((0 0, 0 0))", "raise", GEOSException, "Invalid number of points"), + ("POLYGON ((0 0, 0 0))", "warn", Warning, "Invalid number of points"), + ], +) +def test_from_wkt_on_invalid(wkt, on_invalid, error, message): + if on_invalid == "warn": + handler = pytest.warns(error, match=message) + elif on_invalid == "raise": + handler = pytest.raises(error, match=message) + elif on_invalid == "ignore": + handler = nullcontext() + else: + handler = pytest.raises(error, match=message) + + with handler: + result = shapely.from_wkt(wkt, on_invalid=on_invalid) + assert result is None + + +@pytest.mark.skipif( + shapely.geos_version < (3, 11, 0), + reason="on_invalid='fix' not supported with GEOS < 3.11", +) +@pytest.mark.parametrize( + "wkt, expected_wkt", + [ + ("", None), + ("LINESTRING (0 0)", None), + ("NOT A WKT STRING", None), + ("POLYGON ((0 0, 0 0))", None), + ("POLYGON ((0 0, 1 1, 0 1))", "POLYGON ((0 0, 1 1, 0 1, 0 0))"), + ("POLYGON ((0 0, 1 1))", "POLYGON ((0 0, 1 1, 0 0))"), + ("MULTIPOLYGON (((5 5, 6 6, 6 5, 5 5)), ((0 0, 0 0)))", None), + ( + "MULTIPOLYGON (((5 5, 6 6, 6 5, 5 5)), ((0 0, 1 1)))", + "MULTIPOLYGON (((5 5, 6 6, 6 5, 5 5)), ((0 0, 1 1, 0 0)))", + ), + ( + "GEOMETRYCOLLECTION (POLYGON ((5 5, 6 6, 6 5, 5 5)), POLYGON ((0 0, 0 0)))", + None, + ), + ], +) +def test_from_wkt_on_invalid_fix(wkt, expected_wkt): + """Tests for on_invalid="fix". + + Geometries that cannot be fixed are returned as None. + """ + geom = shapely.from_wkt(wkt, on_invalid="fix") + assert shapely.to_wkt(geom) == expected_wkt + + +@pytest.mark.skipif( + shapely.geos_version >= (3, 11, 0), + reason="on_invalid='fix' is supported with GEOS >= 3.11", +) +def test_from_wkt_on_invalid_fix_unsupported_geos(): + """on_invalid="fix" not supported with GEOS < 3.11""" + with pytest.raises( + ValueError, match="on_invalid='fix' only supported for GEOS >= 3.11" + ): + _ = shapely.from_wkt("", on_invalid="fix") + + +@pytest.mark.parametrize("geom", all_types) +def test_from_wkt_all_types(geom): + wkt = shapely.to_wkt(geom) + actual = shapely.from_wkt(wkt) + + if equal_geometries_abnormally_yield_unequal(geom): + # check abnormal test + with pytest.raises(AssertionError): + assert_geometries_equal(actual, geom) + else: + # normal test + assert_geometries_equal(actual, geom) + + +@pytest.mark.parametrize( + "wkt", + ("POINT EMPTY", "LINESTRING EMPTY", "POLYGON EMPTY", "GEOMETRYCOLLECTION EMPTY"), +) +def test_from_wkt_empty(wkt): + geom = shapely.from_wkt(wkt) + assert shapely.is_geometry(geom).all() + assert shapely.is_empty(geom).all() + assert shapely.to_wkt(geom) == wkt + + +# WKT from https://github.com/libgeos/geos/blob/main/tests/unit/io/WKBReaderTest.cpp +@pytest.mark.parametrize( + "wkt", + ( + "CIRCULARSTRING(1 3,2 4,3 1)", + "COMPOUNDCURVE(CIRCULARSTRING(1 3,2 4,3 1),(3 1,0 0))", + "CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0,2 0,2 1,2 3,4 3),(4 3,4 5,1 4,0 0)),CIRCULARSTRING(1.7 1,1.4 0.4,1.6 0.4,1.6 0.5,1.7 1))", # noqa: E501 + "MULTICURVE((0 0,5 5),COMPOUNDCURVE((-1 -1,0 0),CIRCULARSTRING(0 0,1 1,2 0)),CIRCULARSTRING(4 0,4 4,8 4))", # noqa: E501 + "MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0,4 0,4 4,0 4,0 0),(1 1,3 3,3 1,1 1)),((10 10,14 12,11 10,10 10),(11 11,11.5 11,11 11.5,11 11)))", # noqa: E501 + ), +) +def test_from_wkt_nonlinear_unsupported(wkt): + if shapely.geos_version >= (3, 13, 0): + with pytest.raises( + NotImplementedError, + match="Nonlinear geometry types are not currently supported", + ): + shapely.from_wkt(wkt) + + else: + # prior to GEOS 3.13 nonlinear types were rejected by GEOS on read from WKT + with pytest.raises(shapely.errors.GEOSException, match="Unknown type"): + shapely.from_wkt(wkt) + + +def test_from_wkb(): + expected = shapely.points(1, 1) + actual = shapely.from_wkb(POINT11_WKB) + assert_geometries_equal(actual, expected) + + +def test_from_wkb_hex(): + # HEX form + expected = shapely.points(1, 1) + actual = shapely.from_wkb("0101000000000000000000F03F000000000000F03F") + assert_geometries_equal(actual, expected) + actual = shapely.from_wkb(b"0101000000000000000000F03F000000000000F03F") + assert_geometries_equal(actual, expected) + + +def test_from_wkb_none(): + # None propagates + assert shapely.from_wkb(None) is None + + +@pytest.mark.parametrize( + "wkb, on_invalid, error, message", + [ + (1, "raise", TypeError, "Expected bytes or string, got int"), + ("", "ignore", None, None), + ("", "raise", GEOSException, "Unexpected EOF parsing WKB"), + ("", "warn", Warning, "Unexpected EOF parsing WKB"), + ("", "unsupported_option", ValueError, "not a valid option"), + (b"\x01\x01\x00\x00\x00\x00", "ignore", None, None), + (b"\x01\x01\x00\x00\x00\x00", "raise", GEOSException, "ParseException"), + (b"\x01\x01\x00\x00\x00\x00", "warn", Warning, "ParseException"), + (INVALID_WKB, "ignore", None, None), + ( + INVALID_WKB, + "raise", + GEOSException, + "Points of LinearRing do not form a closed linestring", + ), + ( + INVALID_WKB, + "warn", + Warning, + "Points of LinearRing do not form a closed linestring", + ), + ], +) +def test_from_wkb_on_invalid(wkb, on_invalid, error, message): + if on_invalid == "warn": + handler = pytest.warns(error, match=message) + elif on_invalid == "raise": + handler = pytest.raises(error, match=message) + elif on_invalid == "ignore": + handler = nullcontext() + else: + handler = pytest.raises(error, match=message) + + with handler: + result = shapely.from_wkb(wkb, on_invalid=on_invalid) + assert result is None + + +@pytest.mark.skipif( + shapely.geos_version < (3, 11, 0), + reason="on_invalid='fix' not supported with GEOS < 3.11", +) +@pytest.mark.parametrize( + "wkb, expected_wkt", + [ + (b"", None), + (b"\x01\x01\x00\x00\x00\x00", None), + ( + INVALID_WKB, + "POLYGON ((1421568.7761 1924750.2852, 1421564.1314 1924752.2408, 1421568.7761 1924750.2852))", # noqa: E501 + ), + ], +) +def test_from_wkb_on_invalid_fix(wkb, expected_wkt): + """Tests for on_invalid="fix". + + Geometries that cannot be fixed are returned as None. + """ + geom = shapely.from_wkb(wkb, on_invalid="fix") + assert shapely.to_wkt(geom) == expected_wkt + + +@pytest.mark.skipif( + shapely.geos_version >= (3, 11, 0), + reason="on_invalid='fix' is supported with GEOS >= 3.11", +) +def test_from_wkb_on_invalid_fix_unsupported_geos(): + """on_invalid="fix" not supported with GEOS < 3.11""" + with pytest.raises( + ValueError, match="on_invalid='fix' only supported for GEOS >= 3.11" + ): + _ = shapely.from_wkb(b"", on_invalid="fix") + + +@pytest.mark.parametrize("geom", all_types) +@pytest.mark.parametrize("use_hex", [False, True]) +@pytest.mark.parametrize("byte_order", [0, 1]) +def test_from_wkb_all_types(geom, use_hex, byte_order): + if shapely.get_type_id(geom) == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in WKB") + wkb = shapely.to_wkb(geom, hex=use_hex, byte_order=byte_order) + actual = shapely.from_wkb(wkb) + assert_geometries_equal(actual, geom) + + +@pytest.mark.parametrize("geom", all_types_z) +@pytest.mark.parametrize("use_hex", [False, True]) +@pytest.mark.parametrize("byte_order", [0, 1]) +def test_from_wkb_all_types_z(geom, use_hex, byte_order): + if shapely.get_type_id(geom) == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in WKB") + wkb = shapely.to_wkb(geom, hex=use_hex, byte_order=byte_order) + actual = shapely.from_wkb(wkb) + assert_geometries_equal(actual, geom) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geom", all_types_m) +@pytest.mark.parametrize("use_hex", [False, True]) +@pytest.mark.parametrize("byte_order", [0, 1]) +def test_from_wkb_all_types_m(geom, use_hex, byte_order): + if shapely.get_type_id(geom) == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in WKB") + wkb = shapely.to_wkb(geom, hex=use_hex, byte_order=byte_order) + actual = shapely.from_wkb(wkb) + assert_geometries_equal(actual, geom) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geom", all_types_zm) +@pytest.mark.parametrize("use_hex", [False, True]) +@pytest.mark.parametrize("byte_order", [0, 1]) +def test_from_wkb_all_types_zm(geom, use_hex, byte_order): + if shapely.get_type_id(geom) == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in WKB") + wkb = shapely.to_wkb(geom, hex=use_hex, byte_order=byte_order) + actual = shapely.from_wkb(wkb) + assert_geometries_equal(actual, geom) + + +@pytest.mark.parametrize( + "geom", + (Point(), LineString(), Polygon(), GeometryCollection()), +) +def test_from_wkb_empty(geom): + wkb = shapely.to_wkb(geom) + geom = shapely.from_wkb(wkb) + assert shapely.is_geometry(geom).all() + assert shapely.is_empty(geom).all() + assert shapely.to_wkb(geom) == wkb + + +# WKB from https://github.com/libgeos/geos/blob/main/tests/unit/io/WKBReaderTest.cpp +@pytest.mark.parametrize( + "wkb", + ( + # "CIRCULARSTRING(1 3,2 4,3 1)", + "010800000003000000000000000000F03F0000000000000840000000000000004000000000000010400000000000000840000000000000F03F", + # "COMPOUNDCURVE(CIRCULARSTRING(1 3,2 4,3 1),(3 1,0 0))", + "01090000200E16000002000000010800000003000000000000000000F03F0000000000000840000000000000004000000000000010400000000000000840000000000000F03F0102000000020000000000000000000840000000000000F03F00000000000000000000000000000000", + # "CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0,2 0,2 1,2 3,4 3),(4 3,4 5,1 4,0 0)),CIRCULARSTRING(1.7 1,1.4 0.4,1.6 0.4,1.6 0.5,1.7 1))", # noqa: E501 + "010A0000200E1600000200000001090000000200000001080000000500000000000000000000000000000000000000000000000000004000000000000000000000000000000040000000000000F03F00000000000000400000000000000840000000000000104000000000000008400102000000040000000000000000001040000000000000084000000000000010400000000000001440000000000000F03F000000000000104000000000000000000000000000000000010800000005000000333333333333FB3F000000000000F03F666666666666F63F9A9999999999D93F9A9999999999F93F9A9999999999D93F9A9999999999F93F000000000000E03F333333333333FB3F000000000000F03F", + # "MULTICURVE((0 0,5 5),COMPOUNDCURVE((-1 -1,0 0),CIRCULARSTRING(0 0,1 1,2 0)),CIRCULARSTRING(4 0,4 4,8 4))", # noqa: E501 + "010B000000030000000102000000020000000000000000000000000000000000000000000000000014400000000000001440010900000002000000010200000002000000000000000000F0BF000000000000F0BF0000000000000000000000000000000001080000000300000000000000000000000000000000000000000000000000F03F000000000000F03F00000000000000400000000000000000010800000003000000000000000000104000000000000000000000000000001040000000000000104000000000000020400000000000001040", + # "MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0,4 0,4 4,0 4,0 0),(1 1,3 3,3 1,1 1)),((10 10,14 12,11 10,10 10),(11 11,11.5 11,11 11.5,11 11)))", # noqa: E501 + "010C00000002000000010A000000020000000108000000050000000000000000000000000000000000000000000000000010400000000000000000000000000000104000000000000010400000000000000000000000000000104000000000000000000000000000000000010200000004000000000000000000F03F000000000000F03F000000000000084000000000000008400000000000000840000000000000F03F000000000000F03F000000000000F03F01030000000200000004000000000000000000244000000000000024400000000000002C40000000000000284000000000000026400000000000002440000000000000244000000000000024400400000000000000000026400000000000002640000000000000274000000000000026400000000000002640000000000000274000000000000026400000000000002640", + ), +) +def test_from_wkb_nonlinear_unsupported(wkb): + if shapely.geos_version >= (3, 13, 0): + with pytest.raises( + NotImplementedError, + match="Nonlinear geometry types are not currently supported", + ): + shapely.from_wkb(wkb) + + else: + # prior to GEOS 3.13 nonlinear types were rejected by GEOS on read from WKB + with pytest.raises(shapely.errors.GEOSException, match="Unknown WKB type"): + shapely.from_wkb(wkb) + + +def test_to_wkt(): + point = shapely.points(1, 1) + actual = shapely.to_wkt(point) + assert actual == "POINT (1 1)" + + actual = shapely.to_wkt(point, trim=False) + assert actual == "POINT (1.000000 1.000000)" + + actual = shapely.to_wkt(point, rounding_precision=3, trim=False) + assert actual == "POINT (1.000 1.000)" + + +def test_to_wkt_z(): + point = shapely.points(1, 2, 3) + + assert shapely.to_wkt(point) == "POINT Z (1 2 3)" + assert shapely.to_wkt(point, output_dimension=2) == "POINT (1 2)" + assert shapely.to_wkt(point, output_dimension=3) == "POINT Z (1 2 3)" + assert shapely.to_wkt(point, old_3d=True) == "POINT (1 2 3)" + + if shapely.geos_version >= (3, 12, 0): + assert shapely.to_wkt(point, output_dimension=4) == "POINT Z (1 2 3)" + + +def test_to_wkt_m(): + point = shapely.from_wkt("POINT M (1 2 4)") + + assert shapely.to_wkt(point, output_dimension=2) == "POINT (1 2)" + + if shapely.geos_version < (3, 12, 0): + # previous behavior was to incorrectly parse M as Z + assert shapely.to_wkt(point) == "POINT Z (1 2 4)" + assert shapely.to_wkt(point, output_dimension=3) == "POINT Z (1 2 4)" + assert shapely.to_wkt(point, old_3d=True) == "POINT (1 2 4)" + else: + assert shapely.to_wkt(point) == "POINT M (1 2 4)" + assert shapely.to_wkt(point, output_dimension=3) == "POINT M (1 2 4)" + assert shapely.to_wkt(point, output_dimension=4) == "POINT M (1 2 4)" + assert shapely.to_wkt(point, old_3d=True) == "POINT M (1 2 4)" + + +def test_to_wkt_zm(): + point = shapely.from_wkt("POINT ZM (1 2 3 4)") + + assert shapely.to_wkt(point, output_dimension=2) == "POINT (1 2)" + assert shapely.to_wkt(point, output_dimension=3) == "POINT Z (1 2 3)" + + if shapely.geos_version < (3, 12, 0): + # previous behavior was to parse and ignore M + assert shapely.to_wkt(point) == "POINT Z (1 2 3)" + assert shapely.to_wkt(point, old_3d=True) == "POINT (1 2 3)" + else: + assert shapely.to_wkt(point) == "POINT ZM (1 2 3 4)" + assert shapely.to_wkt(point, output_dimension=4) == "POINT ZM (1 2 3 4)" + assert shapely.to_wkt(point, old_3d=True) == "POINT (1 2 3 4)" + + +def test_to_wkt_none(): + # None propagates + assert shapely.to_wkt(None) is None + + +def test_to_wkt_array_with_empty_z(): + # See GH-2004 + empty_wkt = ["POINT Z EMPTY", None, "POLYGON Z EMPTY"] + empty_geoms = shapely.from_wkt(empty_wkt) + assert list(shapely.to_wkt(empty_geoms)) == empty_wkt + + +def test_to_wkt_exceptions(): + with pytest.raises(TypeError): + shapely.to_wkt(1) + + with pytest.raises(shapely.GEOSException): + shapely.to_wkt(point, output_dimension=5) + + +def test_to_wkt_point_empty(): + assert shapely.to_wkt(empty_point) == "POINT EMPTY" + + +@pytest.mark.parametrize( + "wkt", + [ + "POINT Z EMPTY", + "LINESTRING Z EMPTY", + "LINEARRING Z EMPTY", + "POLYGON Z EMPTY", + ], +) +def test_to_wkt_empty_z(wkt): + assert shapely.to_wkt(shapely.from_wkt(wkt)) == wkt + + +def test_to_wkt_geometrycollection_with_point_empty(): + collection = shapely.geometrycollections([empty_point, point]) + # do not check the full value as some GEOS versions give + # GEOMETRYCOLLECTION Z (...) and others give GEOMETRYCOLLECTION (...) + assert shapely.to_wkt(collection).endswith("(POINT EMPTY, POINT (2 3))") + + +def test_to_wkt_multipoint_with_point_empty(): + geom = shapely.multipoints([empty_point, point]) + if shapely.geos_version >= (3, 12, 0): + expected = "MULTIPOINT (EMPTY, (2 3))" + else: + # invalid WKT form + expected = "MULTIPOINT (EMPTY, 2 3)" + assert shapely.to_wkt(geom) == expected + + +@pytest.mark.parametrize("geom", [Point(1e100, 0), Point(0, 1e100)]) +def test_to_wkt_large_float_ok(geom): + # https://github.com/shapely/shapely/issues/1903 + shapely.to_wkt(geom) + assert "Exception in WKT writer" not in repr(geom) + + +@pytest.mark.parametrize("geom", [Point(1e101, 0), Point(0, 1e101)]) +def test_to_wkt_large_float(geom): + if shapely.geos_version >= (3, 13, 0): + # round-trip WKT + assert geom.equals(shapely.from_wkt(shapely.to_wkt(geom))) + else: + # https://github.com/shapely/shapely/issues/1903 + with pytest.raises( + ValueError, match="WKT output of coordinates greater than.*" + ): + shapely.to_wkt(geom) + assert "Exception in WKT writer" in repr(geom) + + +@pytest.mark.parametrize( + "geom", + [ + # We implemented our own "GetZMax", so go through all geometry types: + Point(0, 0, 1e101), + LineString([(0, 0, 0), (0, 0, 1e101)]), + LinearRing([(0, 0, 0), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)]), + Polygon([(0, 0, 0), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)]), + Polygon( + [(0, 0, 0), (0, 10, 0), (10, 0, 0), (0, 0, 0)], + [[(0, 0, 0), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)]], + ), + MultiPoint([(0, 0, 0), (0, 0, 1e101)]), + MultiLineString( + [LineString([(0, 0, 0), (0, 1, 0)]), LineString([(0, 0, 0), (0, 1, 1e101)])] + ), + MultiPolygon( + [polygon_z, Polygon([(0, 0, 0), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)])] + ), + GeometryCollection([point_z, Point(0, 0, 1e101)]), + GeometryCollection([GeometryCollection([Point(0, 0, 1e101)])]), + LineString([(0, 0, np.nan), (0, 0, 1e101)]), + Polygon([(0, 0, np.nan), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)]), + GeometryCollection([Point(0, 0), Point(0, 0, 1e101)]), + ], +) +def test_to_wkt_large_float_3d_no_crash(geom): + # https://github.com/shapely/shapely/issues/1903 + # just test if there is a crash (detailed behaviour differs per GEOS version) + try: + shapely.to_wkt(geom) + except ValueError as e: + assert str(e).startswith("WKT output of coordinates greater than") + repr(geom) + + +def test_to_wkt_large_float_skip_z(): + # https://github.com/shapely/shapely/issues/1903 + assert shapely.to_wkt(Point(0, 0, 1e101), output_dimension=2) == "POINT (0 0)" + + +def test_to_wkt_large_float_no_trim(): + # https://github.com/shapely/shapely/issues/1903 + # don't test the exact number, it is ridiculously large and probably platform + # dependent + assert shapely.to_wkt(Point(1e101, 0), trim=False).startswith("POINT (") + + +def test_repr(): + assert repr(point) == "" + assert repr(point_z) == "" + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +def test_repr_m(): + assert repr(point_m) == "" + assert repr(point_zm) == "" + + +def test_repr_max_length(): + # the repr is limited to 80 characters + geom = shapely.linestrings(np.arange(1000), np.arange(1000)) + representation = repr(geom) + assert len(representation) == 80 + assert representation.endswith("...>") + + +def test_repr_point_z_empty(): + assert repr(empty_point_z) == "" + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +def test_repr_point_m_empty(): + assert repr(empty_point_m) == "" + assert repr(empty_point_zm) == "" + + +def test_to_wkb(): + point = shapely.points(1, 1) + actual = shapely.to_wkb(point, byte_order=1) + assert actual == POINT11_WKB + + +def test_to_wkb_hex(): + point = shapely.points(1, 1) + actual = shapely.to_wkb(point, hex=True, byte_order=1) + le = "01" + point_type = "01000000" + coord = "000000000000F03F" # 1.0 as double (LE) + assert actual == le + point_type + 2 * coord + + +def test_to_wkb_z(): + point = shapely.points(1, 2, 3) + + expected_wkb = struct.pack("= (3, 12, 0): + assert shapely.to_wkb(point, output_dimension=4, byte_order=1) == expected_wkb_z + + +def test_to_wkb_m(): + # POINT M (1 2 4) + point = shapely.from_wkb(struct.pack("= (3, 12, 0): + assert shapely.to_wkb(point, output_dimension=4, byte_order=1) == expected_wkb_m + + +def test_to_wkb_zm(): + # POINT ZM (1 2 3 4) + point = shapely.from_wkb(struct.pack("= (3, 12, 0): + assert ( + shapely.to_wkb(point, output_dimension=4, byte_order=1) == expected_wkb_zm + ) + + +def test_to_wkb_none(): + # None propagates + assert shapely.to_wkb(None) is None + + +def test_to_wkb_exceptions(): + with pytest.raises(TypeError): + shapely.to_wkb(1) + + with pytest.raises(shapely.GEOSException): + shapely.to_wkb(point, output_dimension=5) + + with pytest.raises(ValueError): + shapely.to_wkb(point, flavor="other") + + +def test_to_wkb_byte_order(): + point = shapely.points(1.0, 1.0) + be = b"\x00" + le = b"\x01" + point_type = b"\x01\x00\x00\x00" # 1 as 32-bit uint (LE) + coord = b"\x00\x00\x00\x00\x00\x00\xf0?" # 1.0 as double (LE) + + assert shapely.to_wkb(point, byte_order=1) == le + point_type + 2 * coord + assert ( + shapely.to_wkb(point, byte_order=0) == be + point_type[::-1] + 2 * coord[::-1] + ) + + +def test_to_wkb_srid(): + # hex representation of POINT (0 0) with SRID=4 + ewkb = "01010000200400000000000000000000000000000000000000" + wkb = "010100000000000000000000000000000000000000" + + actual = shapely.from_wkb(ewkb) + assert shapely.to_wkt(actual, trim=True) == "POINT (0 0)" + + assert shapely.to_wkb(actual, hex=True, byte_order=1) == wkb + assert shapely.to_wkb(actual, hex=True, include_srid=True, byte_order=1) == ewkb + + point = shapely.points(1, 1) + point_with_srid = shapely.set_srid(point, np.int32(4326)) + result = shapely.to_wkb(point_with_srid, include_srid=True, byte_order=1) + assert np.frombuffer(result[5:9], "= (3, 10, 0), reason="GEOS < 3.10.0") +def test_to_wkb_flavor_unsupported_geos(): + with pytest.raises(UnsupportedGEOSVersionError): + shapely.to_wkb(point_z, flavor="iso") + + +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point, POINT_NAN_WKB, id="POINT EMPTY"), + pytest.param(empty_point_z, POINT_NAN_WKB, id="POINT Z EMPTY"), + pytest.param(empty_point_m, POINT_NAN_WKB, id="POINT M EMPTY"), + pytest.param(empty_point_zm, POINT_NAN_WKB, id="POINT ZM EMPTY"), + pytest.param( + multi_point_empty, + MULTIPOINT_NAN_WKB, + id="MULTIPOINT EMPTY", + ), + pytest.param( + multi_point_empty_z, + MULTIPOINT_NAN_WKB, + id="MULTIPOINT Z EMPTY", + ), + pytest.param( + multi_point_empty_m, + MULTIPOINT_NAN_WKB, + id="MULTIPOINT M EMPTY", + ), + pytest.param( + multi_point_empty_zm, + MULTIPOINT_NAN_WKB, + id="MULTIPOINT ZM EMPTY", + ), + pytest.param( + shapely.geometrycollections([empty_point]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT EMPTY)", + ), + pytest.param( + shapely.geometrycollections([empty_point_z]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT Z EMPTY)", + ), + pytest.param( + shapely.geometrycollections([empty_point_m]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT M EMPTY)", + ), + pytest.param( + shapely.geometrycollections([empty_point_zm]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT ZM EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_z]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT Z EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_m]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT M EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_zm]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT ZM EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_2d(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=2, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 16 + header_length = len(expected) - coordinate_length + # Check the total length (this checks the correct dimensionality) + assert len(actual) == header_length + coordinate_length + # Check the header + assert actual[:header_length] == expected[:header_length] + # Check the coordinates (using numpy.isnan; there are many byte representations for + # NaN) + assert np.isnan(struct.unpack("<2d", actual[header_length:])).all() + + +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point_z, POINTZ_NAN_WKB, id="POINT Z EMPTY"), + pytest.param(empty_point_zm, POINTZ_NAN_WKB, id="POINT ZM EMPTY"), + pytest.param( + multi_point_empty_z, + MULTIPOINTZ_NAN_WKB, + id="MULTIPOINT Z EMPTY", + ), + pytest.param( + multi_point_empty_zm, + MULTIPOINTZ_NAN_WKB, + id="MULTIPOINT ZM EMPTY", + ), + pytest.param( + shapely.geometrycollections([empty_point_z]), + GEOMETRYCOLLECTIONZ_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT Z EMPTY)", + ), + pytest.param( + shapely.geometrycollections([empty_point_zm]), + GEOMETRYCOLLECTIONZ_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT ZM EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_z]), + NESTED_COLLECTIONZ_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT Z EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_zm]), + NESTED_COLLECTIONZ_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT ZM EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_z(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=3, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 8 * 3 + header_length = len(expected) - coordinate_length + # Check the total length (this checks the correct dimensionality) + assert len(actual) == header_length + coordinate_length + # Check the header + assert actual[:header_length] == expected[:header_length] + # Check the coordinates (using numpy.isnan; there are many byte representations for + # NaN) + assert np.isnan(struct.unpack("<3d", actual[header_length:])).all() + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point_m, POINTM_NAN_WKB, id="POINT M EMPTY"), + pytest.param( + multi_point_empty_m, + MULTIPOINTM_NAN_WKB, + id="MULTIPOINT M EMPTY", + ), + pytest.param( + shapely.geometrycollections([empty_point_m]), + GEOMETRYCOLLECTIONM_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT M EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_m]), + NESTED_COLLECTIONM_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT M EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_m(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=3, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 8 * 3 + header_length = len(expected) - coordinate_length + assert len(actual) == header_length + coordinate_length + assert actual[:header_length] == expected[:header_length] + assert np.isnan(struct.unpack("<3d", actual[header_length:])).all() + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point_zm, POINTZM_NAN_WKB, id="POINT ZM EMPTY"), + pytest.param( + multi_point_empty_zm, + MULTIPOINTZM_NAN_WKB, + id="MULTIPOINT ZM EMPTY", + ), + pytest.param( + shapely.geometrycollections([empty_point_zm]), + GEOMETRYCOLLECTIONZM_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT ZM EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_zm]), + NESTED_COLLECTIONZM_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT ZM EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_zm(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=4, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 8 * 4 + header_length = len(expected) - coordinate_length + assert len(actual) == header_length + coordinate_length + assert actual[:header_length] == expected[:header_length] + assert np.isnan(struct.unpack("<4d", actual[header_length:])).all() + + +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point, POINT_NAN_WKB, id="POINT EMPTY"), + pytest.param(multi_point_empty, MULTIPOINT_NAN_WKB, id="MULTIPOINT EMPTY"), + pytest.param( + shapely.geometrycollections([empty_point]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_2d_output_dim_3(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=3, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 16 + header_length = len(expected) - coordinate_length + # Check the total length (this checks the correct dimensionality) + assert len(actual) == header_length + coordinate_length + # Check the header + assert actual[:header_length] == expected[:header_length] + # Check the coordinates (using numpy.isnan; there are many byte representations for + # NaN) + assert np.isnan(struct.unpack("<2d", actual[header_length:])).all() + + +@pytest.mark.parametrize( + "wkb,expected_type,expected_dim", + [ + pytest.param(POINT_NAN_WKB, 0, 2, id="POINT_NAN_WKB"), + pytest.param(POINTZ_NAN_WKB, 0, 3, id="POINTZ_NAN_WKB"), + pytest.param(MULTIPOINT_NAN_WKB, 4, 2, id="MULTIPOINT_NAN_WKB"), + pytest.param(MULTIPOINTZ_NAN_WKB, 4, 3, id="MULTIPOINTZ_NAN_WKB"), + pytest.param(GEOMETRYCOLLECTION_NAN_WKB, 7, 2, id="GEOMETRYCOLLECTION_NAN_WKB"), + pytest.param( + GEOMETRYCOLLECTIONZ_NAN_WKB, 7, 3, id="GEOMETRYCOLLECTIONZ_NAN_WKB" + ), + pytest.param(NESTED_COLLECTION_NAN_WKB, 7, 2, id="NESTED_COLLECTION_NAN_WKB"), + pytest.param(NESTED_COLLECTIONZ_NAN_WKB, 7, 3, id="NESTED_COLLECTIONZ_NAN_WKB"), + ], +) +def test_from_wkb_point_empty(wkb, expected_type, expected_dim): + geom = shapely.from_wkb(wkb) + # POINT (nan nan) transforms to an empty point + assert shapely.is_empty(geom) + assert shapely.get_type_id(geom) == expected_type + assert shapely.get_coordinate_dimension(geom) == expected_dim + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize( + "wkb,expected_type", + [ + pytest.param(POINTM_NAN_WKB, 0, id="POINTM_NAN_WKB"), + pytest.param(MULTIPOINTM_NAN_WKB, 4, id="MULTIPOINTM_NAN_WKB"), + pytest.param(GEOMETRYCOLLECTIONM_NAN_WKB, 7, id="GEOMETRYCOLLECTIONM_NAN_WKB"), + pytest.param(NESTED_COLLECTIONM_NAN_WKB, 7, id="NESTED_COLLECTIONM_NAN_WKB"), + ], +) +def test_from_wkb_point_empty_m(wkb, expected_type): + geom = shapely.from_wkb(wkb) + + assert shapely.is_empty(geom) + assert shapely.get_type_id(geom) == expected_type + assert shapely.get_coordinate_dimension(geom) == 3 + assert not shapely.has_z(geom) + assert shapely.has_m(geom) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize( + "wkb,expected_type", + [ + pytest.param(POINTZM_NAN_WKB, 0, id="POINTZM_NAN_WKB"), + pytest.param(MULTIPOINTZM_NAN_WKB, 4, id="MULTIPOINTZM_NAN_WKB"), + pytest.param( + GEOMETRYCOLLECTIONZM_NAN_WKB, 7, id="GEOMETRYCOLLECTIONZM_NAN_WKB" + ), + pytest.param(NESTED_COLLECTIONZM_NAN_WKB, 7, id="NESTED_COLLECTIONZM_NAN_WKB"), + ], +) +def test_from_wkb_point_empty_zm(wkb, expected_type): + geom = shapely.from_wkb(wkb) + + assert shapely.is_empty(geom) + assert shapely.get_type_id(geom) == expected_type + assert shapely.get_coordinate_dimension(geom) == 4 + assert shapely.has_z(geom) + assert shapely.has_m(geom) + + +def test_to_wkb_point_empty_srid(): + expected = shapely.set_srid(empty_point, 4236) + wkb = shapely.to_wkb(expected, include_srid=True) + actual = shapely.from_wkb(wkb) + assert shapely.get_srid(actual) == 4236 + + +@pytest.mark.parametrize("geom", all_types + (point_z, empty_point)) +def test_pickle(geom): + pickled = pickle.dumps(geom) + assert_geometries_equal(pickle.loads(pickled), geom, tolerance=0) + + +@pytest.mark.parametrize("geom", all_types_z) +def test_pickle_z(geom): + pickled = pickle.dumps(geom) + actual = pickle.loads(pickled) + assert_geometries_equal(actual, geom, tolerance=0) + if not actual.is_empty: # GEOSHasZ with EMPTY geometries is inconsistent + assert actual.has_z + if shapely.geos_version >= (3, 12, 0): + assert not actual.has_m + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geom", all_types_m) +def test_pickle_m(geom): + pickled = pickle.dumps(geom) + actual = pickle.loads(pickled) + assert_geometries_equal(actual, geom, tolerance=0) + assert not actual.has_z + if not actual.is_empty: # GEOSHasM with EMPTY geometries is inconsistent + assert actual.has_m + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geom", all_types_zm) +def test_pickle_zm(geom): + pickled = pickle.dumps(geom) + actual = pickle.loads(pickled) + assert_geometries_equal(actual, geom, tolerance=0) + if not actual.is_empty: # GEOSHasZ with EMPTY geometries is inconsistent + assert actual.has_z + assert actual.has_m + + +@pytest.mark.parametrize("geom", all_types + (point_z, empty_point)) +def test_pickle_with_srid(geom): + geom = shapely.set_srid(geom, 4326) + pickled = pickle.dumps(geom) + assert shapely.get_srid(pickle.loads(pickled)) == 4326 + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +@pytest.mark.parametrize( + "geojson,expected", + [ + pytest.param( + GEOJSON_GEOMETRY, GEOJSON_GEOMETRY_EXPECTED, id="GEOJSON_GEOMETRY" + ), + pytest.param(GEOJSON_FEATURE, GEOJSON_GEOMETRY_EXPECTED, id="GEOJSON_FEATURE"), + pytest.param( + GEOJSON_FEATURECOLECTION, + shapely.geometrycollections(GEOJSON_COLLECTION_EXPECTED), + id="GEOJSON_FEATURECOLECTION", + ), + pytest.param( + [GEOJSON_GEOMETRY] * 2, + [GEOJSON_GEOMETRY_EXPECTED] * 2, + id="GEOJSON_GEOMETRYx2", + ), + pytest.param(None, None, id="None"), + pytest.param( + [GEOJSON_GEOMETRY, None], + [GEOJSON_GEOMETRY_EXPECTED, None], + id="GEOJSON_GEOMETRY_None", + ), + ], +) +def test_from_geojson(geojson, expected): + actual = shapely.from_geojson(geojson) + assert_geometries_equal(actual, expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +def test_from_geojson_exceptions(): + with pytest.raises(TypeError, match="Expected bytes or string, got int"): + shapely.from_geojson(1) + + with pytest.raises(shapely.GEOSException, match="Error parsing JSON"): + shapely.from_geojson("") + + with pytest.raises(shapely.GEOSException, match="Unknown geometry type"): + shapely.from_geojson('{"type": "NoGeometry", "coordinates": []}') + + with pytest.raises(shapely.GEOSException, match="type must be array, but is null"): + shapely.from_geojson('{"type": "LineString", "coordinates": null}') + + # Note: The two below tests are the reason that from_geojson is disabled for + # GEOS 3.10.0 See https://trac.osgeo.org/geos/ticket/1138 + with pytest.raises(shapely.GEOSException, match="key 'type' not found"): + shapely.from_geojson('{"geometry": null, "properties": []}') + + with pytest.raises(shapely.GEOSException, match="key 'type' not found"): + shapely.from_geojson('{"no": "geojson"}') + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +def test_from_geojson_warn_on_invalid(): + with pytest.warns(Warning, match="Invalid GeoJSON"): + assert shapely.from_geojson("", on_invalid="warn") is None + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +def test_from_geojson_ignore_on_invalid(): + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert shapely.from_geojson("", on_invalid="ignore") is None + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +def test_from_geojson_on_invalid_unsupported_option(): + with pytest.raises(ValueError, match="not a valid option"): + shapely.from_geojson(GEOJSON_GEOMETRY, on_invalid="unsupported_option") + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "expected,geometry", + [ + pytest.param( + GEOJSON_GEOMETRY, GEOJSON_GEOMETRY_EXPECTED, id="GEOJSON_GEOMETRY" + ), + pytest.param( + [GEOJSON_GEOMETRY] * 2, + [GEOJSON_GEOMETRY_EXPECTED] * 2, + id="GEOJSON_GEOMETRYx2", + ), + pytest.param(None, None, id="None"), + pytest.param( + [GEOJSON_GEOMETRY, None], + [GEOJSON_GEOMETRY_EXPECTED, None], + id="GEOJSON_GEOMETRY_None", + ), + ], +) +def test_to_geojson(geometry, expected): + actual = shapely.to_geojson(geometry, indent=4) + assert np.all(actual == np.asarray(expected)) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize("indent", [None, 0, 4]) +def test_to_geojson_indent(indent): + separators = (",", ":") if indent is None else (",", ": ") + expected = json.dumps( + json.loads(GEOJSON_GEOMETRY), indent=indent, separators=separators + ) + actual = shapely.to_geojson(GEOJSON_GEOMETRY_EXPECTED, indent=indent) + assert actual == expected + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_to_geojson_exceptions(): + with pytest.raises(TypeError): + shapely.to_geojson(1) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 2), reason="GEOS < 3.10.2") +@pytest.mark.parametrize( + "geom", + [ + empty_point, + shapely.multipoints([empty_point, point]), + shapely.geometrycollections([empty_point, point]), + shapely.geometrycollections( + [shapely.geometrycollections([empty_point]), point] + ), + ], +) +def test_to_geojson_point_empty(geom): + assert geom.equals(shapely.from_geojson(shapely.to_geojson(geom))) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +@pytest.mark.parametrize("geom", all_types) +def test_geojson_all_types(geom): + type_id = shapely.get_type_id(geom) + if type_id == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in GeoJSON") + elif ( + geom.is_empty + and type_id == shapely.GeometryType.POINT + and shapely.geos_version < (3, 10, 2) + ): + pytest.skip("GEOS < 3.10.2 with POINT EMPTY") # TRAC-1139 + geojson = shapely.to_geojson(geom) + actual = shapely.from_geojson(geojson) + assert not actual.has_z + geoms_are_empty = shapely.is_empty([geom, actual]) + if geoms_are_empty.any(): + # Ensure both are EMPTY + assert geoms_are_empty.all() + else: + assert_geometries_equal(actual, geom) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_linear.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a5d13c894123d6ac9dcf07867613dded7a6b89 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_linear.py @@ -0,0 +1,224 @@ +import numpy as np +import pytest + +import shapely +from shapely import GeometryCollection, LinearRing, LineString, MultiLineString, Point +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + empty_line_string, + empty_point, + line_string, + linear_ring, + multi_line_string, + multi_point, + multi_polygon, + point, + polygon, +) + + +def test_line_interpolate_point_geom_array(): + actual = shapely.line_interpolate_point( + [line_string, linear_ring, multi_line_string], -1 + ) + assert_geometries_equal(actual[0], Point(1, 0)) + assert_geometries_equal(actual[1], Point(0, 1)) + assert_geometries_equal(actual[2], Point(0.5528, 1.1056), tolerance=0.001) + + +def test_line_interpolate_point_geom_array_normalized(): + actual = shapely.line_interpolate_point( + [line_string, linear_ring, multi_line_string], 1, normalized=True + ) + assert_geometries_equal(actual[0], Point(1, 1)) + assert_geometries_equal(actual[1], Point(0, 0)) + assert_geometries_equal(actual[2], Point(1, 2)) + + +def test_line_interpolate_point_float_array(): + actual = shapely.line_interpolate_point(line_string, [0.2, 1.5, -0.2]) + assert_geometries_equal(actual[0], Point(0.2, 0)) + assert_geometries_equal(actual[1], Point(1, 0.5)) + assert_geometries_equal(actual[2], Point(1, 0.8)) + + +@pytest.mark.parametrize("normalized", [False, True]) +@pytest.mark.parametrize( + "geom", + [ + LineString(), + LinearRing(), + MultiLineString(), + shapely.from_wkt("MULTILINESTRING (EMPTY, (0 0, 1 1))"), + GeometryCollection(), + GeometryCollection([LineString(), Point(1, 1)]), + ], +) +def test_line_interpolate_point_empty(geom, normalized): + assert_geometries_equal( + shapely.line_interpolate_point(geom, 0.2, normalized=normalized), empty_point + ) + + +@pytest.mark.parametrize("normalized", [False, True]) +@pytest.mark.parametrize( + "geom", + [ + empty_point, + point, + polygon, + multi_point, + multi_polygon, + shapely.geometrycollections([point]), + shapely.geometrycollections([polygon]), + shapely.geometrycollections([multi_line_string]), + shapely.geometrycollections([multi_point]), + shapely.geometrycollections([multi_polygon]), + ], +) +def test_line_interpolate_point_invalid_type(geom, normalized): + with pytest.raises(TypeError): + assert shapely.line_interpolate_point(geom, 0.2, normalized=normalized) + + +def test_line_interpolate_point_none(): + assert shapely.line_interpolate_point(None, 0.2) is None + + +def test_line_interpolate_point_nan(): + assert shapely.line_interpolate_point(line_string, np.nan) is None + + +def test_line_interpolate_point_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `normalized` for `line_interpolate_point` " + "is deprecated" + ): + shapely.line_interpolate_point(line_string, 0, False) + + +def test_line_locate_point_geom_array(): + point = shapely.points(0, 1) + actual = shapely.line_locate_point([line_string, linear_ring], point) + np.testing.assert_allclose(actual, [0.0, 3.0]) + + +def test_line_locate_point_geom_array2(): + points = shapely.points([[0, 0], [1, 0]]) + actual = shapely.line_locate_point(line_string, points) + np.testing.assert_allclose(actual, [0.0, 1.0]) + + +@pytest.mark.parametrize("normalized", [False, True]) +def test_line_locate_point_none(normalized): + assert np.isnan(shapely.line_locate_point(line_string, None, normalized=normalized)) + assert np.isnan(shapely.line_locate_point(None, point, normalized=normalized)) + + +@pytest.mark.parametrize("normalized", [False, True]) +def test_line_locate_point_empty(normalized): + assert np.isnan( + shapely.line_locate_point(line_string, empty_point, normalized=normalized) + ) + assert np.isnan( + shapely.line_locate_point(empty_line_string, point, normalized=normalized) + ) + + +@pytest.mark.parametrize("normalized", [False, True]) +def test_line_locate_point_invalid_geometry(normalized): + with pytest.raises(shapely.GEOSException): + shapely.line_locate_point(line_string, line_string, normalized=normalized) + + with pytest.raises(shapely.GEOSException): + shapely.line_locate_point(polygon, point, normalized=normalized) + + +def test_line_locate_point_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `normalized` for `line_locate_point` is deprecated" + ): + shapely.line_locate_point(line_string, point, False) + + +def test_line_merge_geom_array(): + actual = shapely.line_merge([line_string, multi_line_string]) + assert_geometries_equal(actual[0], line_string) + assert_geometries_equal(actual[1], LineString([(0, 0), (1, 2)])) + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11.0") +def test_line_merge_directed(): + lines = MultiLineString([[(0, 0), (1, 0)], [(0, 0), (3, 0)]]) + # Merge lines without directed, this requires changing the vertex ordering + result = shapely.line_merge(lines) + assert_geometries_equal(result, LineString([(1, 0), (0, 0), (3, 0)])) + # Since the lines can't be merged when directed is specified + # the original geometry is returned + result = shapely.line_merge(lines, directed=True) + assert_geometries_equal(result, lines) + + +@pytest.mark.skipif(shapely.geos_version >= (3, 11, 0), reason="GEOS >= 3.11.0") +def test_line_merge_error(): + lines = MultiLineString([[(0, 0), (1, 0)], [(0, 0), (3, 0)]]) + with pytest.raises(UnsupportedGEOSVersionError): + shapely.line_merge(lines, directed=True) + + +def test_shared_paths_linestring(): + g1 = shapely.linestrings([(0, 0), (1, 0), (1, 1)]) + g2 = shapely.linestrings([(0, 0), (1, 0)]) + actual1 = shapely.shared_paths(g1, g2) + assert_geometries_equal( + shapely.get_geometry(actual1, 0), shapely.multilinestrings([g2]) + ) + + +def test_shared_paths_none(): + assert shapely.shared_paths(line_string, None) is None + assert shapely.shared_paths(None, line_string) is None + assert shapely.shared_paths(None, None) is None + + +def test_shared_paths_non_linestring(): + g1 = shapely.linestrings([(0, 0), (1, 0), (1, 1)]) + g2 = shapely.points(0, 1) + with pytest.raises(shapely.GEOSException): + shapely.shared_paths(g1, g2) + + +def _prepare_input(geometry, prepare): + """Prepare without modifying in-place""" + if prepare: + geometry = shapely.transform(geometry, lambda x: x) # makes a copy + shapely.prepare(geometry) + return geometry + else: + return geometry + + +@pytest.mark.parametrize("prepare", [True, False]) +def test_shortest_line(prepare): + g1 = shapely.linestrings([(0, 0), (1, 0), (1, 1)]) + g2 = shapely.linestrings([(0, 3), (3, 0)]) + actual = shapely.shortest_line(_prepare_input(g1, prepare), g2) + expected = shapely.linestrings([(1, 1), (1.5, 1.5)]) + assert shapely.equals(actual, expected) + + +@pytest.mark.parametrize("prepare", [True, False]) +def test_shortest_line_none(prepare): + assert shapely.shortest_line(_prepare_input(line_string, prepare), None) is None + assert shapely.shortest_line(None, line_string) is None + assert shapely.shortest_line(None, None) is None + + +@pytest.mark.parametrize("prepare", [True, False]) +def test_shortest_line_empty(prepare): + g1 = _prepare_input(line_string, prepare) + assert shapely.shortest_line(g1, empty_line_string) is None + g1_empty = _prepare_input(empty_line_string, prepare) + assert shapely.shortest_line(g1_empty, line_string) is None + assert shapely.shortest_line(g1_empty, empty_line_string) is None diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_measurement.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_measurement.py new file mode 100644 index 0000000000000000000000000000000000000000..2edfbed8fe12c239dd9e22b26e7561b5ecd5ceab --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_measurement.py @@ -0,0 +1,344 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal + +import shapely +from shapely import GeometryCollection, LineString, MultiPoint, Point, Polygon +from shapely.tests.common import ( + empty, + geometry_collection, + ignore_invalid, + line_string, + linear_ring, + multi_line_string, + multi_point, + multi_polygon, + point, + point_polygon_testdata, + polygon, + polygon_with_hole, +) + + +@pytest.mark.parametrize( + "geom", + [ + point, + line_string, + linear_ring, + multi_point, + multi_line_string, + geometry_collection, + ], +) +def test_area_non_polygon(geom): + assert shapely.area(geom) == 0.0 + + +def test_area(): + actual = shapely.area([polygon, polygon_with_hole, multi_polygon]) + assert actual.tolist() == [4.0, 96.0, 1.01] + + +def test_distance(): + actual = shapely.distance(*point_polygon_testdata) + expected = [2 * 2**0.5, 2**0.5, 0, 0, 0, 2**0.5] + np.testing.assert_allclose(actual, expected) + + +def test_distance_missing(): + actual = shapely.distance(point, None) + assert np.isnan(actual) + + +def test_distance_duplicated(): + a = Point(1, 2) + b = LineString([(0, 0), (0, 0), (1, 1)]) + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # https://github.com/shapely/shapely/issues/1552 + # GEOS < 3.12 raises "invalid" floating point errors + actual = shapely.distance(a, b) + assert actual == 1.0 + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, [2, 3, 2, 3]), + ([point, multi_point], [[2, 3, 2, 3], [0, 0, 1, 2]]), + (shapely.linestrings([[0, 0], [0, 1]]), [0, 0, 0, 1]), + (shapely.linestrings([[0, 0], [1, 0]]), [0, 0, 1, 0]), + (multi_point, [0, 0, 1, 2]), + (multi_polygon, [0, 0, 2.2, 2.2]), + (geometry_collection, [49, -1, 52, 2]), + (empty, [np.nan, np.nan, np.nan, np.nan]), + (None, [np.nan, np.nan, np.nan, np.nan]), + ], +) +def test_bounds(geom, expected): + assert_array_equal(shapely.bounds(geom), expected) + + +@pytest.mark.parametrize( + "geom,shape", + [ + (point, (4,)), + (None, (4,)), + ([point, multi_point], (2, 4)), + ([[point, multi_point], [polygon, point]], (2, 2, 4)), + ([[[point, multi_point]], [[polygon, point]]], (2, 1, 2, 4)), + ], +) +def test_bounds_dimensions(geom, shape): + assert shapely.bounds(geom).shape == shape + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, [2, 3, 2, 3]), + (shapely.linestrings([[0, 0], [0, 1]]), [0, 0, 0, 1]), + (shapely.linestrings([[0, 0], [1, 0]]), [0, 0, 1, 0]), + (multi_point, [0, 0, 1, 2]), + (multi_polygon, [0, 0, 2.2, 2.2]), + (geometry_collection, [49, -1, 52, 2]), + (empty, [np.nan, np.nan, np.nan, np.nan]), + (None, [np.nan, np.nan, np.nan, np.nan]), + ([empty, empty, None], [np.nan, np.nan, np.nan, np.nan]), + # mixed missing and non-missing coordinates + ([point, None], [2, 3, 2, 3]), + ([point, empty], [2, 3, 2, 3]), + ([point, empty, None], [2, 3, 2, 3]), + ([point, empty, None, multi_point], [0, 0, 2, 3]), + ], +) +def test_total_bounds(geom, expected): + assert_array_equal(shapely.total_bounds(geom), expected) + + +@pytest.mark.parametrize( + "geom", + [ + point, + None, + [point, multi_point], + [[point, multi_point], [polygon, point]], + [[[point, multi_point]], [[polygon, point]]], + ], +) +def test_total_bounds_dimensions(geom): + assert shapely.total_bounds(geom).shape == (4,) + + +def test_length(): + actual = shapely.length( + [ + point, + line_string, + linear_ring, + polygon, + polygon_with_hole, + multi_point, + multi_polygon, + ] + ) + assert actual.tolist() == [0.0, 2.0, 4.0, 8.0, 48.0, 0.0, 4.4] + + +def test_length_missing(): + actual = shapely.length(None) + assert np.isnan(actual) + + +def test_hausdorff_distance(): + # example from GEOS docs + a = shapely.linestrings([[0, 0], [100, 0], [10, 100], [10, 100]]) + b = shapely.linestrings([[0, 100], [0, 10], [80, 10]]) + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Hausdorff distance emits "invalid value encountered" + # (see https://github.com/libgeos/geos/issues/515) + actual = shapely.hausdorff_distance(a, b) + assert actual == pytest.approx(22.360679775, abs=1e-7) + + +def test_hausdorff_distance_densify(): + # example from GEOS docs + a = shapely.linestrings([[0, 0], [100, 0], [10, 100], [10, 100]]) + b = shapely.linestrings([[0, 100], [0, 10], [80, 10]]) + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Hausdorff distance emits "invalid value encountered" + # (see https://github.com/libgeos/geos/issues/515) + actual = shapely.hausdorff_distance(a, b, densify=0.001) + assert actual == pytest.approx(47.8, abs=0.1) + + +def test_hausdorff_distance_missing(): + actual = shapely.hausdorff_distance(point, None) + assert np.isnan(actual) + actual = shapely.hausdorff_distance(point, None, densify=0.001) + assert np.isnan(actual) + + +def test_hausdorff_densify_nan(): + actual = shapely.hausdorff_distance(point, point, densify=np.nan) + assert np.isnan(actual) + + +def test_distance_empty(): + actual = shapely.distance(point, empty) + assert np.isnan(actual) + + +def test_hausdorff_distance_empty(): + actual = shapely.hausdorff_distance(point, empty) + assert np.isnan(actual) + + +def test_hausdorff_distance_densify_empty(): + actual = shapely.hausdorff_distance(point, empty, densify=0.2) + assert np.isnan(actual) + + +@pytest.mark.parametrize( + "geom1, geom2, expected", + [ + # identical geometries should have 0 distance + ( + shapely.linestrings([[0, 0], [100, 0]]), + shapely.linestrings([[0, 0], [100, 0]]), + 0, + ), + # example from GEOS docs + ( + shapely.linestrings([[0, 0], [50, 200], [100, 0], [150, 200], [200, 0]]), + shapely.linestrings([[0, 200], [200, 150], [0, 100], [200, 50], [0, 0]]), + 200, + ), + # same geometries but different curve direction results in maximum + # distance between vertices on the lines. + ( + shapely.linestrings([[0, 0], [50, 200], [100, 0], [150, 200], [200, 0]]), + shapely.linestrings([[200, 0], [150, 200], [100, 0], [50, 200], [0, 0]]), + 200, + ), + # another example from GEOS docs + ( + shapely.linestrings([[0, 0], [50, 200], [100, 0], [150, 200], [200, 0]]), + shapely.linestrings([[0, 0], [200, 50], [0, 100], [200, 150], [0, 200]]), + 282.842712474619, + ), + # example from GEOS tests + ( + shapely.linestrings([[0, 0], [100, 0]]), + shapely.linestrings([[0, 0], [50, 50], [100, 0]]), + 70.7106781186548, + ), + ], +) +def test_frechet_distance(geom1, geom2, expected): + actual = shapely.frechet_distance(geom1, geom2) + assert actual == pytest.approx(expected, abs=1e-12) + + +@pytest.mark.parametrize( + "geom1, geom2, densify, expected", + [ + # example from GEOS tests + ( + shapely.linestrings([[0, 0], [100, 0]]), + shapely.linestrings([[0, 0], [50, 50], [100, 0]]), + 0.002, + 50, + ) + ], +) +def test_frechet_distance_densify(geom1, geom2, densify, expected): + actual = shapely.frechet_distance(geom1, geom2, densify=densify) + assert actual == pytest.approx(expected, abs=1e-12) + + +@pytest.mark.parametrize( + "geom1, geom2", + [ + (line_string, None), + (None, line_string), + (None, None), + (line_string, empty), + (empty, line_string), + (empty, empty), + ], +) +def test_frechet_distance_nan_for_invalid_geometry_inputs(geom1, geom2): + actual = shapely.frechet_distance(geom1, geom2) + assert np.isnan(actual) + + +def test_frechet_densify_ndarray(): + actual = shapely.frechet_distance( + shapely.linestrings([[0, 0], [100, 0]]), + shapely.linestrings([[0, 0], [50, 50], [100, 0]]), + densify=[0.1, 0.2, 1], + ) + expected = np.array([50, 50.99019514, 70.7106781186548]) + np.testing.assert_array_almost_equal(actual, expected) + + +def test_frechet_densify_nan(): + actual = shapely.frechet_distance(line_string, line_string, densify=np.nan) + assert np.isnan(actual) + + +@pytest.mark.parametrize("densify", [0, -1, 2]) +def test_frechet_densify_invalid_values(densify): + with pytest.raises(shapely.GEOSException, match="Fraction is not in range"): + shapely.frechet_distance(line_string, line_string, densify=densify) + + +def test_frechet_distance_densify_empty(): + actual = shapely.frechet_distance(line_string, empty, densify=0.2) + assert np.isnan(actual) + + +def test_minimum_clearance(): + actual = shapely.minimum_clearance([polygon, polygon_with_hole, multi_polygon]) + assert_allclose(actual, [2.0, 2.0, 0.1]) + + +def test_minimum_clearance_nonexistent(): + actual = shapely.minimum_clearance([point, empty]) + assert np.isinf(actual).all() + + +def test_minimum_clearance_missing(): + actual = shapely.minimum_clearance(None) + assert np.isnan(actual) + + +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + Polygon([(0, 5), (5, 10), (10, 5), (5, 0), (0, 5)]), + 5, + ), + ( + LineString([(1, 0), (1, 10)]), + 5, + ), + ( + MultiPoint([(2, 2), (4, 2)]), + 1, + ), + ( + Point(2, 2), + 0, + ), + ( + GeometryCollection(), + 0, + ), + ], +) +def test_minimum_bounding_radius(geometry, expected): + actual = shapely.minimum_bounding_radius(geometry) + assert actual == pytest.approx(expected, abs=1e-12) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_misc.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee2c98ee75b0ef18b4a74cfddf399ee3b8c4c44 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_misc.py @@ -0,0 +1,189 @@ +import os +import sys +from inspect import cleandoc +from itertools import chain +from string import ascii_letters, digits +from unittest import mock + +import numpy as np +import pytest + +import shapely +from shapely.decorators import multithreading_enabled, requires_geos + + +@pytest.fixture +def mocked_geos_version(): + with mock.patch.object(shapely.lib, "geos_version", new=(3, 10, 1)): + yield "3.10.1" + + +@pytest.fixture +def sphinx_doc_build(): + os.environ["SPHINX_DOC_BUILD"] = "1" + yield + del os.environ["SPHINX_DOC_BUILD"] + + +def test_version(): + assert isinstance(shapely.__version__, str) + + +def test_geos_version(): + expected = "{}.{}.{}".format(*shapely.geos_version) + actual = shapely.geos_version_string + + # strip any beta / dev qualifiers + if any(c.isalpha() for c in actual): + if actual[-1].isnumeric(): + actual = actual.rstrip(digits) + actual = actual.rstrip(ascii_letters) + + assert actual == expected + + +def test_geos_capi_version(): + expected = "{}.{}.{}-CAPI-{}.{}.{}".format( + *(shapely.geos_version + shapely.geos_capi_version) + ) + + # split into component parts and strip any beta / dev qualifiers + ( + actual_geos_version, + actual_geos_api_version, + ) = shapely.geos_capi_version_string.split("-CAPI-") + + if any(c.isalpha() for c in actual_geos_version): + if actual_geos_version[-1].isnumeric(): + actual_geos_version = actual_geos_version.rstrip(digits) + actual_geos_version = actual_geos_version.rstrip(ascii_letters) + actual_geos_version = actual_geos_version.rstrip(ascii_letters) + + assert f"{actual_geos_version}-CAPI-{actual_geos_api_version}" == expected + + +def func(): + """Docstring that will be mocked. + A multiline. + + Some description. + """ + + +class SomeClass: + def func(self): + """Docstring that will be mocked. + A multiline. + + Some description. + """ + + +def expected_docstring(**kwds): + doc = """Docstring that will be mocked. +{indent}A multiline. + +{indent}.. note:: 'func' requires at least GEOS {version}. + +{indent}Some description. +{indent}""".format(**kwds) + if sys.version_info[:2] >= (3, 13): + # There are subtle differences between inspect.cleandoc() and + # _PyCompile_CleanDoc(). Most significantly, the latter does not remove + # leading or trailing blank lines. + return cleandoc(doc) + "\n" + return doc + + +@pytest.mark.parametrize("version", ["3.10.0", "3.10.1", "3.9.2"]) +def test_requires_geos_ok(version, mocked_geos_version): + wrapped = requires_geos(version)(func) + wrapped() + assert wrapped is func + + +@pytest.mark.parametrize("version", ["3.10.2", "3.11.0", "3.11.1"]) +def test_requires_geos_not_ok(version, mocked_geos_version): + wrapped = requires_geos(version)(func) + with pytest.raises(shapely.errors.UnsupportedGEOSVersionError): + wrapped() + + assert wrapped.__doc__ == expected_docstring(version=version, indent=" " * 4) + + +@pytest.mark.parametrize("version", ["3.9.0", "3.10.0"]) +def test_requires_geos_doc_build(version, mocked_geos_version, sphinx_doc_build): + """The requires_geos decorator always adapts the docstring.""" + wrapped = requires_geos(version)(func) + + assert wrapped.__doc__ == expected_docstring(version=version, indent=" " * 4) + + +@pytest.mark.parametrize("version", ["3.9.0", "3.10.0"]) +def test_requires_geos_method(version, mocked_geos_version, sphinx_doc_build): + """The requires_geos decorator adjusts methods docstrings correctly""" + wrapped = requires_geos(version)(SomeClass.func) + + assert wrapped.__doc__ == expected_docstring(version=version, indent=" " * 8) + + +@multithreading_enabled +def set_first_element(value, *args, **kwargs): + for arg in chain(args, kwargs.values()): + if hasattr(arg, "__setitem__"): + arg[0] = value + return arg + + +def test_multithreading_enabled_raises_arg(): + arr = np.empty((1,), dtype=object) + + # set_first_element cannot change the input array + with pytest.raises(ValueError): + set_first_element(42, arr) + + # afterwards, we can + arr[0] = 42 + assert arr[0] == 42 + + +def test_multithreading_enabled_raises_kwarg(): + arr = np.empty((1,), dtype=object) + + # set_first_element cannot change the input array + with pytest.raises(ValueError): + set_first_element(42, arr=arr) + + # writable flag goes to original state + assert arr.flags.writeable + + +def test_multithreading_enabled_preserves_flag(): + arr = np.empty((1,), dtype=object) + arr.flags.writeable = False + + # set_first_element cannot change the input array + with pytest.raises(ValueError): + set_first_element(42, arr) + + # writable flag goes to original state + assert not arr.flags.writeable + + +@pytest.mark.parametrize( + "args,kwargs", + [ + ((np.empty((1,), dtype=float),), {}), # float-dtype ndarray is untouched + ((), {"a": np.empty((1,), dtype=float)}), + (([1],), {}), # non-ndarray is untouched + ((), {"a": [1]}), + ((), {"out": np.empty((1,), dtype=object)}), # ufunc kwarg 'out' is untouched + ( + (), + {"where": np.empty((1,), dtype=object)}, + ), # ufunc kwarg 'where' is untouched + ], +) +def test_multithreading_enabled_ok(args, kwargs): + result = set_first_element(42, *args, **kwargs) + assert result[0] == 42 diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_plotting.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..78a4175ee4baaba8030fe127083fb29cbb8fdfa7 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_plotting.py @@ -0,0 +1,121 @@ +import pytest +from numpy.testing import assert_allclose + +from shapely import ( + LineString, + MultiLineString, + MultiPolygon, + Point, + box, + get_coordinates, +) +from shapely.ops import orient +from shapely.plotting import patch_from_polygon, plot_line, plot_points, plot_polygon + +pytest.importorskip("matplotlib") + + +def test_patch_from_polygon(): + poly = box(0, 0, 1, 1) + artist = patch_from_polygon(poly, facecolor="red", edgecolor="blue", linewidth=3) + assert equal_color(artist.get_facecolor(), "red") + assert equal_color(artist.get_edgecolor(), "blue") + assert artist.get_linewidth() == 3 + + +def test_patch_from_polygon_with_interior(): + poly = box(0, 0, 1, 1).difference(box(0.2, 0.2, 0.5, 0.5)) + artist = patch_from_polygon(poly, facecolor="red", edgecolor="blue", linewidth=3) + assert equal_color(artist.get_facecolor(), "red") + assert equal_color(artist.get_edgecolor(), "blue") + assert artist.get_linewidth() == 3 + + +def test_patch_from_multipolygon(): + poly = box(0, 0, 1, 1).union(box(2, 2, 3, 3)) + artist = patch_from_polygon(poly, facecolor="red", edgecolor="blue", linewidth=3) + assert equal_color(artist.get_facecolor(), "red") + assert equal_color(artist.get_edgecolor(), "blue") + assert artist.get_linewidth() == 3 + + +def test_plot_polygon(): + poly = box(0, 0, 1, 1) + artist, _ = plot_polygon(poly) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(poly)) + + # overriding default styling + artist = plot_polygon(poly, add_points=False, color="red", linewidth=3) + assert equal_color(artist.get_facecolor(), "red", alpha=0.3) + assert equal_color(artist.get_edgecolor(), "red", alpha=1.0) + assert artist.get_linewidth() == 3 + + +def test_plot_polygon_with_interior(): + poly = box(0, 0, 1, 1).difference(box(0.2, 0.2, 0.5, 0.5)) + artist, _ = plot_polygon(poly) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(orient(poly))) + + +def test_plot_multipolygon(): + poly = box(0, 0, 1, 1).union(box(2, 2, 3, 3)) + artist, _ = plot_polygon(poly) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(poly)) + + +def test_plot_multipolygon_with_interior(): + poly1 = box(0, 0, 1, 1).difference(box(0.2, 0.2, 0.5, 0.5)) + poly2 = box(3, 3, 6, 6).difference(box(4, 4, 5, 5)) + poly = MultiPolygon([poly1, poly2]) + + artist, _ = plot_polygon(poly) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(orient(poly))) + + +def test_plot_line(): + line = LineString([(0, 0), (1, 0), (1, 1)]) + artist, _ = plot_line(line) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(line)) + + # overriding default styling + artist = plot_line(line, add_points=False, color="red", linewidth=3) + assert equal_color(artist.get_edgecolor(), "red") + assert equal_color(artist.get_facecolor(), "none") + assert artist.get_linewidth() == 3 + + +def test_plot_multilinestring(): + line = MultiLineString( + [LineString([(0, 0), (1, 0), (1, 1)]), LineString([(2, 2), (3, 3)])] + ) + artist, _ = plot_line(line) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(line)) + + +def test_plot_points(): + for geom in [Point(0, 0), LineString([(0, 0), (1, 0), (1, 1)]), box(0, 0, 1, 1)]: + artist = plot_points(geom) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(geom)) + assert artist.get_linestyle() == "None" + + # overriding default styling + geom = Point(0, 0) + artist = plot_points(geom, color="red", marker="+", fillstyle="top") + assert artist.get_color() == "red" + assert artist.get_marker() == "+" + assert artist.get_fillstyle() == "top" + + +def equal_color(actual, expected, alpha=None): + from matplotlib import colors + + conv = colors.colorConverter + + return actual == conv.to_rgba(expected, alpha=alpha) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_predicates.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_predicates.py new file mode 100644 index 0000000000000000000000000000000000000000..a0fbac2358257c9a071995438b1b1594236e5bad --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_predicates.py @@ -0,0 +1,414 @@ +from functools import partial + +import numpy as np +import pytest + +import shapely +from shapely import LinearRing, LineString, Point +from shapely.tests.common import ( + all_types, + all_types_m, + all_types_z, + all_types_zm, + empty, + geometry_collection, + ignore_invalid, + line_string, + linear_ring, + point, + polygon, +) + +UNARY_PREDICATES = ( + shapely.has_z, + pytest.param( + shapely.has_m, + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + shapely.is_empty, + shapely.is_simple, + shapely.is_ring, + shapely.is_closed, + shapely.is_valid, + shapely.is_missing, + shapely.is_geometry, + shapely.is_valid_input, + shapely.is_prepared, + shapely.is_ccw, +) + +BINARY_PREDICATES = ( + shapely.disjoint, + shapely.touches, + shapely.intersects, + shapely.crosses, + shapely.within, + shapely.contains, + shapely.contains_properly, + shapely.overlaps, + shapely.covers, + shapely.covered_by, + pytest.param( + partial(shapely.dwithin, distance=1.0), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10" + ), + ), + shapely.equals, + shapely.equals_exact, + shapely.equals_identical, +) + +BINARY_PREPARED_PREDICATES = BINARY_PREDICATES[:-2] + +XY_PREDICATES = ( + (shapely.contains_xy, shapely.contains), + (shapely.intersects_xy, shapely.intersects), +) + + +@pytest.mark.parametrize("geometry", all_types + all_types_z) +@pytest.mark.parametrize("func", UNARY_PREDICATES) +def test_unary_array(geometry, func): + actual = func([geometry, geometry]) + assert actual.shape == (2,) + assert actual.dtype == np.bool_ + + +@pytest.mark.parametrize("func", UNARY_PREDICATES) +def test_unary_with_kwargs(func): + out = np.empty((), dtype=np.uint8) + actual = func(point, out=out) + assert actual is out + assert actual.dtype == np.uint8 + + +@pytest.mark.parametrize("func", UNARY_PREDICATES) +def test_unary_missing(func): + if func in (shapely.is_valid_input, shapely.is_missing): + assert func(None) + else: + assert not func(None) + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func", BINARY_PREDICATES) +def test_binary_array(a, func): + with ignore_invalid(shapely.is_empty(a) and shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + actual = func([a, a], point) + assert actual.shape == (2,) + assert actual.dtype == np.bool_ + + +@pytest.mark.parametrize("func", BINARY_PREDICATES) +def test_binary_with_kwargs(func): + out = np.empty((), dtype=np.uint8) + actual = func(point, point, out=out) + assert actual is out + assert actual.dtype == np.uint8 + + +@pytest.mark.parametrize("func", BINARY_PREDICATES) +def test_binary_missing(func): + actual = func(np.array([point, None, None]), np.array([None, point, None])) + assert (~actual).all() + + +def test_binary_empty_result(): + a = LineString([(0, 0), (3, 0), (3, 3), (0, 3)]) + b = LineString([(5, 1), (6, 1)]) + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Intersection resulting in empty geometries give 'invalid value encountered' + # (https://github.com/shapely/shapely/issues/1345) + assert shapely.intersection(a, b).is_empty + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func, func_bin", XY_PREDICATES) +def test_xy_array(a, func, func_bin): + with ignore_invalid(shapely.is_empty(a) and shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + actual = func([a, a], 2, 3) + expected = func_bin([a, a], Point(2, 3)) + assert actual.shape == (2,) + assert actual.dtype == np.bool_ + np.testing.assert_allclose(actual, expected) + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func, func_bin", XY_PREDICATES) +def test_xy_array_broadcast(a, func, func_bin): + a2 = shapely.transform(a, lambda x: x) # makes a copy + with ignore_invalid(shapely.is_empty(a) and shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + actual = func(a2, [0, 1, 2], [1, 2, 3]) + expected = func_bin(a, [Point(0, 1), Point(1, 2), Point(2, 3)]) + np.testing.assert_allclose(actual, expected) + + +@pytest.mark.parametrize("func", [funcs[0] for funcs in XY_PREDICATES]) +def test_xy_array_2D(func): + polygon2 = shapely.transform(polygon, lambda x: x) # makes a copy + actual = func(polygon2, [0, 1, 2], [1, 2, 3]) + expected = func(polygon2, [[0, 1], [1, 2], [2, 3]]) + np.testing.assert_allclose(actual, expected) + + +@pytest.mark.parametrize("func, func_bin", XY_PREDICATES) +def test_xy_prepared(func, func_bin): + actual = func(_prepare_with_copy([polygon, line_string]), 2, 3) + expected = func_bin([polygon, line_string], Point(2, 3)) + np.testing.assert_allclose(actual, expected) + + +@pytest.mark.parametrize("func", [funcs[0] for funcs in XY_PREDICATES]) +def test_xy_with_kwargs(func): + out = np.empty((), dtype=np.uint8) + point2 = shapely.transform(point, lambda x: x) # makes a copy + actual = func(point2, point2.x, point2.y, out=out) + assert actual is out + assert actual.dtype == np.uint8 + + +@pytest.mark.parametrize("func", [funcs[0] for funcs in XY_PREDICATES]) +def test_xy_missing(func): + actual = func( + np.array([point, point, point, None]), + np.array([point.x, np.nan, point.x, point.x]), + np.array([point.y, point.y, np.nan, point.y]), + ) + np.testing.assert_allclose(actual, [True, False, False, False]) + + +def test_equals_exact_tolerance(): + # specifying tolerance + p1 = shapely.points(50, 4) + p2 = shapely.points(50.1, 4.1) + actual = shapely.equals_exact([p1, p2, None], p1, tolerance=0.05) + np.testing.assert_allclose(actual, [True, False, False]) + assert actual.dtype == np.bool_ + actual = shapely.equals_exact([p1, p2, None], p1, tolerance=0.2) + np.testing.assert_allclose(actual, [True, True, False]) + assert actual.dtype == np.bool_ + + # default value for tolerance + assert shapely.equals_exact(p1, p1).item() is True + assert shapely.equals_exact(p1, p2).item() is False + + # an array of tolerances + actual = shapely.equals_exact(p1, p2, tolerance=[0.05, 0.2, np.nan]) + np.testing.assert_allclose(actual, [False, True, False]) + + +def test_equals_exact_normalize(): + l1 = LineString([(0, 0), (1, 1)]) + l2 = LineString([(1, 1), (0, 0)]) + # default requires same order of coordinates + assert not shapely.equals_exact(l1, l2) + assert shapely.equals_exact(l1, l2, normalize=True) + + +def test_equals_identical(): + # more elaborate tests are done at the Geometry.__eq__ level + # requires same order of coordinates + l1 = LineString([(0, 0), (1, 1)]) + l2 = LineString([(1, 1), (0, 0)]) + assert not shapely.equals_identical(l1, l2) + + # checks z-dimension (in contrast to equals_exact) + l1 = LineString([(0, 0, 0), (1, 1, 0)]) + l2 = LineString([(0, 0, 1), (1, 1, 1)]) + assert not shapely.equals_identical(l1, l2) + assert shapely.equals_exact(l1, l2) + + # NaNs in same place are equal (in contrast to equals_exact) + with ignore_invalid(): + l1 = LineString([(0, np.nan), (1, 1)]) + l2 = LineString([(0, np.nan), (1, 1)]) + assert shapely.equals_identical(l1, l2) + assert not shapely.equals_exact(l1, l2) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_dwithin(): + p1 = shapely.points(50, 4) + p2 = shapely.points(50.1, 4.1) + actual = shapely.dwithin([p1, p2, None], p1, distance=0.05) + np.testing.assert_equal(actual, [True, False, False]) + assert actual.dtype == np.bool_ + actual = shapely.dwithin([p1, p2, None], p1, distance=0.2) + np.testing.assert_allclose(actual, [True, True, False]) + assert actual.dtype == np.bool_ + + # an array of distances + actual = shapely.dwithin(p1, p2, distance=[0.05, 0.2, np.nan]) + np.testing.assert_allclose(actual, [False, True, False]) + + +@pytest.mark.parametrize("geometry", all_types) +def test_has_z_has_m_all_types(geometry): + assert not shapely.has_z(geometry) + if shapely.geos_version >= (3, 12, 0): + assert not shapely.has_m(geometry) + + +# The next few tests skip has_z/has_m with empty geometries +# See https://github.com/libgeos/geos/issues/888 + + +@pytest.mark.parametrize("geometry", all_types_z) +def test_has_z_has_m_all_types_z(geometry): + if shapely.is_empty(geometry): + pytest.skip("GEOSHasZ with EMPTY geometries is inconsistent") + assert shapely.has_z(geometry) + if shapely.geos_version >= (3, 12, 0): + assert not shapely.has_m(geometry) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geometry", all_types_m) +def test_has_m_all_types_m(geometry): + if shapely.is_empty(geometry): + pytest.skip("GEOSHasM with EMPTY geometries is inconsistent") + assert not shapely.has_z(geometry) + assert shapely.has_m(geometry) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geometry", all_types_zm) +def test_has_z_has_m_all_types_zm(geometry): + if shapely.is_empty(geometry): + pytest.skip("GEOSHasZ with EMPTY geometries is inconsistent") + assert shapely.has_z(geometry) + assert shapely.has_m(geometry) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (point, False), + (line_string, False), + (linear_ring, True), + (empty, False), + ], +) +def test_is_closed(geometry, expected): + assert shapely.is_closed(geometry) == expected + + +def test_relate(): + p1 = shapely.points(0, 0) + p2 = shapely.points(1, 1) + actual = shapely.relate(p1, p2) + assert isinstance(actual, str) + assert actual == "FF0FFF0F2" + + +@pytest.mark.parametrize("g1, g2", [(point, None), (None, point), (None, None)]) +def test_relate_none(g1, g2): + assert shapely.relate(g1, g2) is None + + +def test_relate_pattern(): + g = shapely.linestrings([(0, 0), (1, 0), (1, 1)]) + polygon = shapely.box(0, 0, 2, 2) + assert shapely.relate(g, polygon) == "11F00F212" + assert shapely.relate_pattern(g, polygon, "11F00F212") + assert shapely.relate_pattern(g, polygon, "*********") + assert not shapely.relate_pattern(g, polygon, "F********") + + +def test_relate_pattern_empty(): + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + assert shapely.relate_pattern(empty, empty, "*" * 9).item() is True + + +@pytest.mark.parametrize("g1, g2", [(point, None), (None, point), (None, None)]) +def test_relate_pattern_none(g1, g2): + assert shapely.relate_pattern(g1, g2, "*" * 9).item() is False + + +def test_relate_pattern_incorrect_length(): + with pytest.raises(shapely.GEOSException, match="Should be length 9"): + shapely.relate_pattern(point, polygon, "**") + + with pytest.raises(shapely.GEOSException, match="Should be length 9"): + shapely.relate_pattern(point, polygon, "**********") + + +@pytest.mark.parametrize("pattern", [b"*********", 10, None]) +def test_relate_pattern_non_string(pattern): + with pytest.raises(TypeError, match="expected string"): + shapely.relate_pattern(point, polygon, pattern) + + +def test_relate_pattern_non_scalar(): + with pytest.raises(ValueError, match="only supports scalar"): + shapely.relate_pattern([point] * 2, polygon, ["*********"] * 2) + + +@pytest.mark.parametrize( + "geom, expected", + [ + (LinearRing([(0, 0), (0, 1), (1, 1), (0, 0)]), False), + (LinearRing([(0, 0), (1, 1), (0, 1), (0, 0)]), True), + (LineString([(0, 0), (0, 1), (1, 1), (0, 0)]), False), + (LineString([(0, 0), (1, 1), (0, 1), (0, 0)]), True), + (LineString([(0, 0), (1, 1), (0, 1)]), False), + (LineString([(0, 0), (0, 1), (1, 1)]), False), + (point, False), + (polygon, False), + (geometry_collection, False), + (None, False), + ], +) +def test_is_ccw(geom, expected): + assert shapely.is_ccw(geom) == expected + + +def _prepare_with_copy(geometry): + """Prepare without modifying in-place""" + geometry = shapely.transform(geometry, lambda x: x) # makes a copy + shapely.prepare(geometry) + return geometry + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func", BINARY_PREPARED_PREDICATES) +def test_binary_prepared(a, func): + with ignore_invalid(shapely.is_empty(a) and shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + actual = func(a, point) + result = func(_prepare_with_copy(a), point) + assert actual == result + + +@pytest.mark.parametrize("geometry", all_types) +def test_is_prepared_true(geometry): + assert shapely.is_prepared(_prepare_with_copy(geometry)) + + +@pytest.mark.parametrize("geometry", all_types + (None,)) +def test_is_prepared_false(geometry): + assert not shapely.is_prepared(geometry) + + +def test_contains_properly(): + # polygon contains itself, but does not properly contains itself + assert shapely.contains(polygon, polygon).item() is True + assert shapely.contains_properly(polygon, polygon).item() is False diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_ragged_array.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_ragged_array.py new file mode 100644 index 0000000000000000000000000000000000000000..8b540923c8669859228542846b3c899070e08417 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_ragged_array.py @@ -0,0 +1,665 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose + +import shapely +from shapely import MultiLineString, MultiPoint, MultiPolygon +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + empty_line_string, + empty_line_string_m, + empty_line_string_z, + empty_line_string_zm, + empty_multi_polygon_m, + empty_multi_polygon_z, + empty_multi_polygon_zm, + geometry_collection, + line_string, + line_string_m, + line_string_z, + line_string_zm, + linear_ring, + multi_line_string, + multi_line_string_m, + multi_line_string_z, + multi_line_string_zm, + multi_point, + multi_point_m, + multi_point_z, + multi_point_zm, + multi_polygon, + multi_polygon_m, + multi_polygon_z, + multi_polygon_zm, + point, + point_m, + point_z, + point_zm, + polygon, + polygon_m, + polygon_z, + polygon_zm, +) + +all_types = ( + point, + line_string, + polygon, + multi_point, + multi_line_string, + multi_polygon, +) + +all_types_z = ( + point_z, + line_string_z, + polygon_z, + multi_point_z, + multi_line_string_z, + multi_polygon_z, +) + +all_types_m = ( + point_m, + line_string_m, + polygon_m, + multi_point_m, + multi_line_string_m, + multi_polygon_m, +) + +all_types_zm = ( + point_zm, + line_string_zm, + polygon_zm, + multi_point_zm, + multi_line_string_zm, + multi_polygon_zm, +) + +all_types_dims_combos = all_types + all_types_z +if shapely.geos_version >= (3, 12, 0): + all_types_dims_combos = all_types_dims_combos + all_types_m + all_types_zm + +all_types_not_supported = ( + linear_ring, + geometry_collection, +) + + +@pytest.mark.parametrize("geom", all_types + all_types_z) +def test_roundtrip(geom): + actual = shapely.from_ragged_array(*shapely.to_ragged_array([geom, geom])) + assert_geometries_equal(actual, [geom, geom]) + + +@pytest.mark.parametrize("include_m", [None, True, False]) +@pytest.mark.parametrize("include_z", [None, True, False]) +@pytest.mark.parametrize("geom", all_types_dims_combos) +def test_to_ragged_array(geom, include_z, include_m): + _, coords, _ = shapely.to_ragged_array( + [geom, geom], include_z=include_z, include_m=include_m + ) + nan_dims = np.all(np.isnan(coords), axis=0).tolist() + expected = [False, False] # XY + has_z = geom.has_z + if include_z or (include_z is None and has_z): + expected.append(not has_z) # XYZ or XYZM + if shapely.geos_version >= (3, 12, 0): + has_m = geom.has_m + else: + has_m = False + if include_m or (include_m is None and has_m): + expected.append(not has_m) # XYM or XYZM + assert nan_dims == expected + + +def test_include_z_default(): + # corner cases for inferring dimensionality + + # mixed XY and XYZ -> XYZ + _, coords, _ = shapely.to_ragged_array([line_string, line_string_z]) + assert coords.shape[1] == 3 + + # only empties -> always 2D + _, coords, _ = shapely.to_ragged_array([empty_line_string]) + assert coords.shape[1] == 2 + _, coords, _ = shapely.to_ragged_array([empty_line_string_z]) + assert coords.shape[1] == 2 + # empty collection -> GEOS indicates 2D + _, coords, _ = shapely.to_ragged_array([empty_multi_polygon_z]) + assert coords.shape[1] == 2 + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_include_m_default(): + # a few other corner cases for inferring dimensionality + + # mixed XY and XYM -> XYM + _, coords, _ = shapely.to_ragged_array([line_string, line_string_m]) + assert coords.shape[1] == 3 + + # mixed XY, XYM, and XYZM -> XYZM + _, coords, _ = shapely.to_ragged_array([line_string, line_string_m, line_string_zm]) + assert coords.shape[1] == 4 + + # only empties -> always 2D + _, coords, _ = shapely.to_ragged_array([empty_line_string_m]) + assert coords.shape[1] == 2 + _, coords, _ = shapely.to_ragged_array([empty_line_string_zm]) + assert coords.shape[1] == 2 + # empty collection -> GEOS indicates 2D + _, coords, _ = shapely.to_ragged_array([empty_multi_polygon_m]) + assert coords.shape[1] == 2 + _, coords, _ = shapely.to_ragged_array([empty_multi_polygon_zm]) + assert coords.shape[1] == 2 + + +@pytest.mark.parametrize("geom", all_types) +def test_read_only_arrays(geom): + # https://github.com/shapely/shapely/pull/1744 + typ, coords, offsets = shapely.to_ragged_array([geom, geom]) + coords.flags.writeable = False + for arr in offsets: + arr.flags.writeable = False + result = shapely.from_ragged_array(typ, coords, offsets) + assert_geometries_equal(result, [geom, geom]) + + +@pytest.mark.parametrize("geom", all_types_not_supported) +def test_raise_geometry_type(geom): + with pytest.raises(ValueError): + shapely.to_ragged_array([geom, geom]) + + +def test_points(): + arr = shapely.from_wkt( + [ + "POINT (0 0)", + "POINT (1 1)", + "POINT EMPTY", + "POINT EMPTY", + "POINT (4 4)", + None, + "POINT EMPTY", + ] + ) + typ, result, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [0, 0], + [1, 1], + [np.nan, np.nan], + [np.nan, np.nan], + [4, 4], + [np.nan, np.nan], + [np.nan, np.nan], + ] + ) + assert typ == shapely.GeometryType.POINT + assert len(result) == len(arr) + assert_allclose(result, expected) + assert len(offsets) == 0 + + geoms = shapely.from_ragged_array(typ, result) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("POINT EMPTY") + assert_geometries_equal(geoms, arr) + + +def test_linestrings(): + arr = shapely.from_wkt( + [ + "LINESTRING (30 10, 10 30, 40 40)", + "LINESTRING (40 40, 30 30, 40 20, 30 10)", + "LINESTRING EMPTY", + "LINESTRING EMPTY", + "LINESTRING (10 10, 20 20, 10 40)", + None, + "LINESTRING EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [30.0, 10.0], + [10.0, 30.0], + [40.0, 40.0], + [40.0, 40.0], + [30.0, 30.0], + [40.0, 20.0], + [30.0, 10.0], + [10.0, 10.0], + [20.0, 20.0], + [10.0, 40.0], + ] + ) + expected_offsets = np.array([0, 3, 7, 7, 7, 10, 10, 10], dtype="int32") + assert typ == shapely.GeometryType.LINESTRING + assert_allclose(coords, expected) + assert len(offsets) == 1 + assert offsets[0].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("LINESTRING EMPTY") + assert_geometries_equal(result, arr) + + # sliced + offsets_sliced = (offsets[0][1:],) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0][:-1],) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-1]) + + +def test_polygons(): + arr = shapely.from_wkt( + [ + "POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))", + "POLYGON ((35 10, 45 45, 15 40, 10 20, 35 10), (20 30, 35 35, 30 20, 20 30))", # noqa: E501 + "POLYGON EMPTY", + "POLYGON EMPTY", + "POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))", + None, + "POLYGON EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [30.0, 10.0], + [40.0, 40.0], + [20.0, 40.0], + [10.0, 20.0], + [30.0, 10.0], + [35.0, 10.0], + [45.0, 45.0], + [15.0, 40.0], + [10.0, 20.0], + [35.0, 10.0], + [20.0, 30.0], + [35.0, 35.0], + [30.0, 20.0], + [20.0, 30.0], + [30.0, 10.0], + [40.0, 40.0], + [20.0, 40.0], + [10.0, 20.0], + [30.0, 10.0], + ] + ) + expected_offsets1 = np.array([0, 5, 10, 14, 19]) + expected_offsets2 = np.array([0, 1, 3, 3, 3, 4, 4, 4]) + + assert typ == shapely.GeometryType.POLYGON + assert_allclose(coords, expected) + assert len(offsets) == 2 + assert offsets[0].dtype == np.int32 + assert offsets[1].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets1) + assert_allclose(offsets[1], expected_offsets2) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("POLYGON EMPTY") + assert_geometries_equal(result, arr) + + # sliced: + # - indices into the coordinate array for the whole buffer + # - indices into the ring array for *just* the sliced part + offsets_sliced = (offsets[0], offsets[1][1:]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0], offsets[1][:-1]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-1]) + + +def test_multipoints(): + arr = shapely.from_wkt( + [ + "MULTIPOINT (10 40, 40 30, 20 20, 30 10)", + "MULTIPOINT (30 10)", + "MULTIPOINT EMPTY", + "MULTIPOINT EMPTY", + "MULTIPOINT (30 10, 10 30, 40 40)", + None, + "MULTIPOINT EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [10.0, 40.0], + [40.0, 30.0], + [20.0, 20.0], + [30.0, 10.0], + [30.0, 10.0], + [30.0, 10.0], + [10.0, 30.0], + [40.0, 40.0], + ] + ) + expected_offsets = np.array([0, 4, 5, 5, 5, 8, 8, 8]) + + assert typ == shapely.GeometryType.MULTIPOINT + assert_allclose(coords, expected) + assert len(offsets) == 1 + assert offsets[0].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("MULTIPOINT EMPTY") + assert_geometries_equal(result, arr) + + # sliced: + offsets_sliced = (offsets[0][1:],) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0][:-1],) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-1]) + + +def test_multilinestrings(): + arr = shapely.from_wkt( + [ + "MULTILINESTRING ((30 10, 10 30, 40 40))", + "MULTILINESTRING ((10 10, 20 20, 10 40), (40 40, 30 30, 40 20, 30 10))", + "MULTILINESTRING EMPTY", + "MULTILINESTRING EMPTY", + "MULTILINESTRING ((35 10, 45 45), (15 40, 10 20), (30 10, 10 30, 40 40))", + None, + "MULTILINESTRING EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [30.0, 10.0], + [10.0, 30.0], + [40.0, 40.0], + [10.0, 10.0], + [20.0, 20.0], + [10.0, 40.0], + [40.0, 40.0], + [30.0, 30.0], + [40.0, 20.0], + [30.0, 10.0], + [35.0, 10.0], + [45.0, 45.0], + [15.0, 40.0], + [10.0, 20.0], + [30.0, 10.0], + [10.0, 30.0], + [40.0, 40.0], + ] + ) + expected_offsets1 = np.array([0, 3, 6, 10, 12, 14, 17]) + expected_offsets2 = np.array([0, 1, 3, 3, 3, 6, 6, 6]) + + assert typ == shapely.GeometryType.MULTILINESTRING + assert_allclose(coords, expected) + assert len(offsets) == 2 + assert offsets[0].dtype == np.int32 + assert offsets[1].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets1) + assert_allclose(offsets[1], expected_offsets2) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("MULTILINESTRING EMPTY") + assert_geometries_equal(result, arr) + + # sliced: + # - indices into the coordinate array for the whole buffer + # - indices into the line parts for *just* the sliced part + offsets_sliced = (offsets[0], offsets[1][1:]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0], offsets[1][:-1]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-1]) + + +def test_multipolygons(): + arr = shapely.from_wkt( + [ + "MULTIPOLYGON (((35 10, 45 45, 15 40, 10 20, 35 10), (20 30, 35 35, 30 20, 20 30)))", # noqa: E501 + "MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)), ((20 35, 10 30, 10 10, 30 5, 45 20, 20 35), (30 20, 20 15, 20 25, 30 20)))", # noqa: E501 + "MULTIPOLYGON EMPTY", + "MULTIPOLYGON EMPTY", + "MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)))", + None, + "MULTIPOLYGON EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [35.0, 10.0], + [45.0, 45.0], + [15.0, 40.0], + [10.0, 20.0], + [35.0, 10.0], + [20.0, 30.0], + [35.0, 35.0], + [30.0, 20.0], + [20.0, 30.0], + [40.0, 40.0], + [20.0, 45.0], + [45.0, 30.0], + [40.0, 40.0], + [20.0, 35.0], + [10.0, 30.0], + [10.0, 10.0], + [30.0, 5.0], + [45.0, 20.0], + [20.0, 35.0], + [30.0, 20.0], + [20.0, 15.0], + [20.0, 25.0], + [30.0, 20.0], + [40.0, 40.0], + [20.0, 45.0], + [45.0, 30.0], + [40.0, 40.0], + ] + ) + expected_offsets1 = np.array([0, 5, 9, 13, 19, 23, 27]) + expected_offsets2 = np.array([0, 2, 3, 5, 6]) + expected_offsets3 = np.array([0, 1, 3, 3, 3, 4, 4, 4]) + + assert typ == shapely.GeometryType.MULTIPOLYGON + assert_allclose(coords, expected) + assert len(offsets) == 3 + assert offsets[0].dtype == np.int32 + assert offsets[1].dtype == np.int32 + assert offsets[2].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets1) + assert_allclose(offsets[1], expected_offsets2) + assert_allclose(offsets[2], expected_offsets3) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("MULTIPOLYGON EMPTY") + assert_geometries_equal(result, arr) + + # sliced: + offsets_sliced = (offsets[0], offsets[1], offsets[2][1:]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0], offsets[1], offsets[2][:-3]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-3]) + print(result) + + +def test_mixture_point_multipoint(): + typ, coords, offsets = shapely.to_ragged_array([point, multi_point]) + assert typ == shapely.GeometryType.MULTIPOINT + result = shapely.from_ragged_array(typ, coords, offsets) + expected = np.array([MultiPoint([point]), multi_point]) + assert_geometries_equal(result, expected) + + +def test_mixture_linestring_multilinestring(): + typ, coords, offsets = shapely.to_ragged_array([line_string, multi_line_string]) + assert typ == shapely.GeometryType.MULTILINESTRING + result = shapely.from_ragged_array(typ, coords, offsets) + expected = np.array([MultiLineString([line_string]), multi_line_string]) + assert_geometries_equal(result, expected) + + +def test_mixture_polygon_multipolygon(): + typ, coords, offsets = shapely.to_ragged_array([polygon, multi_polygon]) + assert typ == shapely.GeometryType.MULTIPOLYGON + result = shapely.from_ragged_array(typ, coords, offsets) + expected = np.array([MultiPolygon([polygon]), multi_polygon]) + assert_geometries_equal(result, expected) + + +def test_from_ragged_incorrect_rings_short(): + # too few coordinates for linearring + coords = np.array([[0, 0], [1, 1]], dtype="float64") + offsets1 = np.array([0, 2]) + offsets2 = np.array([0, 1]) + offsets3 = np.array([0, 1]) + + with pytest.raises( + ValueError, match="A linearring requires at least 4 coordinates" + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + + with pytest.raises( + ValueError, match="A linearring requires at least 4 coordinates" + ): + shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + + +def test_from_ragged_incorrect_rings_unclosed(): + # NaNs cause the ring to be unclosed + coords = np.full((4, 2), np.nan) + offsets1 = np.array([0, 4]) + offsets2 = np.array([0, 1]) + offsets3 = np.array([0, 1]) + + with pytest.raises( + shapely.GEOSException, + match="Points of LinearRing do not form a closed linestring", + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + + with pytest.raises( + shapely.GEOSException, + match="Points of LinearRing do not form a closed linestring", + ): + shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + + +def test_from_ragged_wrong_offsets(): + with pytest.raises(ValueError, match="'offsets' must be provided"): + shapely.from_ragged_array( + shapely.GeometryType.LINESTRING, np.array([[0, 0], [0, 1]]) + ) + + with pytest.raises(ValueError, match="'offsets' should not be provided"): + shapely.from_ragged_array( + shapely.GeometryType.POINT, + np.array([[0, 0], [0, 1]]), + offsets=(np.array([0, 1]),), + ) + + +def test_from_ragged_crash_2284(): + # caused segfault in shapely 2.1.0 + # https://github.com/shapely/shapely/discussions/2284 + + # one of the geometries has more rings than the total number of geometries + coords = np.random.default_rng().random(120).reshape((60, 2)) + offsets1 = np.array([0, 10, 20, 30, 40, 50, 60]) + offsets2 = np.array([0, 1, 5, 6]) + + for _ in range(10): + polygons = shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + # just ensure it didn't crash + assert len(polygons) == 3 + + offsets3 = np.array([0, 3]) + for _ in range(10): + polygons = shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + # just ensure it didn't crash + assert len(polygons) == 1 + + +def test_from_ragged_wrong_offsets_values(): + # caused segfault in shapely 2.1.0 + + # outer offsets indicates more rings than the shape of the ring offsets + coords = np.random.default_rng().random(70).reshape((35, 2)) + offsets1 = np.array([0, 10, 20], dtype=np.uint32) + offsets2 = np.array([0, 1, 5], dtype=np.uint32) + offsets3 = np.array([0, 2]) + + with pytest.raises( + ValueError, match="Number of rings indicated by the geometry offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + + with pytest.raises( + ValueError, match="Number of rings indicated by the part offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + + # inner offsets indicating more coordinats that the shape of the coordinates + coords = np.random.default_rng().random(70).reshape((35, 2)) + offsets1 = np.array([0, 10, 40], dtype=np.uint32) + offsets2 = np.array([0, 1, 2], dtype=np.uint32) + + with pytest.raises( + ValueError, match="Number of coordinates indicated by the linear offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + + with pytest.raises( + ValueError, match="Number of coordinates indicated by the linear offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + + # outer multipolygon offsets indicating too many parts + offsets3 = np.array([0, 3]) + with pytest.raises( + ValueError, match="Number of geometry parts indicated by the geometry offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_set_operations.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_set_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..09144fdf816993efea196b8002f363ae2db2c2cd --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_set_operations.py @@ -0,0 +1,481 @@ +import numpy as np +import pytest + +import shapely +from shapely import Geometry, GeometryCollection, Polygon +from shapely.testing import assert_geometries_equal +from shapely.tests.common import all_types, empty, ignore_invalid, point, polygon + +pytestmark = pytest.mark.filterwarnings( + "ignore:The symmetric_difference_all function:DeprecationWarning" +) + +# fixed-precision operations raise GEOS exceptions on mixed dimension geometry +# collections +all_single_types = np.array(all_types)[ + ~shapely.is_empty(all_types) + & (shapely.get_type_id(all_types) != shapely.GeometryType.GEOMETRYCOLLECTION) +] + +SET_OPERATIONS = ( + shapely.difference, + shapely.intersection, + shapely.symmetric_difference, + shapely.union, + # shapely.coverage_union is tested separately +) + +REDUCE_SET_OPERATIONS = ( + (shapely.intersection_all, shapely.intersection), + (shapely.symmetric_difference_all, shapely.symmetric_difference), + (shapely.union_all, shapely.union), + # shapely.coverage_union_all, shapely.coverage_union) is tested separately +) + +# operations that support fixed precision +REDUCE_SET_OPERATIONS_PREC = ((shapely.union_all, shapely.union),) + +if shapely.geos_version >= (3, 12, 0): + SET_OPERATIONS += (shapely.disjoint_subset_union,) + REDUCE_SET_OPERATIONS += ( + (shapely.disjoint_subset_union_all, shapely.disjoint_subset_union), + ) + +reduce_test_data = [ + shapely.box(0, 0, 5, 5), + shapely.box(2, 2, 7, 7), + shapely.box(4, 4, 9, 9), + shapely.box(5, 5, 10, 10), +] + +non_polygon_types = np.array(all_types)[ + ~shapely.is_empty(all_types) & (shapely.get_dimensions(all_types) != 2) +] + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func", SET_OPERATIONS) +def test_set_operation_array(a, func): + if ( + func is shapely.difference + and a.geom_type == "GeometryCollection" + and shapely.get_num_geometries(a) == 2 + and shapely.geos_version == (3, 9, 5) + ): + pytest.xfail("GEOS 3.9.5 crashes with mixed collection") + actual = func(a, point) + assert isinstance(actual, Geometry) + + actual = func([a, a], point) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + +@pytest.mark.parametrize("func", SET_OPERATIONS) +def test_set_operation_prec_nonscalar_grid_size(func): + if func is shapely.disjoint_subset_union: + pytest.skip("disjoint_subset_union does not support grid_size") + with pytest.raises( + ValueError, match="grid_size parameter only accepts scalar values" + ): + func(point, point, grid_size=[1]) + + +@pytest.mark.parametrize("a", all_single_types) +@pytest.mark.parametrize("func", SET_OPERATIONS) +@pytest.mark.parametrize("grid_size", [0, 1, 2]) +def test_set_operation_prec_array(a, func, grid_size): + if func is shapely.disjoint_subset_union: + pytest.skip("disjoint_subset_union does not support grid_size") + actual = func([a, a], point, grid_size=grid_size) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + # results should match the operation when the precision is previously set + # to same grid_size + b = shapely.set_precision(a, grid_size=grid_size) + point2 = shapely.set_precision(point, grid_size=grid_size) + expected = func([b, b], point2) + + assert shapely.equals(shapely.normalize(actual), shapely.normalize(expected)).all() + + +@pytest.mark.parametrize("n", range(1, 5)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_1dim(n, func, related_func): + actual = func(reduce_test_data[:n]) + # perform the reduction in a python loop and compare + expected = reduce_test_data[0] + for i in range(1, n): + expected = related_func(expected, reduce_test_data[i]) + assert shapely.equals(actual, expected) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_single_geom(func, related_func): + geom = shapely.Point(1, 1) + actual = func([geom, None, None]) + assert shapely.equals(actual, geom) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_axis(func, related_func): + data = [[point] * 2] * 3 # shape = (3, 2) + actual = func(data, axis=None) # default + assert isinstance(actual, Geometry) # scalar output + actual = func(data, axis=0) + assert actual.shape == (2,) + actual = func(data, axis=1) + assert actual.shape == (3,) + actual = func(data, axis=-1) + assert actual.shape == (3,) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_empty(func, related_func): + assert func(np.empty((0,), dtype=object)) == empty + arr_empty_2D = np.empty((0, 2), dtype=object) + assert func(arr_empty_2D) == empty + assert func(arr_empty_2D, axis=0).tolist() == [empty] * 2 + assert func(arr_empty_2D, axis=1).tolist() == [] + + +@pytest.mark.parametrize("none_position", range(3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_one_none(func, related_func, none_position): + # API change: before, intersection_all and symmetric_difference_all returned + # None if any input geometry was None. + # The new behaviour is to ignore None values. + test_data = reduce_test_data[:2] + test_data.insert(none_position, None) + actual = func(test_data) + expected = related_func(reduce_test_data[0], reduce_test_data[1]) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("none_position", range(3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_two_none(func, related_func, none_position): + test_data = reduce_test_data[:2] + test_data.insert(none_position, None) + test_data.insert(none_position, None) + actual = func(test_data) + expected = related_func(reduce_test_data[0], reduce_test_data[1]) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_some_none_len2(func, related_func): + # in a previous implementation, this would take a different code path + # and return wrong result + assert func([empty, None]) == empty + + +@pytest.mark.parametrize("n", range(1, 3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_all_none(n, func, related_func): + assert_geometries_equal(func([None] * n), GeometryCollection([])) + + +@pytest.mark.parametrize("n", range(1, 3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_all_none_arr(n, func, related_func): + assert func([[None] * n] * 2, axis=1).tolist() == [empty, empty] + assert func([[None] * 2] * n, axis=0).tolist() == [empty, empty] + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_nonscalar_grid_size(func, related_func): + with pytest.raises( + ValueError, match="grid_size parameter only accepts scalar values" + ): + func([point, point], grid_size=[1]) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_grid_size_nan(func, related_func): + actual = func([point, point], grid_size=np.nan) + assert actual is None + + +@pytest.mark.parametrize("n", range(1, 5)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +@pytest.mark.parametrize("grid_size", [0, 1]) +def test_set_operation_prec_reduce_1dim(n, func, related_func, grid_size): + actual = func(reduce_test_data[:n], grid_size=grid_size) + # perform the reduction in a python loop and compare + expected = reduce_test_data[0] + for i in range(1, n): + expected = related_func(expected, reduce_test_data[i], grid_size=grid_size) + + assert shapely.equals(actual, expected) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_axis(func, related_func): + data = [[point] * 2] * 3 # shape = (3, 2) + actual = func(data, grid_size=1, axis=None) # default + assert isinstance(actual, Geometry) # scalar output + actual = func(data, grid_size=1, axis=0) + assert actual.shape == (2,) + actual = func(data, grid_size=1, axis=1) + assert actual.shape == (3,) + actual = func(data, grid_size=1, axis=-1) + assert actual.shape == (3,) + + +@pytest.mark.parametrize("none_position", range(3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_one_none(func, related_func, none_position): + test_data = reduce_test_data[:2] + test_data.insert(none_position, None) + actual = func(test_data, grid_size=1) + expected = related_func(reduce_test_data[0], reduce_test_data[1], grid_size=1) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("none_position", range(3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_two_none(func, related_func, none_position): + test_data = reduce_test_data[:2] + test_data.insert(none_position, None) + test_data.insert(none_position, None) + actual = func(test_data, grid_size=1) + expected = related_func(reduce_test_data[0], reduce_test_data[1], grid_size=1) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("n", range(1, 3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_all_none(n, func, related_func): + assert_geometries_equal(func([None] * n, grid_size=1), GeometryCollection([])) + + +@pytest.mark.parametrize("n", range(1, 4)) +def test_coverage_union_reduce_1dim(n): + """ + This is tested separately from other set operations as it expects only + non-overlapping polygons + """ + test_data = [ + shapely.box(0, 0, 1, 1), + shapely.box(1, 0, 2, 1), + shapely.box(2, 0, 3, 1), + ] + actual = shapely.coverage_union_all(test_data[:n]) + # perform the reduction in a python loop and compare + expected = test_data[0] + for i in range(1, n): + expected = shapely.coverage_union(expected, test_data[i]) + assert_geometries_equal(actual, expected, normalize=True) + + +def test_coverage_union_reduce_axis(): + # shape = (3, 2), all polygons - none of them overlapping + data = [[shapely.box(i, j, i + 1, j + 1) for i in range(2)] for j in range(3)] + actual = shapely.coverage_union_all(data, axis=None) # default + assert isinstance(actual, Geometry) + actual = shapely.coverage_union_all(data, axis=0) + assert actual.shape == (2,) + actual = shapely.coverage_union_all(data, axis=1) + assert actual.shape == (3,) + actual = shapely.coverage_union_all(data, axis=-1) + assert actual.shape == (3,) + + +def test_coverage_union_overlapping_inputs(): + polygon = Polygon([(1, 1), (1, 0), (0, 0), (0, 1), (1, 1)]) + other = Polygon([(1, 0), (0.9, 1), (2, 1), (2, 0), (1, 0)]) + + if shapely.geos_version >= (3, 14, 0): + # Overlapping polygons raise an error again + with pytest.raises(shapely.GEOSException, match="TopologyException"): + shapely.coverage_union(polygon, other) + elif shapely.geos_version >= (3, 12, 0): + # Return mostly unchanged output + result = shapely.coverage_union(polygon, other) + expected = shapely.multipolygons([polygon, other]) + assert_geometries_equal(result, expected, normalize=True) + else: + # Overlapping polygons raise an error + with pytest.raises( + shapely.GEOSException, + match="CoverageUnion cannot process incorrectly noded inputs.", + ): + shapely.coverage_union(polygon, other) + + +@pytest.mark.parametrize( + "geom_1, geom_2", + # All possible polygon, non_polygon combinations + [[polygon, non_polygon] for non_polygon in non_polygon_types] + # All possible non_polygon, non_polygon combinations + + [ + [non_polygon_1, non_polygon_2] + for non_polygon_1 in non_polygon_types + for non_polygon_2 in non_polygon_types + ], +) +def test_coverage_union_non_polygon_inputs(geom_1, geom_2): + if shapely.geos_version >= (3, 12, 0): + + def effective_geom_types(geom): + if hasattr(geom, "geoms") and not geom.is_empty: + gts = set() + for part in geom.geoms: + gts |= effective_geom_types(part) + return gts + return {geom.geom_type.lstrip("Multi").replace("LinearRing", "LineString")} + + geom_types_1 = effective_geom_types(geom_1) + geom_types_2 = effective_geom_types(geom_2) + if len(geom_types_1) == 1 and geom_types_1 == geom_types_2: + with ignore_invalid(): + # these show "invalid value encountered in coverage_union" + result = shapely.coverage_union(geom_1, geom_2) + assert geom_types_1 == effective_geom_types(result) + else: + with pytest.raises( + shapely.GEOSException, match="Overlay input is mixed-dimension" + ): + shapely.coverage_union(geom_1, geom_2) + else: + # Non polygon geometries raise an error + with pytest.raises( + shapely.GEOSException, match="Unhandled geometry type in CoverageUnion." + ): + shapely.coverage_union(geom_1, geom_2) + + +@pytest.mark.parametrize( + "geom,grid_size,expected", + [ + # floating point precision, expect no change + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 0, + Polygon( + ( + (0, 0.2), + (0, 10), + (5.1, 10), + (5.1, 0.2), + (5, 0.2), + (5, 0.1), + (0.1, 0.1), + (0.1, 0.2), + (0, 0.2), + ) + ), + ), + # grid_size is at effective precision, expect no change + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 0.1, + Polygon( + ( + (0, 0.2), + (0, 10), + (5.1, 10), + (5.1, 0.2), + (5, 0.2), + (5, 0.1), + (0.1, 0.1), + (0.1, 0.2), + (0, 0.2), + ) + ), + ), + # grid_size forces rounding to nearest integer + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 1, + Polygon([(0, 5), (0, 10), (5, 10), (5, 5), (5, 0), (0, 0), (0, 5)]), + ), + # grid_size much larger than effective precision causes rounding to nearest + # multiple of 10 + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 10, + Polygon([(0, 10), (10, 10), (10, 0), (0, 0), (0, 10)]), + ), + # grid_size is so large that polygons collapse to empty + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 100, + Polygon(), + ), + ], +) +def test_union_all_prec(geom, grid_size, expected): + actual = shapely.union_all(geom, grid_size=grid_size) + assert shapely.equals(actual, expected) + + +def test_uary_union_alias(): + geoms = [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)] + actual = shapely.unary_union(geoms, grid_size=1) + expected = shapely.union_all(geoms, grid_size=1) + assert shapely.equals(actual, expected) + + +def test_difference_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `difference` is deprecated" + ): + shapely.difference(point, point, None) + + +def test_intersection_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `intersection` is deprecated" + ): + shapely.intersection(point, point, None) + + +def test_intersection_all_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `axis` for `intersection_all` is deprecated" + ): + shapely.intersection_all([point, point], None) + + +def test_symmetric_difference_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `symmetric_difference` is deprecated" + ): + shapely.symmetric_difference(point, point, None) + + +def test_symmetric_difference_all_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `axis` for `symmetric_difference_all` is deprecated" + ): + shapely.symmetric_difference_all([point, point], None) + + +def test_union_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `union` is deprecated" + ): + shapely.union(point, point, None) + + +def test_union_all_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `union_all` is deprecated" + ): + shapely.union_all([point, point], None) + with pytest.deprecated_call( + match="positional arguments `grid_size` and `axis` for `union_all` " + "are deprecated" + ): + shapely.union_all([point, point], None, None) + + +def test_coverage_union_all_deprecate_positional(): + data = [shapely.box(0, 0, 1, 1), shapely.box(1, 0, 2, 1)] + with pytest.deprecated_call( + match="positional argument `axis` for `coverage_union_all` is deprecated" + ): + shapely.coverage_union_all(data, None) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_strtree.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_strtree.py new file mode 100644 index 0000000000000000000000000000000000000000..991191717bad108dc3fa77d684b76cbe580288bf --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_strtree.py @@ -0,0 +1,1964 @@ +import itertools +import math +import pickle +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import shapely +from shapely import LineString, MultiPoint, Point, STRtree, box, geos_version +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + empty, + empty_line_string, + empty_point, + ignore_invalid, + point, +) + +# the distance between 2 points spaced at whole numbers along a diagonal +HALF_UNIT_DIAG = math.sqrt(2) / 2 +EPS = 1e-9 + + +@pytest.fixture(scope="session") +def tree(): + geoms = shapely.points(np.arange(10), np.arange(10)) + yield STRtree(geoms) + + +@pytest.fixture(scope="session") +def line_tree(): + x = np.arange(10) + y = np.arange(10) + offset = 1 + geoms = shapely.linestrings(np.array([[x, x + offset], [y, y + offset]]).T) + yield STRtree(geoms) + + +@pytest.fixture(scope="session") +def poly_tree(): + # create buffers so that midpoint between two buffers intersects + # each buffer. NOTE: add EPS to help mitigate rounding errors at midpoint. + geoms = shapely.buffer( + shapely.points(np.arange(10), np.arange(10)), HALF_UNIT_DIAG + EPS, quad_segs=32 + ) + yield STRtree(geoms) + + +@pytest.mark.parametrize( + "geometry,count, hits", + [ + # Empty array produces empty tree + ([], 0, 0), + ([point], 1, 1), + # None geometries are ignored when creating tree + ([None], 0, 0), + ([point, None], 1, 1), + # empty geometries are ignored when creating tree + ([empty, empty_point, empty_line_string], 0, 0), + # only the valid geometry should have a hit + ([empty, point, empty_point, empty_line_string], 1, 1), + ], +) +def test_init(geometry, count, hits): + tree = STRtree(geometry) + assert len(tree) == count + assert tree.query(box(0, 0, 100, 100)).size == hits + + +def test_init_with_invalid_geometry(): + with pytest.raises(TypeError): + STRtree(["Not a geometry"]) + + +def test_references(): + point1 = Point() + point2 = Point(0, 1) + + geoms = [point1, point2] + tree = STRtree(geoms) + + point1 = None + point2 = None + + import gc + + gc.collect() + + # query after freeing geometries does not lead to segfault + assert tree.query(box(0, 0, 1, 1)).tolist() == [1] + + +def test_flush_geometries(): + arr = shapely.points(np.arange(10), np.arange(10)) + tree = STRtree(arr) + + # Dereference geometries + arr[:] = None + import gc + + gc.collect() + # Still it does not lead to a segfault + tree.query(point) + + +def test_geometries_property(): + arr = np.array([point]) + tree = STRtree(arr) + assert_geometries_equal(arr, tree.geometries) + + # modifying elements of input should not modify tree.geometries + arr[0] = shapely.Point(0, 0) + assert_geometries_equal(point, tree.geometries[0]) + + +def test_pickle_persistence(tmp_path): + # write the pickeled tree to another process; the process should not crash + tree = STRtree([Point(i, i).buffer(0.1) for i in range(3)]) + + pickled_strtree = pickle.dumps(tree) + unpickle_script = """ +import pickle +import sys + +from shapely import Point + +pickled_strtree = sys.stdin.buffer.read() +print("received pickled strtree:", repr(pickled_strtree)) +tree = pickle.loads(pickled_strtree) + +tree.query(Point(0, 0)) +tree.nearest(Point(0, 0)) +print("done") +""" + + filename = tmp_path / "unpickle-strtree.py" + with open(filename, "w") as out: + out.write(unpickle_script) + + proc = subprocess.Popen( + [sys.executable, str(filename)], + stdin=subprocess.PIPE, + ) + proc.communicate(input=pickled_strtree) + proc.wait() + assert proc.returncode == 0 + + +@pytest.mark.parametrize( + "geometry", + [ + "I am not a geometry", + ["I am not a geometry"], + [Point(0, 0), "still not a geometry"], + [[], "in a mixed array", 1], + ], +) +@pytest.mark.filterwarnings("ignore:Creating an ndarray from ragged nested sequences:") +def test_query_invalid_geometry(tree, geometry): + with pytest.raises((TypeError, ValueError)): + tree.query(geometry) + + +def test_query_invalid_dimension(tree): + with pytest.raises(TypeError, match="Array should be one dimensional"): + tree.query([[Point(0.5, 0.5)]]) + + +@pytest.mark.parametrize( + "tree_geometry, geometry,expected", + [ + # Empty tree returns no results + ([], point, []), + ([], [point], [[], []]), + ([], None, []), + ([], [None], [[], []]), + # Tree with only None returns no results + ([None], point, []), + ([None], [point], [[], []]), + ([None], None, []), + ([None], [None], [[], []]), + # querying with None returns no results + ([point], None, []), + ([point], [None], [[], []]), + # Empty is included in the tree, but ignored when querying the tree + ([empty], empty, []), + ([empty], [empty], [[], []]), + ([empty], point, []), + ([empty], [point], [[], []]), + ([point, empty], empty, []), + ([point, empty], [empty], [[], []]), + # None and empty are ignored in the tree, but the index of the valid + # geometry should be retained. + ([None, point], box(0, 0, 10, 10), [1]), + ([None, point], [box(0, 0, 10, 10)], [[0], [1]]), + ([None, empty, point], box(0, 0, 10, 10), [2]), + ([point, None, point], box(0, 0, 10, 10), [0, 2]), + ([point, None, point], [box(0, 0, 10, 10)], [[0, 0], [0, 2]]), + # Only the non-empty query geometry gets hits + ([empty, point], [empty, point], [[1], [1]]), + ( + [empty, empty_point, empty_line_string, point], + [empty, empty_point, empty_line_string, point], + [[3], [3]], + ), + ], +) +def test_query_with_none_and_empty(tree_geometry, geometry, expected): + tree = STRtree(tree_geometry) + assert_array_equal(tree.query(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # first and last points intersect + ( + [Point(1, 1), Point(-1, -1), Point(2, 2)], + [[0, 2], [1, 2]], + ), + # box contains points + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # bigger box contains more points + (box(5, 5, 15, 15), [5, 6, 7, 8, 9]), + ([box(5, 5, 15, 15)], [[0, 0, 0, 0, 0], [5, 6, 7, 8, 9]]), + # first and last boxes contains points + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(5, 5, 15, 15)], + [[0, 0, 2, 2, 2, 2, 2], [0, 1, 5, 6, 7, 8, 9]], + ), + # envelope of buffer contains points + (shapely.buffer(Point(3, 3), 1), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), 1)], [[0, 0, 0], [2, 3, 4]]), + # envelope of points contains points + (MultiPoint([[5, 7], [7, 5]]), [5, 6, 7]), + ([MultiPoint([[5, 7], [7, 5]])], [[0, 0, 0], [5, 6, 7]]), + ], +) +def test_query_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects first line + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # point within envelope of first line + (Point(0, 0.5), [0]), + ([Point(0, 0.5)], [[0], [0]]), + # point at shared vertex between 2 lines + (Point(1, 1), [0, 1]), + ([Point(1, 1)], [[0, 0], [0, 1]]), + # box overlaps envelope of first 2 lines (touches edge of 1) + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # envelope of buffer overlaps envelope of 2 lines + (shapely.buffer(Point(3, 3), 0.5), [2, 3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0, 0], [2, 3]]), + # envelope of points overlaps 5 lines (touches edge of 2 envelopes) + (MultiPoint([[5, 7], [7, 5]]), [4, 5, 6, 7]), + ([MultiPoint([[5, 7], [7, 5]])], [[0, 0, 0, 0], [4, 5, 6, 7]]), + ], +) +def test_query_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects edge of envelopes of 2 polygons + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # point intersects single polygon + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box overlaps envelope of 2 polygons + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # larger box overlaps envelope of 3 polygons + (box(0, 0, 1.5, 1.5), [0, 1, 2]), + ([box(0, 0, 1.5, 1.5)], [[0, 0, 0], [0, 1, 2]]), + # first and last boxes overlap envelope of 2 polyons + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(2, 2, 3, 3)], + [[0, 0, 2, 2], [0, 1, 2, 3]], + ), + # envelope of buffer overlaps envelope of 3 polygons + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3, 4]), + ( + [shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], + [[0, 0, 0], [2, 3, 4]], + ), + # envelope of larger buffer overlaps envelope of 6 polygons + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [1, 2, 3, 4, 5]), + ( + [shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], + [[0, 0, 0, 0, 0], [1, 2, 3, 4, 5]], + ), + # envelope of points overlaps 3 polygons + (MultiPoint([[5, 7], [7, 5]]), [5, 6, 7]), + ([MultiPoint([[5, 7], [7, 5]])], [[0, 0, 0], [5, 6, 7]]), + ], +) +def test_query_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry), expected) + + +@pytest.mark.parametrize( + "predicate", + [ + "bad_predicate", + # disjoint is a valid GEOS binary predicate, but not supported for query + "disjoint", + ], +) +def test_query_invalid_predicate(tree, predicate): + with pytest.raises(ValueError, match="is not a valid option"): + tree.query(Point(1, 1), predicate=predicate) + + +@pytest.mark.parametrize( + "predicate,expected", + [ + ("intersects", [0, 1, 2]), + ("within", []), + ("contains", [1]), + ("overlaps", []), + ("crosses", []), + ("covers", [0, 1, 2]), + ("covered_by", []), + ("contains_properly", [1]), + ], +) +def test_query_prepared_inputs(tree, predicate, expected): + geom = box(0, 0, 2, 2) + shapely.prepare(geom) + assert_array_equal(tree.query(geom, predicate=predicate), expected) + + +def test_query_with_partially_prepared_inputs(tree): + geom = np.array([box(0, 0, 1, 1), box(3, 3, 5, 5)]) + expected = tree.query(geom, predicate="intersects") + + # test with array of partially prepared geometries + shapely.prepare(geom[0]) + assert_array_equal(expected, tree.query(geom, predicate="intersects")) + + +@pytest.mark.parametrize( + "predicate,expected", + [ + pytest.param( + "intersects", + [1], + marks=pytest.mark.xfail(geos_version < (3, 13, 0), reason="GEOS < 3.13"), + ), + ("within", []), + ("contains", []), + ("overlaps", []), + ("crosses", [1]), + ("touches", []), + ("covers", []), + ("covered_by", []), + ("contains_properly", []), + ], +) +def test_query_predicate_errors(tree, predicate, expected): + with ignore_invalid(): + line_nan = shapely.linestrings([1, 1], [1, float("nan")]) + if geos_version < (3, 13, 0): + with pytest.raises(shapely.GEOSException): + tree.query(line_nan, predicate=predicate) + else: + assert_array_equal(tree.query(line_nan, predicate=predicate), expected) + + +### predicate == 'intersects' + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box contains points + (box(3, 3, 6, 6), [3, 4, 5, 6]), + ([box(3, 3, 6, 6)], [[0, 0, 0, 0], [3, 4, 5, 6]]), + # first and last boxes contain points + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(3, 3, 6, 6)], + [[0, 0, 2, 2, 2, 2], [0, 1, 3, 4, 5, 6]], + ), + # envelope of buffer contains more points than intersect buffer + # due to diagonal distance + (shapely.buffer(Point(3, 3), 1), [3]), + ([shapely.buffer(Point(3, 3), 1)], [[0], [3]]), + # envelope of buffer with 1/2 distance between points should intersect + # same points as envelope + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [2, 3, 4]), + ( + [shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], + [[0, 0, 0], [2, 3, 4]], + ), + # multipoints intersect + ( + MultiPoint([[5, 5], [7, 7]]), + [5, 7], + ), + ( + [MultiPoint([[5, 5], [7, 7]])], + [[0, 0], [5, 7]], + ), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + ( + MultiPoint([[5, 7], [7, 7]]), + [7], + ), + ( + [MultiPoint([[5, 7], [7, 7]])], + [[0], [7]], + ), + ], +) +def test_query_intersects_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="intersects"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects first line + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # point within envelope of first line but does not intersect + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # point at shared vertex between 2 lines + (Point(1, 1), [0, 1]), + ([Point(1, 1)], [[0, 0], [0, 1]]), + # box overlaps envelope of first 2 lines (touches edge of 1) + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # first and last boxes overlap multiple lines each + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(2, 2, 3, 3)], + [[0, 0, 2, 2, 2], [0, 1, 1, 2, 3]], + ), + # buffer intersects 2 lines + (shapely.buffer(Point(3, 3), 0.5), [2, 3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0, 0], [2, 3]]), + # buffer intersects midpoint of line at tangent + (shapely.buffer(Point(2, 1), HALF_UNIT_DIAG), [1]), + ([shapely.buffer(Point(2, 1), HALF_UNIT_DIAG)], [[0], [1]]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), [6, 7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0, 0], [6, 7]]), + ], +) +def test_query_intersects_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="intersects"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point within first polygon + (Point(0, 0.5), [0]), + ([Point(0, 0.5)], [[0], [0]]), + (Point(0.5, 0), [0]), + ([Point(0.5, 0)], [[0], [0]]), + # midpoint between two polygons intersects both + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # point intersects single polygon + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box overlaps envelope of 2 polygons + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # larger box intersects 3 polygons + (box(0, 0, 1.5, 1.5), [0, 1, 2]), + ([box(0, 0, 1.5, 1.5)], [[0, 0, 0], [0, 1, 2]]), + # first and last boxes overlap + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(2, 2, 3, 3)], + [[0, 0, 2, 2], [0, 1, 2, 3]], + ), + # buffer overlaps 3 polygons + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3, 4]), + ( + [shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], + [[0, 0, 0], [2, 3, 4]], + ), + # larger buffer overlaps 6 polygons (touches midpoints) + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [1, 2, 3, 4, 5]), + ( + [shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], + [[0, 0, 0, 0, 0], [1, 2, 3, 4, 5]], + ), + # envelope of points overlaps polygons, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint within polygon + (MultiPoint([[5, 7], [7, 7]]), [7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0], [7]]), + ], +) +def test_query_intersects_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="intersects"), expected) + + +### predicate == 'within' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box not within points + (box(3, 3, 6, 6), []), + ([box(3, 3, 6, 6)], [[], []]), + # envelope of buffer not within points + (shapely.buffer(Point(3, 3), 1), []), + ([shapely.buffer(Point(3, 3), 1)], [[], []]), + # multipoints intersect but are not within points in tree + (MultiPoint([[5, 5], [7, 7]]), []), + ([MultiPoint([[5, 5], [7, 7]])], [[], []]), + # only one point of multipoint intersects, but multipoints are not + # within any points in tree + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_within_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="within"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # endpoint not within first line + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # point within first line + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # point within envelope of first line but does not intersect + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # point at shared vertex between 2 lines (but within neither) + (Point(1, 1), []), + ([Point(1, 1)], [[], []]), + # box not within line + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # buffer intersects 2 lines but not within either + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects, but both are not within line + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + (MultiPoint([[6.5, 6.5], [7, 7]]), [6]), + ([MultiPoint([[6.5, 6.5], [7, 7]])], [[0], [6]]), + ], +) +def test_query_within_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="within"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point within first polygon + (Point(0, 0.5), [0]), + ([Point(0, 0.5)], [[0], [0]]), + (Point(0.5, 0), [0]), + ([Point(0.5, 0)], [[0], [0]]), + # midpoint between two polygons intersects both + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # point intersects single polygon + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box overlaps envelope of 2 polygons but within neither + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # box within polygon + (box(0, 0, 0.5, 0.5), [0]), + ([box(0, 0, 0.5, 0.5)], [[0], [0]]), + # larger box intersects 3 polygons but within none + (box(0, 0, 1.5, 1.5), []), + ([box(0, 0, 1.5, 1.5)], [[], []]), + # buffer intersects 3 polygons but only within one + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[0], [3]]), + # larger buffer overlaps 6 polygons (touches midpoints) but within none + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[], []]), + # envelope of points overlaps polygons, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint within polygon + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points in multipoint within polygon + (MultiPoint([[5.25, 5.5], [5.25, 5.0]]), [5]), + ([MultiPoint([[5.25, 5.5], [5.25, 5.0]])], [[0], [5]]), + ], +) +def test_query_within_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="within"), expected) + + +### predicate == 'contains' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box contains points (2 are at edges and not contained) + (box(3, 3, 6, 6), [4, 5]), + ([box(3, 3, 6, 6)], [[0, 0], [4, 5]]), + # envelope of buffer contains more points than within buffer + # due to diagonal distance + (shapely.buffer(Point(3, 3), 1), [3]), + ([shapely.buffer(Point(3, 3), 1)], [[0], [3]]), + # envelope of buffer with 1/2 distance between points should intersect + # same points as envelope + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0, 0, 0], [2, 3, 4]]), + # multipoints intersect + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), [7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0], [7]]), + ], +) +def test_query_contains_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="contains"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not contain any lines (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box contains first line (touches edge of 1 but does not contain it) + (box(0, 0, 1, 1), [0]), + ([box(0, 0, 1, 1)], [[0], [0]]), + # buffer intersects 2 lines but contains neither + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points intersect but do not contain any lines (not valid relation) + (MultiPoint([[5, 5], [6, 6]]), []), + ([MultiPoint([[5, 5], [6, 6]])], [[], []]), + ], +) +def test_query_contains_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="contains"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not contain any polygons (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps envelope of 2 polygons but contains neither + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # larger box intersects 3 polygons but contains only one + (box(0, 0, 2, 2), [1]), + ([box(0, 0, 2, 2)], [[0], [1]]), + # buffer overlaps 3 polygons but contains none + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[], []]), + # larger buffer overlaps 6 polygons (touches midpoints) but contains one + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0], [3]]), + # envelope of points overlaps polygons, but points do not intersect + # (not valid relation) + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_contains_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="contains"), expected) + + +### predicate == 'overlaps' +# Overlaps only returns results where geometries are of same dimensions +# and do not completely contain each other. +# See: https://postgis.net/docs/ST_Overlaps.html +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect but do not overlap + (Point(1, 1), []), + ([Point(1, 1)], [[], []]), + # box overlaps points including those at edge but does not overlap + # (completely contains all points) + (box(3, 3, 6, 6), []), + ([box(3, 3, 6, 6)], [[], []]), + # envelope of buffer contains points, but does not overlap + (shapely.buffer(Point(3, 3), 1), []), + ([shapely.buffer(Point(3, 3), 1)], [[], []]), + # multipoints intersect but do not overlap (both completely contain each other) + (MultiPoint([[5, 5], [7, 7]]), []), + ([MultiPoint([[5, 5], [7, 7]])], [[], []]), + # envelope of points contains points in tree, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects but does not overlap + # the intersecting point from multipoint completely contains point in tree + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + ], +) +def test_query_overlaps_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="overlaps"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects line but is completely contained by it + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps second line (contains first line) + # but of different dimensions so does not overlap + (box(0, 0, 1.5, 1.5), []), + ([box(0, 0, 1.5, 1.5)], [[], []]), + # buffer intersects 2 lines but of different dimensions so does not overlap + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points intersect but different dimensions + (MultiPoint([[5, 5], [6, 6]]), []), + ([MultiPoint([[5, 5], [6, 6]])], [[], []]), + ], +) +def test_query_overlaps_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="overlaps"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not overlap any polygons (different dimensions) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps 2 polygons + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # larger box intersects 3 polygons and contains one + (box(0, 0, 2, 2), [0, 2]), + ([box(0, 0, 2, 2)], [[0, 0], [0, 2]]), + # buffer overlaps 3 polygons and contains 1 + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 4]), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[0, 0], [2, 4]]), + # larger buffer overlaps 6 polygons (touches midpoints) but contains one + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [1, 2, 4, 5]), + ( + [shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], + [[0, 0, 0, 0], [1, 2, 4, 5]], + ), + # one of two points intersects but different dimensions + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + ], +) +def test_query_overlaps_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="overlaps"), expected) + + +### predicate == 'crosses' +# Only valid for certain geometry combinations +# See: https://postgis.net/docs/ST_Crosses.html +@pytest.mark.parametrize( + "geometry,expected", + [ + # points intersect but not valid relation + (Point(1, 1), []), + # all points of result from tree are in common with box + (box(3, 3, 6, 6), []), + # all points of result from tree are in common with buffer + (shapely.buffer(Point(3, 3), 1), []), + # only one point of multipoint intersects but not valid relation + (MultiPoint([[5, 7], [7, 7]]), []), + ], +) +def test_query_crosses_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="crosses"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects first line but is completely in common with line + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps envelope of first 2 lines, contains first and crosses second + (box(0, 0, 1.5, 1.5), [1]), + ([box(0, 0, 1.5, 1.5)], [[0], [1]]), + # buffer intersects 2 lines + (shapely.buffer(Point(3, 3), 0.5), [2, 3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0, 0], [2, 3]]), + # line crosses line + (shapely.linestrings([(1, 0), (0, 1)]), [0]), + ([shapely.linestrings([(1, 0), (0, 1)])], [[0], [0]]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7], [7, 8]]), []), + ([MultiPoint([[5, 7], [7, 7], [7, 8]])], [[], []]), + ], +) +def test_query_crosses_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="crosses"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point within first polygon but not valid relation + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # box overlaps 2 polygons but not valid relation + (box(0, 0, 1.5, 1.5), []), + ([box(0, 0, 1.5, 1.5)], [[], []]), + # buffer overlaps 3 polygons but not valid relation + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[], []]), + # only one point of multipoint within + (MultiPoint([[5, 7], [7, 7], [7, 8]]), [7]), + ([MultiPoint([[5, 7], [7, 7], [7, 8]])], [[0], [7]]), + ], +) +def test_query_crosses_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="crosses"), expected) + + +### predicate == 'touches' +# See: https://postgis.net/docs/ST_Touches.html +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect but not valid relation + (Point(1, 1), []), + ([Point(1, 1)], [[], []]), + # box contains points but touches only those at edges + (box(3, 3, 6, 6), [3, 6]), + ([box(3, 3, 6, 6)], [[0, 0], [3, 6]]), + # polygon completely contains point in tree + (shapely.buffer(Point(3, 3), 1), []), + ([shapely.buffer(Point(3, 3), 1)], [[], []]), + # linestring intersects 2 points but touches only one + (LineString([(-1, -1), (1, 1)]), [1]), + ([LineString([(-1, -1), (1, 1)])], [[0], [1]]), + # multipoints intersect but not valid relation + (MultiPoint([[5, 5], [7, 7]]), []), + ([MultiPoint([[5, 5], [7, 7]])], [[], []]), + ], +) +def test_query_touches_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="touches"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects first line + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + # point is within line + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # point at shared vertex between 2 lines + (Point(1, 1), [0, 1]), + ([Point(1, 1)], [[0, 0], [0, 1]]), + # box overlaps envelope of first 2 lines (touches edge of 1) + (box(0, 0, 1, 1), [1]), + ([box(0, 0, 1, 1)], [[0], [1]]), + # buffer intersects 2 lines but does not touch edges of either + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # buffer intersects midpoint of line at tangent but there is a little overlap + # due to precision issues + (shapely.buffer(Point(2, 1), HALF_UNIT_DIAG + 1e-7), []), + ([shapely.buffer(Point(2, 1), HALF_UNIT_DIAG + 1e-7)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects at vertex between lines + (MultiPoint([[5, 7], [7, 7], [7, 8]]), [6, 7]), + ([MultiPoint([[5, 7], [7, 7], [7, 8]])], [[0, 0], [6, 7]]), + ], +) +def test_query_touches_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="touches"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point within first polygon + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # point is at edge of first polygon + (Point(HALF_UNIT_DIAG + EPS, 0), [0]), + ([Point(HALF_UNIT_DIAG + EPS, 0)], [[0], [0]]), + # box overlaps envelope of 2 polygons does not touch any at edge + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # box overlaps 2 polygons and touches edge of first + (box(HALF_UNIT_DIAG + EPS, 0, 2, 2), [0]), + ([box(HALF_UNIT_DIAG + EPS, 0, 2, 2)], [[0], [0]]), + # buffer overlaps 3 polygons but does not touch any at edge + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG + EPS), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG + EPS)], [[], []]), + # only one point of multipoint within polygon but does not touch + (MultiPoint([[0, 0], [7, 7], [7, 8]]), []), + ([MultiPoint([[0, 0], [7, 7], [7, 8]])], [[], []]), + ], +) +def test_query_touches_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="touches"), expected) + + +### predicate == 'covers' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect and thus no point is outside the other + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box covers any points that intersect or are within + (box(3, 3, 6, 6), [3, 4, 5, 6]), + ([box(3, 3, 6, 6)], [[0, 0, 0, 0], [3, 4, 5, 6]]), + # envelope of buffer covers more points than are covered by buffer + # due to diagonal distance + (shapely.buffer(Point(3, 3), 1), [3]), + ([shapely.buffer(Point(3, 3), 1)], [[0], [3]]), + # envelope of buffer with 1/2 distance between points should intersect + # same points as envelope + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0, 0, 0], [2, 3, 4]]), + # multipoints intersect and thus no point is outside the other + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), [7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0], [7]]), + ], +) +def test_query_covers_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="covers"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not cover any lines (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box covers first line (intersects another does not contain it) + (box(0, 0, 1.5, 1.5), [0]), + ([box(0, 0, 1.5, 1.5)], [[0], [0]]), + # box completely covers 2 lines (touches edges of 2 others) + (box(1, 1, 3, 3), [1, 2]), + ([box(1, 1, 3, 3)], [[0, 0], [1, 2]]), + # buffer intersects 2 lines but does not completely cover either + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects a line, but does not completely cover + # it + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points intersect but do not cover any lines (not valid relation) + (MultiPoint([[5, 5], [6, 6]]), []), + ([MultiPoint([[5, 5], [6, 6]])], [[], []]), + ], +) +def test_query_covers_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="covers"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not cover any polygons (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps envelope of 2 polygons but does not completely cover either + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # larger box intersects 3 polygons but covers only one + (box(0, 0, 2, 2), [1]), + ([box(0, 0, 2, 2)], [[0], [1]]), + # buffer overlaps 3 polygons but does not completely cover any + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[], []]), + # larger buffer overlaps 6 polygons (touches midpoints) but covers only one + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0], [3]]), + # envelope of points overlaps polygons, but points do not intersect + # (not valid relation) + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_covers_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="covers"), expected) + + +### predicate == 'covered_by' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box not covered by points + (box(3, 3, 6, 6), []), + ([box(3, 3, 6, 6)], [[], []]), + # envelope of buffer not covered by points + (shapely.buffer(Point(3, 3), 1), []), + ([shapely.buffer(Point(3, 3), 1)], [[], []]), + # multipoints intersect but are not covered by points in tree + (MultiPoint([[5, 5], [7, 7]]), []), + ([MultiPoint([[5, 5], [7, 7]])], [[], []]), + # only one point of multipoint intersects, but multipoints are not + # covered by any points in tree + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # envelope of points overlaps points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_covered_by_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="covered_by"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # endpoint is covered by first line + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + # point covered by first line + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # point within envelope of first line but does not intersect + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # point at shared vertex between 2 lines and is covered by both + (Point(1, 1), [0, 1]), + ([Point(1, 1)], [[0, 0], [0, 1]]), + # line intersects 3 lines, but is covered by only one + (shapely.linestrings([[1, 1], [2, 2]]), [1]), + ([shapely.linestrings([[1, 1], [2, 2]])], [[0], [1]]), + # line intersects 2 lines, but is covered by neither + (shapely.linestrings([[1.5, 1.5], [2.5, 2.5]]), []), + ([shapely.linestrings([[1.5, 1.5], [2.5, 2.5]])], [[], []]), + # box not covered by line (not valid geometric relation) + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # buffer intersects 2 lines but not within either (not valid geometric relation) + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects, but both are not covered by line + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points are covered by a line + (MultiPoint([[6.5, 6.5], [7, 7]]), [6]), + ([MultiPoint([[6.5, 6.5], [7, 7]])], [[0], [6]]), + ], +) +def test_query_covered_by_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="covered_by"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point covered by polygon + (Point(0, 0.5), [0]), + ([Point(0, 0.5)], [[0], [0]]), + (Point(0.5, 0), [0]), + ([Point(0.5, 0)], [[0], [0]]), + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # midpoint between two polygons is covered by both + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # line intersects multiple polygons but is not covered by any + (shapely.linestrings([[0, 0], [2, 2]]), []), + ([shapely.linestrings([[0, 0], [2, 2]])], [[], []]), + # line intersects multiple polygons but is covered by only one + (shapely.linestrings([[1.5, 1.5], [2.5, 2.5]]), [2]), + ([shapely.linestrings([[1.5, 1.5], [2.5, 2.5]])], [[0], [2]]), + # box overlaps envelope of 2 polygons but not covered by either + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # box covered by polygon + (box(0, 0, 0.5, 0.5), [0]), + ([box(0, 0, 0.5, 0.5)], [[0], [0]]), + # larger box intersects 3 polygons but not covered by any + (box(0, 0, 1.5, 1.5), []), + ([box(0, 0, 1.5, 1.5)], [[], []]), + # buffer intersects 3 polygons but only within one + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[0], [3]]), + # larger buffer overlaps 6 polygons (touches midpoints) but within none + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[], []]), + # envelope of points overlaps polygons, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint within polygon + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points in multipoint within polygon + (MultiPoint([[5.25, 5.5], [5.25, 5.0]]), [5]), + ([MultiPoint([[5.25, 5.5], [5.25, 5.0]])], [[0], [5]]), + ], +) +def test_query_covered_by_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="covered_by"), expected) + + +### predicate == 'contains_properly' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # line contains every point that is not on its first or last coordinate + # these are on the "exterior" of the line + (shapely.linestrings([[0, 0], [2, 2]]), [1]), + ([shapely.linestrings([[0, 0], [2, 2]])], [[0], [1]]), + # slightly longer line contains multiple points + (shapely.linestrings([[0.5, 0.5], [2.5, 2.5]]), [1, 2]), + ([shapely.linestrings([[0.5, 0.5], [2.5, 2.5]])], [[0, 0], [1, 2]]), + # line intersects and contains one point + (shapely.linestrings([[0, 2], [2, 0]]), [1]), + ([shapely.linestrings([[0, 2], [2, 0]])], [[0], [1]]), + # box contains points (2 are at edges and not contained) + (box(3, 3, 6, 6), [4, 5]), + ([box(3, 3, 6, 6)], [[0, 0], [4, 5]]), + # envelope of buffer contains more points than within buffer + # due to diagonal distance + (shapely.buffer(Point(3, 3), 1), [3]), + ([shapely.buffer(Point(3, 3), 1)], [[0], [3]]), + # envelope of buffer with 1/2 distance between points should intersect + # same points as envelope + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0, 0, 0], [2, 3, 4]]), + # multipoints intersect + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), [7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0], [7]]), + ], +) +def test_query_contains_properly_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="contains_properly"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # None of the following conditions satisfy the relation for linestrings + # because they have no interior: + # "a contains b if no points of b lie in the exterior of a, and at least one + # point of the interior of b lies in the interior of a" + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + (shapely.linestrings([[0, 0], [1, 1]]), []), + ([shapely.linestrings([[0, 0], [1, 1]])], [[], []]), + (shapely.linestrings([[0, 0], [2, 2]]), []), + ([shapely.linestrings([[0, 0], [2, 2]])], [[], []]), + (shapely.linestrings([[0, 2], [2, 0]]), []), + ([shapely.linestrings([[0, 2], [2, 0]])], [[], []]), + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + (MultiPoint([[5, 5], [6, 6]]), []), + ([MultiPoint([[5, 5], [6, 6]])], [[], []]), + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + (box(0, 0, 2, 2), []), + ([box(0, 0, 2, 2)], [[], []]), + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + ], +) +def test_query_contains_properly_lines(line_tree, geometry, expected): + assert_array_equal( + line_tree.query(geometry, predicate="contains_properly"), expected + ) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not contain any polygons (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # line intersects multiple polygons but does not contain any (not valid + # relation) + (shapely.linestrings([[0, 0], [2, 2]]), []), + ([shapely.linestrings([[0, 0], [2, 2]])], [[], []]), + # box overlaps envelope of 2 polygons but contains neither + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # larger box intersects 3 polygons but contains only one + (box(0, 0, 2, 2), [1]), + ([box(0, 0, 2, 2)], [[0], [1]]), + # buffer overlaps 3 polygons but contains none + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[], []]), + # larger buffer overlaps 6 polygons (touches midpoints) but contains one + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0], [3]]), + # envelope of points overlaps polygons, but points do not intersect + # (not valid relation) + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_contains_properly_polygons(poly_tree, geometry, expected): + assert_array_equal( + poly_tree.query(geometry, predicate="contains_properly"), expected + ) + + +### predicate = 'dwithin' + + +@pytest.mark.skipif(geos_version >= (3, 10, 0), reason="GEOS >= 3.10") +@pytest.mark.parametrize( + "geometry", [Point(0, 0), [Point(0, 0)], None, [None], empty, [empty]] +) +def test_query_dwithin_geos_version(tree, geometry): + with pytest.raises(UnsupportedGEOSVersionError, match="requires GEOS >= 3.10"): + tree.query(geometry, predicate="dwithin", distance=1) + + +@pytest.mark.skipif(geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,distance,match", + [ + (Point(0, 0), None, "distance parameter must be provided"), + ([Point(0, 0)], None, "distance parameter must be provided"), + (Point(0, 0), "foo", "could not convert string to float"), + ([Point(0, 0)], "foo", "could not convert string to float"), + ([Point(0, 0)], ["foo"], "could not convert string to float"), + (Point(0, 0), [0, 1], "Could not broadcast distance to match geometry"), + ([Point(0, 0)], [0, 1], "Could not broadcast distance to match geometry"), + (Point(0, 0), [[1.0]], "should be one dimensional"), + ([Point(0, 0)], [[1.0]], "should be one dimensional"), + ], +) +def test_query_dwithin_invalid_distance(tree, geometry, distance, match): + with pytest.raises(ValueError, match=match): + tree.query(geometry, predicate="dwithin", distance=distance) + + +@pytest.mark.skipif(geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,distance,expected", + [ + (None, 1.0, []), + ([None], 1.0, [[], []]), + (Point(0.25, 0.25), 0, []), + ([Point(0.25, 0.25)], 0, [[], []]), + (Point(0.25, 0.25), -1, []), + ([Point(0.25, 0.25)], -1, [[], []]), + (Point(0.25, 0.25), np.nan, []), + ([Point(0.25, 0.25)], np.nan, [[], []]), + (Point(), 1, []), + ([Point()], 1, [[], []]), + (Point(0.25, 0.25), 0.5, [0]), + ([Point(0.25, 0.25)], 0.5, [[0], [0]]), + (Point(0.25, 0.25), 2.5, [0, 1, 2]), + ([Point(0.25, 0.25)], 2.5, [[0, 0, 0], [0, 1, 2]]), + (Point(3, 3), 1.5, [2, 3, 4]), + ([Point(3, 3)], 1.5, [[0, 0, 0], [2, 3, 4]]), + # 2 equidistant points in tree + (Point(0.5, 0.5), 0.75, [0, 1]), + ([Point(0.5, 0.5)], 0.75, [[0, 0], [0, 1]]), + ( + [None, Point(0.5, 0.5)], + 0.75, + [ + [ + 1, + 1, + ], + [0, 1], + ], + ), + ( + [Point(0.5, 0.5), Point(0.25, 0.25)], + 0.75, + [[0, 0, 1], [0, 1, 0]], + ), + ( + [Point(0, 0.2), Point(1.75, 1.75)], + [0.25, 2], + [[0, 1, 1, 1], [0, 1, 2, 3]], + ), + # all points intersect box + (box(0, 0, 3, 3), 0, [0, 1, 2, 3]), + ([box(0, 0, 3, 3)], 0, [[0, 0, 0, 0], [0, 1, 2, 3]]), + (box(0, 0, 3, 3), 0.25, [0, 1, 2, 3]), + ([box(0, 0, 3, 3)], 0.25, [[0, 0, 0, 0], [0, 1, 2, 3]]), + # intersecting and nearby points + (box(1, 1, 2, 2), 1.5, [0, 1, 2, 3]), + ([box(1, 1, 2, 2)], 1.5, [[0, 0, 0, 0], [0, 1, 2, 3]]), + # # return nearest point in tree for each point in multipoint + (MultiPoint([[0.25, 0.25], [1.5, 1.5]]), 0.75, [0, 1, 2]), + ([MultiPoint([[0.25, 0.25], [1.5, 1.5]])], 0.75, [[0, 0, 0], [0, 1, 2]]), + # 2 equidistant points per point in multipoint + ( + MultiPoint([[0.5, 0.5], [3.5, 3.5]]), + 0.75, + [0, 1, 3, 4], + ), + ( + [MultiPoint([[0.5, 0.5], [3.5, 3.5]])], + 0.75, + [[0, 0, 0, 0], [0, 1, 3, 4]], + ), + ], +) +def test_query_dwithin_points(tree, geometry, distance, expected): + assert_array_equal( + tree.query(geometry, predicate="dwithin", distance=distance), expected + ) + + +@pytest.mark.skipif(geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,distance,expected", + [ + (None, 1.0, []), + ([None], 1.0, [[], []]), + (Point(0.5, 0.5), 0, [0]), + ([Point(0.5, 0.5)], 0, [[0], [0]]), + (Point(0.5, 0.5), 1.0, [0, 1]), + ([Point(0.5, 0.5)], 1.0, [[0, 0], [0, 1]]), + (Point(2, 2), 0.5, [1, 2]), + ([Point(2, 2)], 0.5, [[0, 0], [1, 2]]), + (box(0, 0, 1, 1), 0.5, [0, 1]), + ([box(0, 0, 1, 1)], 0.5, [[0, 0], [0, 1]]), + (box(0.5, 0.5, 1.5, 1.5), 0.5, [0, 1]), + ([box(0.5, 0.5, 1.5, 1.5)], 0.5, [[0, 0], [0, 1]]), + # multipoints at endpoints of 2 lines each + (MultiPoint([[5, 5], [7, 7]]), 0.5, [4, 5, 6, 7]), + ([MultiPoint([[5, 5], [7, 7]])], 0.5, [[0, 0, 0, 0], [4, 5, 6, 7]]), + # multipoints are equidistant from 2 lines + (MultiPoint([[5, 7], [7, 5]]), 1.5, [5, 6]), + ([MultiPoint([[5, 7], [7, 5]])], 1.5, [[0, 0], [5, 6]]), + ], +) +def test_query_dwithin_lines(line_tree, geometry, distance, expected): + assert_array_equal( + line_tree.query(geometry, predicate="dwithin", distance=distance), + expected, + ) + + +@pytest.mark.skipif(geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,distance,expected", + [ + (Point(0, 0), 0, [0]), + ([Point(0, 0)], 0, [[0], [0]]), + (Point(0, 0), 0.5, [0]), + ([Point(0, 0)], 0.5, [[0], [0]]), + (Point(0, 0), 1.5, [0, 1]), + ([Point(0, 0)], 1.5, [[0, 0], [0, 1]]), + (Point(0.5, 0.5), 1, [0, 1]), + ([Point(0.5, 0.5)], 1, [[0, 0], [0, 1]]), + (Point(0.5, 0.5), 0.5, [0, 1]), + ([Point(0.5, 0.5)], 0.5, [[0, 0], [0, 1]]), + (box(0, 0, 1, 1), 0, [0, 1]), + ([box(0, 0, 1, 1)], 0, [[0, 0], [0, 1]]), + (box(0, 0, 1, 1), 2, [0, 1, 2]), + ([box(0, 0, 1, 1)], 2, [[0, 0, 0], [0, 1, 2]]), + (MultiPoint([[5, 5], [7, 7]]), 0.5, [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], 0.5, [[0, 0], [5, 7]]), + ( + MultiPoint([[5, 5], [7, 7]]), + 2.5, + [3, 4, 5, 6, 7, 8, 9], + ), + ( + [MultiPoint([[5, 5], [7, 7]])], + 2.5, + [[0, 0, 0, 0, 0, 0, 0], [3, 4, 5, 6, 7, 8, 9]], + ), + ], +) +def test_query_dwithin_polygons(poly_tree, geometry, distance, expected): + assert_array_equal( + poly_tree.query(geometry, predicate="dwithin", distance=distance), + expected, + ) + + +### STRtree nearest + + +def test_nearest_empty_tree(): + tree = STRtree([]) + assert tree.nearest(point) is None + + +@pytest.mark.parametrize("geometry", ["I am not a geometry"]) +def test_nearest_invalid_geom(tree, geometry): + with pytest.raises(TypeError): + tree.nearest(geometry) + + +@pytest.mark.parametrize("geometry", [None, [None], [Point(1, 1), None]]) +def test_nearest_none(tree, geometry): + with pytest.raises(ValueError): + tree.nearest(geometry) + + +@pytest.mark.parametrize( + "geometry", [empty_point, [empty_point], [Point(1, 1), empty_point]] +) +def test_nearest_empty(tree, geometry): + with pytest.raises(ValueError): + tree.nearest(geometry) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0.25, 0.25), 0), + (Point(0.75, 0.75), 1), + (Point(1, 1), 1), + ([Point(1, 1), Point(0, 0)], [1, 0]), + ([Point(1, 1), Point(0.25, 1)], [1, 1]), + ([Point(-10, -10), Point(100, 100)], [0, 9]), + (box(0.5, 0.5, 0.75, 0.75), 1), + (shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG), 2), + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), 3), + (MultiPoint([[5.5, 5], [7, 7]]), 7), + (MultiPoint([[5, 7], [7, 5]]), 6), + ], +) +def test_nearest_points(tree, geometry, expected): + assert_array_equal(tree.nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # 2 equidistant points in tree + (Point(0.5, 0.5), [0, 1]), + # multiple points in box + (box(0, 0, 3, 3), [0, 1, 2, 3]), + # return nearest point in tree for each point in multipoint + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ], +) +def test_nearest_points_equidistant(tree, geometry, expected): + # results are returned in order they are traversed when searching the tree, + # which can vary between GEOS versions, so we test that one of the valid + # results is present + result = tree.nearest(geometry) + assert result in expected + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0.5, 0.5), 0), + (Point(1.5, 0.5), 0), + (shapely.box(0.5, 1.5, 1, 2), 1), + (shapely.linestrings([[0, 0.5], [1, 2.5]]), 0), + ], +) +def test_nearest_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # at junction between 2 lines + (Point(2, 2), [1, 2]), + # contains one line, intersects with another + (box(0, 0, 1, 1), [0, 1]), + # overlaps 2 lines + (box(0.5, 0.5, 1.5, 1.5), [0, 1]), + # box overlaps 2 lines and intersects endpoints of 2 more + (box(3, 3, 5, 5), [2, 3, 4, 5]), + (shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG), [1, 2]), + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3]), + # multipoints at endpoints of 2 lines each + (MultiPoint([[5, 5], [7, 7]]), [4, 5, 6, 7]), + # second point in multipoint at endpoints of 2 lines + (MultiPoint([[5.5, 5], [7, 7]]), [6, 7]), + # multipoints are equidistant from 2 lines + (MultiPoint([[5, 7], [7, 5]]), [5, 6]), + ], +) +def test_nearest_lines_equidistant(line_tree, geometry, expected): + # results are returned in order they are traversed when searching the tree, + # which can vary between GEOS versions, so we test that one of the valid + # results is present + result = line_tree.nearest(geometry) + assert result in expected + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0, 0), 0), + (Point(2, 2), 2), + (shapely.box(0, 5, 1, 6), 3), + (MultiPoint([[5, 7], [7, 5]]), 6), + ], +) +def test_nearest_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # 2 polygons in tree overlap point + (Point(0.5, 0.5), [0, 1]), + # box overlaps multiple polygons + (box(0, 0, 1, 1), [0, 1]), + (box(0.5, 0.5, 1.5, 1.5), [0, 1, 2]), + (box(3, 3, 5, 5), [3, 4, 5]), + (shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG), [2, 3]), + # completely overlaps one polygon, touches 2 others + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3, 4]), + # each point in multi point intersects a polygon in tree + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + (MultiPoint([[5.5, 5], [7, 7]]), [5, 7]), + ], +) +def test_nearest_polygons_equidistant(poly_tree, geometry, expected): + # results are returned in order they are traversed when searching the tree, + # which can vary between GEOS versions, so we test that one of the valid + # results is present + result = poly_tree.nearest(geometry) + assert result in expected + + +def test_query_nearest_empty_tree(): + tree = STRtree([]) + assert_array_equal(tree.query_nearest(point), []) + assert_array_equal(tree.query_nearest([point]), [[], []]) + + +@pytest.mark.parametrize("geometry", ["I am not a geometry", ["still not a geometry"]]) +def test_query_nearest_invalid_geom(tree, geometry): + with pytest.raises(TypeError): + tree.query_nearest(geometry) + + +@pytest.mark.parametrize( + "geometry,return_distance,expected", + [ + (None, False, []), + ([None], False, [[], []]), + (None, True, ([], [])), + ([None], True, ([[], []], [])), + ], +) +def test_query_nearest_none(tree, geometry, return_distance, expected): + if return_distance: + index, distance = tree.query_nearest(geometry, return_distance=True) + assert_array_equal(index, expected[0]) + assert_array_equal(distance, expected[1]) + + else: + assert_array_equal(tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [(empty, []), ([empty], [[], []]), ([empty, point], [[1, 1], [2, 3]])], +) +def test_query_nearest_empty_geom(tree, geometry, expected): + assert_array_equal(tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0.25, 0.25), [0]), + ([Point(0.25, 0.25)], [[0], [0]]), + (Point(0.75, 0.75), [1]), + ([Point(0.75, 0.75)], [[0], [1]]), + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # 2 equidistant points in tree + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + ([Point(1, 1), Point(0, 0)], [[0, 1], [1, 0]]), + ([Point(1, 1), Point(0.25, 1)], [[0, 1], [1, 1]]), + ([Point(-10, -10), Point(100, 100)], [[0, 1], [0, 9]]), + (box(0.5, 0.5, 0.75, 0.75), [1]), + ([box(0.5, 0.5, 0.75, 0.75)], [[0], [1]]), + # multiple points in box + (box(0, 0, 3, 3), [0, 1, 2, 3]), + ([box(0, 0, 3, 3)], [[0, 0, 0, 0], [0, 1, 2, 3]]), + (shapely.buffer(Point(2.5, 2.5), 1), [2, 3]), + ([shapely.buffer(Point(2.5, 2.5), 1)], [[0, 0], [2, 3]]), + (shapely.buffer(Point(3, 3), 0.5), [3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0], [3]]), + (MultiPoint([[5.5, 5], [7, 7]]), [7]), + ([MultiPoint([[5.5, 5], [7, 7]])], [[0], [7]]), + (MultiPoint([[5, 7], [7, 5]]), [6]), + ([MultiPoint([[5, 7], [7, 5]])], [[0], [6]]), + # return nearest point in tree for each point in multipoint + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + # 2 equidistant points per point in multipoint + (MultiPoint([[0.5, 0.5], [3.5, 3.5]]), [0, 1, 3, 4]), + ([MultiPoint([[0.5, 0.5], [3.5, 3.5]])], [[0, 0, 0, 0], [0, 1, 3, 4]]), + ], +) +def test_query_nearest_points(tree, geometry, expected): + assert_array_equal(tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # at junction between 2 lines, will return both + (Point(2, 2), [1, 2]), + ([Point(2, 2)], [[0, 0], [1, 2]]), + # contains one line, intersects with another + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # overlaps 2 lines + (box(0.5, 0.5, 1.5, 1.5), [0, 1]), + ([box(0.5, 0.5, 1.5, 1.5)], [[0, 0], [0, 1]]), + # second box overlaps 2 lines and intersects endpoints of 2 more + ([box(0, 0, 0.5, 0.5), box(3, 3, 5, 5)], [[0, 1, 1, 1, 1], [0, 2, 3, 4, 5]]), + (shapely.buffer(Point(2.5, 2.5), 1), [1, 2, 3]), + ([shapely.buffer(Point(2.5, 2.5), 1)], [[0, 0, 0], [1, 2, 3]]), + (shapely.buffer(Point(3, 3), 0.5), [2, 3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0, 0], [2, 3]]), + # multipoints at endpoints of 2 lines each + (MultiPoint([[5, 5], [7, 7]]), [4, 5, 6, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0, 0, 0], [4, 5, 6, 7]]), + # second point in multipoint at endpoints of 2 lines + (MultiPoint([[5.5, 5], [7, 7]]), [6, 7]), + ([MultiPoint([[5.5, 5], [7, 7]])], [[0, 0], [6, 7]]), + # multipoints are equidistant from 2 lines + (MultiPoint([[5, 7], [7, 5]]), [5, 6]), + ([MultiPoint([[5, 7], [7, 5]])], [[0, 0], [5, 6]]), + ], +) +def test_query_nearest_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + (Point(2, 2), [2]), + ([Point(2, 2)], [[0], [2]]), + # 2 polygons in tree overlap point + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # box overlaps multiple polygons + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + (box(0.5, 0.5, 1.5, 1.5), [0, 1, 2]), + ([box(0.5, 0.5, 1.5, 1.5)], [[0, 0, 0], [0, 1, 2]]), + ([box(0, 0, 1, 1), box(3, 3, 5, 5)], [[0, 0, 1, 1, 1], [0, 1, 3, 4, 5]]), + (shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG), [2, 3]), + ([shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG)], [[0, 0], [2, 3]]), + # completely overlaps one polygon, touches 2 others + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[0, 0, 0], [2, 3, 4]]), + # each point in multi point intersects a polygon in tree + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + (MultiPoint([[5.5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5.5, 5], [7, 7]])], [[0, 0], [5, 7]]), + (MultiPoint([[5, 7], [7, 5]]), [6]), + ([MultiPoint([[5, 7], [7, 5]])], [[0], [6]]), + ], +) +def test_query_nearest_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,max_distance,expected", + [ + # using unset max_distance should return all nearest + (Point(0.5, 0.5), None, [0, 1]), + ([Point(0.5, 0.5)], None, [[0, 0], [0, 1]]), + # using large max_distance should return all nearest + (Point(0.5, 0.5), 10, [0, 1]), + ([Point(0.5, 0.5)], 10, [[0, 0], [0, 1]]), + # using small max_distance should return no results + (Point(0.5, 0.5), 0.1, []), + ([Point(0.5, 0.5)], 0.1, [[], []]), + # using small max_distance should only return results in that distance + ([Point(0.5, 0.5), Point(0, 0)], 0.1, [[1], [0]]), + ], +) +def test_query_nearest_max_distance(tree, geometry, max_distance, expected): + assert_array_equal( + tree.query_nearest(geometry, max_distance=max_distance), expected + ) + + +@pytest.mark.parametrize( + "geometry,max_distance", + [ + (Point(0.5, 0.5), 0), + ([Point(0.5, 0.5)], 0), + (Point(0.5, 0.5), -1), + ([Point(0.5, 0.5)], -1), + ], +) +def test_query_nearest_invalid_max_distance(tree, geometry, max_distance): + with pytest.raises(ValueError, match="max_distance must be greater than 0"): + tree.query_nearest(geometry, max_distance=max_distance) + + +def test_query_nearest_nonscalar_max_distance(tree): + with pytest.raises(ValueError, match="parameter only accepts scalar values"): + tree.query_nearest(Point(0.5, 0.5), max_distance=[1]) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0, 0), ([0], [0.0])), + ([Point(0, 0)], ([[0], [0]], [0.0])), + (Point(0.5, 0.5), ([0, 1], [0.7071, 0.7071])), + ([Point(0.5, 0.5)], ([[0, 0], [0, 1]], [0.7071, 0.7071])), + (box(0, 0, 1, 1), ([0, 1], [0.0, 0.0])), + ([box(0, 0, 1, 1)], ([[0, 0], [0, 1]], [0.0, 0.0])), + ], +) +def test_query_nearest_return_distance(tree, geometry, expected): + expected_indices, expected_dist = expected + + actual_indices, actual_dist = tree.query_nearest(geometry, return_distance=True) + + assert_array_equal(actual_indices, expected_indices) + assert_array_equal(np.round(actual_dist, 4), expected_dist) + + +@pytest.mark.parametrize( + "geometry,exclusive,expected", + [ + (Point(1, 1), False, [1]), + ([Point(1, 1)], False, [[0], [1]]), + (Point(1, 1), True, [0, 2]), + ([Point(1, 1)], True, [[0, 0], [0, 2]]), + ([Point(1, 1), Point(2, 2)], True, [[0, 0, 1, 1], [0, 2, 1, 3]]), + ], +) +def test_query_nearest_exclusive(tree, geometry, exclusive, expected): + assert_array_equal(tree.query_nearest(geometry, exclusive=exclusive), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(1, 1), []), + ([Point(1, 1)], [[], []]), + ], +) +def test_query_nearest_exclusive_no_results(tree, geometry, expected): + tree = STRtree([Point(1, 1)]) + assert_array_equal(tree.query_nearest(geometry, exclusive=True), expected) + + +@pytest.mark.parametrize( + "geometry,exclusive", + [ + (Point(1, 1), "invalid"), + # non-scalar exclusive parameter not allowed + (Point(1, 1), ["also invalid"]), + ([Point(1, 1)], []), + ([Point(1, 1)], [False]), + ], +) +def test_query_nearest_invalid_exclusive(tree, geometry, exclusive): + with pytest.raises(ValueError): + tree.query_nearest(geometry, exclusive=exclusive) + + +@pytest.mark.parametrize( + "geometry,all_matches", + [ + (Point(1, 1), "invalid"), + # non-scalar all_matches parameter not allowed + (Point(1, 1), ["also invalid"]), + ([Point(1, 1)], []), + ([Point(1, 1)], [False]), + ], +) +def test_query_nearest_invalid_all_matches(tree, geometry, all_matches): + with pytest.raises(ValueError): + tree.query_nearest(geometry, all_matches=all_matches) + + +def test_query_nearest_all_matches(tree): + point = Point(0.5, 0.5) + assert_array_equal(tree.query_nearest(point, all_matches=True), [0, 1]) + + indices = tree.query_nearest(point, all_matches=False) + # result is dependent on tree traversal order; may vary across test runs + assert np.array_equal(indices, [0]) or np.array_equal(indices, [1]) + + +def test_strtree_threaded_query(): + ## Create data + polygons = shapely.polygons(np.random.randn(1000, 3, 2)) + # needs to be big enough to trigger the segfault + N = 100_000 + points = shapely.points(4 * np.random.random(N) - 2, 4 * np.random.random(N) - 2) + + ## Slice parts of the arrays -> 4x4 => 16 combinations + n = int(len(polygons) / 4) + polygons_parts = [ + polygons[:n], + polygons[n : 2 * n], + polygons[2 * n : 3 * n], + polygons[3 * n :], + ] + n = int(len(points) / 4) + points_parts = [ + points[:n], + points[n : 2 * n], + points[2 * n : 3 * n], + points[3 * n :], + ] + + ## Creating the trees in advance + trees = [] + for i in range(4): + left = points_parts[i] + tree = STRtree(left) + trees.append(tree) + + ## The function querying the trees in parallel + + def thread_func(idxs): + i, j = idxs + tree = trees[i] + right = polygons_parts[j] + return tree.query(right, predicate="contains") + + with ThreadPoolExecutor() as pool: + list(pool.map(thread_func, itertools.product(range(4), range(4)))) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_testing.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..5def4fb9f3cb87f59516ac13debb95841e0df1d5 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/tests/test_testing.py @@ -0,0 +1,97 @@ +import numpy as np +import pytest + +import shapely +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + all_types, + empty, + empty_line_string, + empty_line_string_z, + empty_point, + empty_point_z, + empty_polygon, + line_string, + line_string_nan, + line_string_z, + point, +) + +EMPTY_GEOMS = ( + empty_point, + empty_point_z, + empty_line_string, + empty_line_string_z, + empty_polygon, + empty, +) + +line_string_reversed = shapely.linestrings([(0, 0), (1, 0), (1, 1)][::-1]) + + +def make_array(left, right, use_array): + if use_array in ("left", "both"): + left = np.array([left] * 3, dtype=object) + if use_array in ("right", "both"): + right = np.array([right] * 3, dtype=object) + return left, right + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +@pytest.mark.parametrize("geom", all_types + EMPTY_GEOMS) +def test_assert_geometries_equal(geom, use_array): + assert_geometries_equal(*make_array(geom, geom, use_array)) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +@pytest.mark.parametrize( + "geom1,geom2", + [ + (point, line_string), + (line_string, line_string_z), + (empty_point, empty_polygon), + (empty_point, empty_point_z), + (empty_line_string, empty_line_string_z), + ], +) +def test_assert_geometries_not_equal(geom1, geom2, use_array): + with pytest.raises(AssertionError): + assert_geometries_equal(*make_array(geom1, geom2, use_array)) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +def test_assert_none_equal(use_array): + assert_geometries_equal(*make_array(None, None, use_array)) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +def test_assert_none_not_equal(use_array): + with pytest.raises(AssertionError): + assert_geometries_equal(*make_array(None, None, use_array), equal_none=False) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +def test_assert_nan_equal(use_array): + assert_geometries_equal(*make_array(line_string_nan, line_string_nan, use_array)) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +def test_assert_nan_not_equal(use_array): + with pytest.raises(AssertionError): + assert_geometries_equal( + *make_array(line_string_nan, line_string_nan, use_array), equal_nan=False + ) + + +def test_normalize_true(): + assert_geometries_equal(line_string_reversed, line_string, normalize=True) + + +def test_normalize_default(): + with pytest.raises(AssertionError): + assert_geometries_equal(line_string_reversed, line_string) + + +def test_normalize_false(): + with pytest.raises(AssertionError): + assert_geometries_equal(line_string_reversed, line_string, normalize=False) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/validation.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..bd7afea07d5daa929fa014b6925a8e124568bae0 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/validation.py @@ -0,0 +1,55 @@ +"""Validate geometries and make them valid.""" +# TODO: allow for implementations using other than GEOS + +import shapely + +__all__ = ["explain_validity", "make_valid"] + + +def explain_validity(ob): + """Explain the validity of the input geometry, if it is invalid. + + This will describe why the geometry is invalid, and might + include a location if there is a self-intersection or a + ring self-intersection. + + Parameters + ---------- + ob: Geometry + A shapely geometry object + + Returns + ------- + str + A string describing the reason the geometry is invalid. + + """ + return shapely.is_valid_reason(ob) + + +def make_valid(ob): + """Make the input geometry valid according to the GEOS MakeValid algorithm. + + If the input geometry is already valid, then it will be returned. + + If the geometry must be split into multiple parts of the same type to be + made valid, then a multi-part geometry will be returned. + + If the geometry must be split into multiple parts of different types to be + made valid, then a GeometryCollection will be returned. + + Parameters + ---------- + ob : Geometry + A shapely geometry object which should be made valid. If the object is + already valid, it will be returned as-is. + + Returns + ------- + Geometry + The input geometry, made valid according to the GEOS MakeValid algorithm. + + """ + if ob.is_valid: + return ob + return shapely.make_valid(ob) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/vectorized/__init__.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/vectorized/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..49462c2e11bf5d1360560cc84c68694ff70eef68 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/vectorized/__init__.py @@ -0,0 +1,91 @@ +"""Provides multi-point element-wise operations such as ``contains``.""" + +import warnings + +import numpy as np + +import shapely +from shapely.prepared import PreparedGeometry + + +def _construct_points(x, y): + x, y = np.asanyarray(x), np.asanyarray(y) + if x.shape != y.shape: + raise ValueError("X and Y shapes must be equivalent.") + + if x.dtype != np.float64: + x = x.astype(np.float64) + if y.dtype != np.float64: + y = y.astype(np.float64) + + return shapely.points(x, y) + + +def contains(geometry, x, y): + """Check whether multiple points are contained by a single geometry. + + Vectorized (element-wise) version of `contains`. + + Parameters + ---------- + geometry : PreparedGeometry or subclass of BaseGeometry + The geometry which is to be checked to see whether each point is + contained within. The geometry will be "prepared" if it is not already + a PreparedGeometry instance. + x : array + The x coordinates of the points to check. + y : array + The y coordinates of the points to check. + + Returns + ------- + Mask of points contained by the given `geometry`. + + """ + warnings.warn( + "The 'shapely.vectorized.contains' function is deprecated and will be " + "removed a future version. Use 'shapely.contains_xy' instead (available " + "since shapely 2.0.0).", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(geometry, PreparedGeometry): + geometry = geometry.context + shapely.prepare(geometry) + return shapely.contains_xy(geometry, x, y) + + +def touches(geometry, x, y): + """Check whether multiple points touch the exterior of a single geometry. + + Vectorized (element-wise) version of `touches`. + + Parameters + ---------- + geometry : PreparedGeometry or subclass of BaseGeometry + The geometry which is to be checked to see whether each point is + contained within. The geometry will be "prepared" if it is not already + a PreparedGeometry instance. + x : array + The x coordinates of the points to check. + y : array + The y coordinates of the points to check. + + Returns + ------- + Mask of points which touch the exterior of the given `geometry`. + + """ + warnings.warn( + "The 'shapely.vectorized.touches' function is deprecated and will be " + "removed a future version. Use 'shapely.intersects_xy(geometry.boundary, x, y)'" + " instead (available since shapely 2.0.0).", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(geometry, PreparedGeometry): + geometry = geometry.context + # Touches(geom, point) == Intersects(Boundary(geom), point) + boundary = geometry.boundary + shapely.prepare(boundary) + return shapely.intersects_xy(boundary, x, y) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/vectorized/__pycache__/__init__.cpython-311.pyc b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/vectorized/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12083f2ffe21dfd7dc59eabdb916fbee35a922ee Binary files /dev/null and b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/vectorized/__pycache__/__init__.cpython-311.pyc differ diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/wkb.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/wkb.py new file mode 100644 index 0000000000000000000000000000000000000000..2040bdc49ce5534fac24712cb6ae1fb574c2f9a8 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/wkb.py @@ -0,0 +1,70 @@ +"""Load/dump geometries using the well-known binary (WKB) format. + +Also provides pickle-like convenience functions. +""" + +import shapely + + +def loads(data, hex=False): + """Load a geometry from a WKB byte string. + + If ``hex=True``, the string will be hex-encoded. + + Raises + ------ + GEOSException, UnicodeDecodeError + If ``data`` contains an invalid geometry. + + """ + return shapely.from_wkb(data) + + +def load(fp, hex=False): + """Load a geometry from an open file. + + Raises + ------ + GEOSException, UnicodeDecodeError + If the given file contains an invalid geometry. + + """ + data = fp.read() + return loads(data, hex=hex) + + +def dumps(ob, hex=False, srid=None, **kw): + """Dump a WKB representation of a geometry to a byte string. + + If ``hex=True``, the string will be hex-encoded. + + Parameters + ---------- + ob : geometry + The geometry to export to well-known binary (WKB) representation. + hex : bool + If true, export the WKB as a hexadecimal string. The default is to + return a binary string/bytes object. + srid : int + Spatial reference system ID to include in the output. The default value + means no SRID is included. + **kw : kwargs, optional + Keyword output options passed to :func:`~shapely.to_wkb`. + + """ + if srid is not None: + # clone the object and set the SRID before dumping + ob = shapely.set_srid(ob, srid) + kw["include_srid"] = True + if "big_endian" in kw: + # translate big_endian=True/False into byte_order=0/1 + # but if not specified, keep the default of byte_order=-1 (native) + big_endian = kw.pop("big_endian") + byte_order = 0 if big_endian else 1 + kw.update(byte_order=byte_order) + return shapely.to_wkb(ob, hex=hex, **kw) + + +def dump(ob, fp, hex=False, **kw): + """Dump a geometry to an open file.""" + fp.write(dumps(ob, hex=hex, **kw)) diff --git a/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/wkt.py b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/wkt.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc19c9521b67f93f66087fcbeab574d5019d344 --- /dev/null +++ b/grounding-dino/.eval_venv/lib64/python3.11/site-packages/shapely/wkt.py @@ -0,0 +1,82 @@ +"""Load/dump geometries using the well-known text (WKT) format. + +Also provides pickle-like convenience functions. +""" + +import shapely + + +def loads(data): + """Load a geometry from a WKT string. + + Parameters + ---------- + data : str + A WKT string + + Returns + ------- + Shapely geometry object + + """ + return shapely.from_wkt(data) + + +def load(fp): + """Load a geometry from an open file. + + Parameters + ---------- + fp : + A file-like object which implements a `read` method. + + Returns + ------- + Shapely geometry object + + """ + data = fp.read() + return loads(data) + + +def dumps(ob, trim=False, rounding_precision=-1, **kw): + """Dump a WKT representation of a geometry to a string. + + Parameters + ---------- + ob : + A geometry object of any type to be dumped to WKT. + trim : bool, default False + Remove excess decimals from the WKT. + rounding_precision : int, default -1 + Round output to the specified number of digits. + Default behavior returns full precision. + **kw : kwargs, optional + Keyword output options passed to :func:`~shapely.to_wkt`. + + Returns + ------- + input geometry as WKT string + + """ + return shapely.to_wkt(ob, trim=trim, rounding_precision=rounding_precision, **kw) + + +def dump(ob, fp, **settings): + """Dump a geometry to an open file. + + Parameters + ---------- + ob : + A geometry object of any type to be dumped to WKT. + fp : + A file-like object which implements a `write` method. + **settings : kwargs, optional + Keyword output options passed to :func:`~shapely.wkt.dumps`. + + Returns + ------- + None + + """ + fp.write(dumps(ob, **settings)) diff --git a/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/config.yml b/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..56bbd88fddfd7a1ceb50a1cb406e80318a8d0370 --- /dev/null +++ b/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,9 @@ +blank_issues_enabled: false + +contact_links: + - name: Common Issues + url: https://mmdetection.readthedocs.io/en/latest/faq.html + about: Check if your issue already has solutions + - name: MMDetection Documentation + url: https://mmdetection.readthedocs.io/en/latest/ + about: Check if your question is answered in docs diff --git a/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/feature_request.md b/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..7bf92e8c912df6839eb755715c181f5fc7244f36 --- /dev/null +++ b/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' +--- + +**Describe the feature** + +**Motivation** +A clear and concise description of the motivation of the feature. +Ex1. It is inconvenient when \[....\]. +Ex2. There is a recent paper \[....\], which is very helpful for \[....\]. + +**Related resources** +If there is an official code release or third-party implementations, please also provide the information here, which would be very helpful. + +**Additional context** +Add any other context or screenshots about the feature request here. +If you would like to implement the feature and create a PR, please leave a comment here and that would be much appreciated. diff --git a/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/general_questions.md b/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/general_questions.md new file mode 100644 index 0000000000000000000000000000000000000000..f02dd63a8095c65ca6a46172d8c739c6cde3e5f0 --- /dev/null +++ b/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/general_questions.md @@ -0,0 +1,7 @@ +--- +name: General questions +about: Ask general questions to get help +title: '' +labels: '' +assignees: '' +--- diff --git a/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/reimplementation_questions.md b/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/reimplementation_questions.md new file mode 100644 index 0000000000000000000000000000000000000000..83607ac34028bec7312e2f163777da77a0da192f --- /dev/null +++ b/grounding-dino/mmdetection/.github/ISSUE_TEMPLATE/reimplementation_questions.md @@ -0,0 +1,67 @@ +--- +name: Reimplementation Questions +about: Ask about questions during model reimplementation +title: '' +labels: reimplementation +assignees: '' +--- + +**Notice** + +There are several common situations in the reimplementation issues as below + +1. Reimplement a model in the model zoo using the provided configs +2. Reimplement a model in the model zoo on other dataset (e.g., custom datasets) +3. Reimplement a custom model but all the components are implemented in MMDetection +4. Reimplement a custom model with new modules implemented by yourself + +There are several things to do for different cases as below. + +- For case 1 & 3, please follow the steps in the following sections thus we could help to quick identify the issue. +- For case 2 & 4, please understand that we are not able to do much help here because we usually do not know the full code and the users should be responsible to the code they write. +- One suggestion for case 2 & 4 is that the users should first check whether the bug lies in the self-implemented code or the original code. For example, users can first make sure that the same model runs well on supported datasets. If you still need help, please describe what you have done and what you obtain in the issue, and follow the steps in the following sections and try as clear as possible so that we can better help you. + +**Checklist** + +1. I have searched related issues but cannot get the expected help. +2. The issue has not been fixed in the latest version. + +**Describe the issue** + +A clear and concise description of what the problem you meet and what have you done. + +**Reproduction** + +1. What command or script did you run? + +```none +A placeholder for the command. +``` + +2. What config dir you run? + +```none +A placeholder for the config. +``` + +3. Did you make any modifications on the code or config? Did you understand what you have modified? +4. What dataset did you use? + +**Environment** + +1. Please run `python mmdet/utils/collect_env.py` to collect necessary environment information and paste it here. +2. You may add addition that may be helpful for locating the problem, such as + 1. How you installed PyTorch \[e.g., pip, conda, source\] + 2. Other environment variables that may be related (such as `$PATH`, `$LD_LIBRARY_PATH`, `$PYTHONPATH`, etc.) + +**Results** + +If applicable, paste the related results here, e.g., what you expect and what you get. + +```none +A placeholder for results comparison +``` + +**Issue fix** + +If you have already identified the reason, you can provide the information here. If you are willing to create a PR to fix it, please also leave a comment here and that would be much appreciated! diff --git a/grounding-dino/mmdetection/.github/workflows/deploy.yml b/grounding-dino/mmdetection/.github/workflows/deploy.yml new file mode 100644 index 0000000000000000000000000000000000000000..f575061468b98978caa067c970ad853efc0cfa21 --- /dev/null +++ b/grounding-dino/mmdetection/.github/workflows/deploy.yml @@ -0,0 +1,28 @@ +name: deploy + +on: push + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-n-publish: + runs-on: ubuntu-latest + if: startsWith(github.event.ref, 'refs/tags') + steps: + - uses: actions/checkout@v2 + - name: Set up Python 3.7 + uses: actions/setup-python@v2 + with: + python-version: 3.7 + - name: Install torch + run: pip install torch + - name: Install wheel + run: pip install wheel + - name: Build MMDetection + run: python setup.py sdist bdist_wheel + - name: Publish distribution to PyPI + run: | + pip install twine + twine upload dist/* -u __token__ -p ${{ secrets.pypi_password }} diff --git a/grounding-dino/mmdetection/configs/albu_example/README.md b/grounding-dino/mmdetection/configs/albu_example/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fa362f95fb91ba4beed5c9d6814e087324bd74d5 --- /dev/null +++ b/grounding-dino/mmdetection/configs/albu_example/README.md @@ -0,0 +1,31 @@ +# Albu Example + +> [Albumentations: fast and flexible image augmentations](https://arxiv.org/abs/1809.06839) + + + +## Abstract + +Data augmentation is a commonly used technique for increasing both the size and the diversity of labeled training sets by leveraging input transformations that preserve output labels. In computer vision domain, image augmentations have become a common implicit regularization technique to combat overfitting in deep convolutional neural networks and are ubiquitously used to improve performance. While most deep learning frameworks implement basic image transformations, the list is typically limited to some variations and combinations of flipping, rotating, scaling, and cropping. Moreover, the image processing speed varies in existing tools for image augmentation. We present Albumentations, a fast and flexible library for image augmentations with many various image transform operations available, that is also an easy-to-use wrapper around other augmentation libraries. We provide examples of image augmentations for different computer vision tasks and show that Albumentations is faster than other commonly used image augmentation tools on the most of commonly used image transformations. + +
+ +
+ +## Results and Models + +| Backbone | Style | Lr schd | Mem (GB) | Inf time (fps) | box AP | mask AP | Config | Download | +| :------: | :-----: | :-----: | :------: | :------------: | :----: | :-----: | :-------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50 | pytorch | 1x | 4.4 | 16.6 | 38.0 | 34.5 | [config](./mask-rcnn_r50_fpn_albu-1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/albu_example/mask_rcnn_r50_fpn_albu_1x_coco/mask_rcnn_r50_fpn_albu_1x_coco_20200208-ab203bcd.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/albu_example/mask_rcnn_r50_fpn_albu_1x_coco/mask_rcnn_r50_fpn_albu_1x_coco_20200208_225520.log.json) | + +## Citation + +```latex +@article{2018arXiv180906839B, + author = {A. Buslaev, A. Parinov, E. Khvedchenya, V.~I. Iglovikov and A.~A. Kalinin}, + title = "{Albumentations: fast and flexible image augmentations}", + journal = {ArXiv e-prints}, + eprint = {1809.06839}, + year = 2018 +} +``` diff --git a/grounding-dino/mmdetection/configs/albu_example/mask-rcnn_r50_fpn_albu-1x_coco.py b/grounding-dino/mmdetection/configs/albu_example/mask-rcnn_r50_fpn_albu-1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a2780e99b88c78adbe74c024fcd2d693817030 --- /dev/null +++ b/grounding-dino/mmdetection/configs/albu_example/mask-rcnn_r50_fpn_albu-1x_coco.py @@ -0,0 +1,66 @@ +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' + +albu_train_transforms = [ + dict( + type='ShiftScaleRotate', + shift_limit=0.0625, + scale_limit=0.0, + rotate_limit=0, + interpolation=1, + p=0.5), + dict( + type='RandomBrightnessContrast', + brightness_limit=[0.1, 0.3], + contrast_limit=[0.1, 0.3], + p=0.2), + dict( + type='OneOf', + transforms=[ + dict( + type='RGBShift', + r_shift_limit=10, + g_shift_limit=10, + b_shift_limit=10, + p=1.0), + dict( + type='HueSaturationValue', + hue_shift_limit=20, + sat_shift_limit=30, + val_shift_limit=20, + p=1.0) + ], + p=0.1), + dict(type='JpegCompression', quality_lower=85, quality_upper=95, p=0.2), + dict(type='ChannelShuffle', p=0.1), + dict( + type='OneOf', + transforms=[ + dict(type='Blur', blur_limit=3, p=1.0), + dict(type='MedianBlur', blur_limit=3, p=1.0) + ], + p=0.1), +] +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='Albu', + transforms=albu_train_transforms, + bbox_params=dict( + type='BboxParams', + format='pascal_voc', + label_fields=['gt_bboxes_labels', 'gt_ignore_flags'], + min_visibility=0.0, + filter_lost_elements=True), + keymap={ + 'img': 'image', + 'gt_masks': 'masks', + 'gt_bboxes': 'bboxes' + }, + skip_img_without_anno=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) diff --git a/grounding-dino/mmdetection/configs/albu_example/metafile.yml b/grounding-dino/mmdetection/configs/albu_example/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..3b54bdf15688281e5896faac3f841433497c7eaf --- /dev/null +++ b/grounding-dino/mmdetection/configs/albu_example/metafile.yml @@ -0,0 +1,17 @@ +Models: + - Name: mask-rcnn_r50_fpn_albu-1x_coco + In Collection: Mask R-CNN + Config: mask-rcnn_r50_fpn_albu-1x_coco.py + Metadata: + Training Memory (GB): 4.4 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 38.0 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 34.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/albu_example/mask_rcnn_r50_fpn_albu_1x_coco/mask_rcnn_r50_fpn_albu_1x_coco_20200208-ab203bcd.pth diff --git a/grounding-dino/mmdetection/configs/atss/README.md b/grounding-dino/mmdetection/configs/atss/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1411672e205683914c24bec47ac02517d44f684b --- /dev/null +++ b/grounding-dino/mmdetection/configs/atss/README.md @@ -0,0 +1,31 @@ +# ATSS + +> [Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection](https://arxiv.org/abs/1912.02424) + + + +## Abstract + +Object detection has been dominated by anchor-based detectors for several years. Recently, anchor-free detectors have become popular due to the proposal of FPN and Focal Loss. In this paper, we first point out that the essential difference between anchor-based and anchor-free detection is actually how to define positive and negative training samples, which leads to the performance gap between them. If they adopt the same definition of positive and negative samples during training, there is no obvious difference in the final performance, no matter regressing from a box or a point. This shows that how to select positive and negative training samples is important for current object detectors. Then, we propose an Adaptive Training Sample Selection (ATSS) to automatically select positive and negative samples according to statistical characteristics of object. It significantly improves the performance of anchor-based and anchor-free detectors and bridges the gap between them. Finally, we discuss the necessity of tiling multiple anchors per location on the image to detect objects. Extensive experiments conducted on MS COCO support our aforementioned analysis and conclusions. With the newly introduced ATSS, we improve state-of-the-art detectors by a large margin to 50.7% AP without introducing any overhead. + +
+ +
+ +## Results and Models + +| Backbone | Style | Lr schd | Mem (GB) | Inf time (fps) | box AP | Config | Download | +| :------: | :-----: | :-----: | :------: | :------------: | :----: | :----------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50 | pytorch | 1x | 3.7 | 19.7 | 39.4 | [config](./atss_r50_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/atss/atss_r50_fpn_1x_coco/atss_r50_fpn_1x_coco_20200209-985f7bd0.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/atss/atss_r50_fpn_1x_coco/atss_r50_fpn_1x_coco_20200209_102539.log.json) | +| R-101 | pytorch | 1x | 5.6 | 12.3 | 41.5 | [config](./atss_r101_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/atss/atss_r101_fpn_1x_coco/atss_r101_fpn_1x_20200825-dfcadd6f.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/atss/atss_r101_fpn_1x_coco/atss_r101_fpn_1x_20200825-dfcadd6f.log.json) | + +## Citation + +```latex +@article{zhang2019bridging, + title = {Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection}, + author = {Zhang, Shifeng and Chi, Cheng and Yao, Yongqiang and Lei, Zhen and Li, Stan Z.}, + journal = {arXiv preprint arXiv:1912.02424}, + year = {2019} +} +``` diff --git a/grounding-dino/mmdetection/configs/atss/atss_r101_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/atss/atss_r101_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..5225d2ab672738d4d427eba252e92bd554252476 --- /dev/null +++ b/grounding-dino/mmdetection/configs/atss/atss_r101_fpn_1x_coco.py @@ -0,0 +1,6 @@ +_base_ = './atss_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/atss/atss_r101_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/atss/atss_r101_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..69999ce45aee9c76dcc4af974e6e9baabbd5b44b --- /dev/null +++ b/grounding-dino/mmdetection/configs/atss/atss_r101_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,7 @@ +_base_ = './atss_r50_fpn_8xb8-amp-lsj-200e_coco.py' + +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/atss/atss_r18_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/atss/atss_r18_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..12d9f13263619333391befd6692c83622091ef4e --- /dev/null +++ b/grounding-dino/mmdetection/configs/atss/atss_r18_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,7 @@ +_base_ = './atss_r50_fpn_8xb8-amp-lsj-200e_coco.py' + +model = dict( + backbone=dict( + depth=18, + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18')), + neck=dict(in_channels=[64, 128, 256, 512])) diff --git a/grounding-dino/mmdetection/configs/atss/atss_r50_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/atss/atss_r50_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..306435d7d2fc645f1c2deae784c1875cc4ceaf98 --- /dev/null +++ b/grounding-dino/mmdetection/configs/atss/atss_r50_fpn_1x_coco.py @@ -0,0 +1,71 @@ +_base_ = [ + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +# model settings +model = dict( + type='ATSS', + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_size_divisor=32), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=True, + style='pytorch', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict( + type='FPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + start_level=1, + add_extra_convs='on_output', + num_outs=5), + bbox_head=dict( + type='ATSSHead', + num_classes=80, + in_channels=256, + stacked_convs=4, + feat_channels=256, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[0.1, 0.1, 0.2, 0.2]), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + # training and testing settings + train_cfg=dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False), + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) +# optimizer +optim_wrapper = dict( + optimizer=dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)) diff --git a/grounding-dino/mmdetection/configs/atss/atss_r50_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/atss/atss_r50_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b3c46f4b926b82fbab438d6d50eb6c079dabc3 --- /dev/null +++ b/grounding-dino/mmdetection/configs/atss/atss_r50_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,81 @@ +_base_ = '../common/lsj-200e_coco-detection.py' + +image_size = (1024, 1024) +batch_augments = [dict(type='BatchFixedSizePad', size=image_size)] + +model = dict( + type='ATSS', + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_size_divisor=32, + batch_augments=batch_augments), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=True, + style='pytorch', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict( + type='FPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + start_level=1, + add_extra_convs='on_output', + num_outs=5), + bbox_head=dict( + type='ATSSHead', + num_classes=80, + in_channels=256, + stacked_convs=4, + feat_channels=256, + anchor_generator=dict( + type='AnchorGenerator', + ratios=[1.0], + octave_base_scale=8, + scales_per_octave=1, + strides=[8, 16, 32, 64, 128]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[.0, .0, .0, .0], + target_stds=[0.1, 0.1, 0.2, 0.2]), + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + # training and testing settings + train_cfg=dict( + assigner=dict(type='ATSSAssigner', topk=9), + allowed_border=-1, + pos_weight=-1, + debug=False), + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + +train_dataloader = dict(batch_size=8, num_workers=4) + +# Enable automatic-mixed-precision training with AmpOptimWrapper. +optim_wrapper = dict( + type='AmpOptimWrapper', + optimizer=dict( + type='SGD', lr=0.01 * 4, momentum=0.9, weight_decay=0.00004)) + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (8 samples per GPU) +auto_scale_lr = dict(base_batch_size=64) diff --git a/grounding-dino/mmdetection/configs/atss/metafile.yml b/grounding-dino/mmdetection/configs/atss/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..f4c567ef29ba9ea4fddd7bc00d63a4bca41b1cfa --- /dev/null +++ b/grounding-dino/mmdetection/configs/atss/metafile.yml @@ -0,0 +1,60 @@ +Collections: + - Name: ATSS + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - ATSS + - FPN + - ResNet + Paper: + URL: https://arxiv.org/abs/1912.02424 + Title: 'Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection' + README: configs/atss/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.0.0/mmdet/models/detectors/atss.py#L6 + Version: v2.0.0 + +Models: + - Name: atss_r50_fpn_1x_coco + In Collection: ATSS + Config: configs/atss/atss_r50_fpn_1x_coco.py + Metadata: + Training Memory (GB): 3.7 + inference time (ms/im): + - value: 50.76 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 39.4 + Weights: https://download.openmmlab.com/mmdetection/v2.0/atss/atss_r50_fpn_1x_coco/atss_r50_fpn_1x_coco_20200209-985f7bd0.pth + + - Name: atss_r101_fpn_1x_coco + In Collection: ATSS + Config: configs/atss/atss_r101_fpn_1x_coco.py + Metadata: + Training Memory (GB): 5.6 + inference time (ms/im): + - value: 81.3 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/atss/atss_r101_fpn_1x_coco/atss_r101_fpn_1x_20200825-dfcadd6f.pth diff --git a/grounding-dino/mmdetection/configs/autoassign/README.md b/grounding-dino/mmdetection/configs/autoassign/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f6b05738ccc222223863974697cee7f2770d8f25 --- /dev/null +++ b/grounding-dino/mmdetection/configs/autoassign/README.md @@ -0,0 +1,35 @@ +# AutoAssign + +> [AutoAssign: Differentiable Label Assignment for Dense Object Detection](https://arxiv.org/abs/2007.03496) + + + +## Abstract + +Determining positive/negative samples for object detection is known as label assignment. Here we present an anchor-free detector named AutoAssign. It requires little human knowledge and achieves appearance-aware through a fully differentiable weighting mechanism. During training, to both satisfy the prior distribution of data and adapt to category characteristics, we present Center Weighting to adjust the category-specific prior distributions. To adapt to object appearances, Confidence Weighting is proposed to adjust the specific assign strategy of each instance. The two weighting modules are then combined to generate positive and negative weights to adjust each location's confidence. Extensive experiments on the MS COCO show that our method steadily surpasses other best sampling strategies by large margins with various backbones. Moreover, our best model achieves 52.1% AP, outperforming all existing one-stage detectors. Besides, experiments on other datasets, e.g., PASCAL VOC, Objects365, and WiderFace, demonstrate the broad applicability of AutoAssign. + +
+ +
+ +## Results and Models + +| Backbone | Style | Lr schd | Mem (GB) | box AP | Config | Download | +| :------: | :---: | :-----: | :------: | :----: | :---------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50 | caffe | 1x | 4.08 | 40.4 | [config](./autoassign_r50-caffe_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/autoassign/auto_assign_r50_fpn_1x_coco/auto_assign_r50_fpn_1x_coco_20210413_115540-5e17991f.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/autoassign/auto_assign_r50_fpn_1x_coco/auto_assign_r50_fpn_1x_coco_20210413_115540-5e17991f.log.json) | + +**Note**: + +1. We find that the performance is unstable with 1x setting and may fluctuate by about 0.3 mAP. mAP 40.3 ~ 40.6 is acceptable. Such fluctuation can also be found in the original implementation. +2. You can get a more stable results ~ mAP 40.6 with a schedule total 13 epoch, and learning rate is divided by 10 at 10th and 13th epoch. + +## Citation + +```latex +@article{zhu2020autoassign, + title={AutoAssign: Differentiable Label Assignment for Dense Object Detection}, + author={Zhu, Benjin and Wang, Jianfeng and Jiang, Zhengkai and Zong, Fuhang and Liu, Songtao and Li, Zeming and Sun, Jian}, + journal={arXiv preprint arXiv:2007.03496}, + year={2020} +} +``` diff --git a/grounding-dino/mmdetection/configs/autoassign/autoassign_r50-caffe_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/autoassign/autoassign_r50-caffe_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..76a361952d95b655451186ef1cb39df2f24ae305 --- /dev/null +++ b/grounding-dino/mmdetection/configs/autoassign/autoassign_r50-caffe_fpn_1x_coco.py @@ -0,0 +1,69 @@ +# We follow the original implementation which +# adopts the Caffe pre-trained backbone. +_base_ = [ + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] +# model settings +model = dict( + type='AutoAssign', + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[102.9801, 115.9465, 122.7717], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False, + pad_size_divisor=32), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=False), + norm_eval=True, + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe')), + neck=dict( + type='FPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + start_level=1, + add_extra_convs=True, + num_outs=5, + relu_before_extra_convs=True, + init_cfg=dict(type='Caffe2Xavier', layer='Conv2d')), + bbox_head=dict( + type='AutoAssignHead', + num_classes=80, + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_bbox=dict(type='GIoULoss', loss_weight=5.0)), + train_cfg=None, + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[8, 11], + gamma=0.1) +] + +# optimizer +optim_wrapper = dict( + optimizer=dict(lr=0.01), paramwise_cfg=dict(norm_decay_mult=0.)) diff --git a/grounding-dino/mmdetection/configs/autoassign/metafile.yml b/grounding-dino/mmdetection/configs/autoassign/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..ab7a4af3371d4be5325498db97af0e7dd8fdc28c --- /dev/null +++ b/grounding-dino/mmdetection/configs/autoassign/metafile.yml @@ -0,0 +1,33 @@ +Collections: + - Name: AutoAssign + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - AutoAssign + - FPN + - ResNet + Paper: + URL: https://arxiv.org/abs/2007.03496 + Title: 'AutoAssign: Differentiable Label Assignment for Dense Object Detection' + README: configs/autoassign/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.12.0/mmdet/models/detectors/autoassign.py#L6 + Version: v2.12.0 + +Models: + - Name: autoassign_r50-caffe_fpn_1x_coco + In Collection: AutoAssign + Config: configs/autoassign/autoassign_r50-caffe_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.08 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 40.4 + Weights: https://download.openmmlab.com/mmdetection/v2.0/autoassign/auto_assign_r50_fpn_1x_coco/auto_assign_r50_fpn_1x_coco_20210413_115540-5e17991f.pth diff --git a/grounding-dino/mmdetection/configs/boxinst/README.md b/grounding-dino/mmdetection/configs/boxinst/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f6f01c5d27b13b1758a5c9a60251383852e0f48e --- /dev/null +++ b/grounding-dino/mmdetection/configs/boxinst/README.md @@ -0,0 +1,32 @@ +# BoxInst + +> [BoxInst: High-Performance Instance Segmentation with Box Annotations](https://arxiv.org/pdf/2012.02310.pdf) + + + +## Abstract + +We present a high-performance method that can achieve mask-level instance segmentation with only bounding-box annotations for training. While this setting has been studied in the literature, here we show significantly stronger performance with a simple design (e.g., dramatically improving previous best reported mask AP of 21.1% to 31.6% on the COCO dataset). Our core idea is to redesign the loss +of learning masks in instance segmentation, with no modification to the segmentation network itself. The new loss functions can supervise the mask training without relying on mask annotations. This is made possible with two loss terms, namely, 1) a surrogate term that minimizes the discrepancy between the projections of the ground-truth box and the predicted mask; 2) a pairwise loss that can exploit the prior that proximal pixels with similar colors are very likely to have the same category label. Experiments demonstrate that the redesigned mask loss can yield surprisingly high-quality instance masks with only box annotations. For example, without using any mask annotations, with a ResNet-101 backbone and 3× training schedule, we achieve 33.2% mask AP on COCO test-dev split (vs. 39.1% of the fully supervised counterpart). Our excellent experiment results on COCO and Pascal VOC indicate that our method dramatically narrows the performance gap between weakly and fully supervised instance segmentation. + +
+ +
+ +## Results and Models + +| Backbone | Style | MS train | Lr schd | bbox AP | mask AP | Config | Download | +| :------: | :-----: | :------: | :-----: | :-----: | :-----: | :-----------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50 | pytorch | Y | 1x | 39.6 | 31.1 | [config](./boxinst_r50_fpn_ms-90k_coco.py) | [model](https://download.openmmlab.com/mmdetection/v3.0/boxinst/boxinst_r50_fpn_ms-90k_coco/boxinst_r50_fpn_ms-90k_coco_20221228_163052-6add751a.pth) \| [log](https://download.openmmlab.com/mmdetection/v3.0/boxinst/boxinst_r50_fpn_ms-90k_coco/boxinst_r50_fpn_ms-90k_coco_20221228_163052.log.json) | +| R-101 | pytorch | Y | 1x | 41.8 | 32.7 | [config](./boxinst_r101_fpn_ms-90k_coco.py) | [model](https://download.openmmlab.com/mmdetection/v3.0/boxinst/boxinst_r101_fpn_ms-90k_coco/boxinst_r101_fpn_ms-90k_coco_20221229_145106-facf375b.pth) \|[log](https://download.openmmlab.com/mmdetection/v3.0/boxinst/boxinst_r101_fpn_ms-90k_coco/boxinst_r101_fpn_ms-90k_coco_20221229_145106.log.json) | + +## Citation + +```latex +@inproceedings{tian2020boxinst, + title = {{BoxInst}: High-Performance Instance Segmentation with Box Annotations}, + author = {Tian, Zhi and Shen, Chunhua and Wang, Xinlong and Chen, Hao}, + booktitle = {Proc. IEEE Conf. Computer Vision and Pattern Recognition (CVPR)}, + year = {2021} +} +``` diff --git a/grounding-dino/mmdetection/configs/boxinst/boxinst_r101_fpn_ms-90k_coco.py b/grounding-dino/mmdetection/configs/boxinst/boxinst_r101_fpn_ms-90k_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2b11628a79aee7f6f6403cecf8f7b1d0526d69 --- /dev/null +++ b/grounding-dino/mmdetection/configs/boxinst/boxinst_r101_fpn_ms-90k_coco.py @@ -0,0 +1,8 @@ +_base_ = './boxinst_r50_fpn_ms-90k_coco.py' + +# model settings +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/boxinst/boxinst_r50_fpn_ms-90k_coco.py b/grounding-dino/mmdetection/configs/boxinst/boxinst_r50_fpn_ms-90k_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..371f252a153855e19f3a3bb25cd42c83a4bb77fd --- /dev/null +++ b/grounding-dino/mmdetection/configs/boxinst/boxinst_r50_fpn_ms-90k_coco.py @@ -0,0 +1,93 @@ +_base_ = '../common/ms-90k_coco.py' + +# model settings +model = dict( + type='BoxInst', + data_preprocessor=dict( + type='BoxInstDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_size_divisor=32, + mask_stride=4, + pairwise_size=3, + pairwise_dilation=2, + pairwise_color_thresh=0.3, + bottom_pixels_removed=10), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=True, + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), + style='pytorch'), + neck=dict( + type='FPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + start_level=1, + add_extra_convs='on_output', # use P5 + num_outs=5, + relu_before_extra_convs=True), + bbox_head=dict( + type='BoxInstBboxHead', + num_params=593, + num_classes=80, + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + norm_on_bbox=True, + centerness_on_reg=True, + dcn_on_last_conv=False, + center_sampling=True, + conv_bias=True, + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + mask_head=dict( + type='BoxInstMaskHead', + num_layers=3, + feat_channels=16, + size_of_interest=8, + mask_out_stride=4, + topk_masks_per_img=64, + mask_feature_head=dict( + in_channels=256, + feat_channels=128, + start_level=0, + end_level=2, + out_channels=16, + mask_stride=8, + num_stacked_convs=4, + norm_cfg=dict(type='BN', requires_grad=True)), + loss_mask=dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + eps=5e-6, + loss_weight=1.0)), + # model training and testing settings + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100, + mask_thr=0.5)) + +# optimizer +optim_wrapper = dict(optimizer=dict(lr=0.01)) + +# evaluator +val_evaluator = dict(metric=['bbox', 'segm']) +test_evaluator = val_evaluator diff --git a/grounding-dino/mmdetection/configs/boxinst/metafile.yml b/grounding-dino/mmdetection/configs/boxinst/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..c97fcdcd636cd4d8d1a1437679f20b96d90fc74f --- /dev/null +++ b/grounding-dino/mmdetection/configs/boxinst/metafile.yml @@ -0,0 +1,52 @@ +Collections: + - Name: BoxInst + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x A100 GPUs + Architecture: + - ResNet + - FPN + - CondInst + Paper: + URL: https://arxiv.org/abs/2012.02310 + Title: 'BoxInst: High-Performance Instance Segmentation with Box Annotations' + README: configs/boxinst/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v3.0.0rc6/mmdet/models/detectors/boxinst.py#L8 + Version: v3.0.0rc6 + +Models: + - Name: boxinst_r50_fpn_ms-90k_coco + In Collection: BoxInst + Config: configs/boxinst/boxinst_r50_fpn_ms-90k_coco.py + Metadata: + Iterations: 90000 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 39.4 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 30.8 + Weights: https://download.openmmlab.com/mmdetection/v3.0/boxinst/boxinst_r50_fpn_ms-90k_coco/boxinst_r50_fpn_ms-90k_coco_20221228_163052-6add751a.pth + + - Name: boxinst_r101_fpn_ms-90k_coco + In Collection: BoxInst + Config: configs/boxinst/boxinst_r101_fpn_ms-90k_coco.py + Metadata: + Iterations: 90000 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.8 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 32.7 + Weights: https://download.openmmlab.com/mmdetection/v3.0/boxinst/boxinst_r101_fpn_ms-90k_coco/boxinst_r101_fpn_ms-90k_coco_20221229_145106-facf375b.pth diff --git a/grounding-dino/mmdetection/configs/bytetrack/README.md b/grounding-dino/mmdetection/configs/bytetrack/README.md new file mode 100644 index 0000000000000000000000000000000000000000..30b96f07cece7666c488972e315dbdcededdb21f --- /dev/null +++ b/grounding-dino/mmdetection/configs/bytetrack/README.md @@ -0,0 +1,132 @@ +# ByteTrack: Multi-Object Tracking by Associating Every Detection Box + +## Abstract + + + +Multi-object tracking (MOT) aims at estimating bounding boxes and identities of objects in videos. Most methods obtain identities by associating detection boxes whose scores are higher than a threshold. The objects with low detection scores, e.g. occluded objects, are simply thrown away, which brings non-negligible true object missing and fragmented trajectories. To solve this problem, we present a simple, effective and generic association method, tracking by associating every detection box instead of only the high score ones. For the low score detection boxes, we utilize their similarities with tracklets to recover true objects and filter out the background detections. When applied to 9 different state-of-the-art trackers, our method achieves consistent improvement on IDF1 score ranging from 1 to 10 points. To put forwards the state-of-the-art performance of MOT, we design a simple and strong tracker, named ByteTrack. For the first time, we achieve 80.3 MOTA, 77.3 IDF1 and 63.1 HOTA on the test set of MOT17 with 30 FPS running speed on a single V100 GPU. + + + +
+ +
+ +## Citation + + + +```latex +@inproceedings{zhang2021bytetrack, + title={ByteTrack: Multi-Object Tracking by Associating Every Detection Box}, + author={Zhang, Yifu and Sun, Peize and Jiang, Yi and Yu, Dongdong and Yuan, Zehuan and Luo, Ping and Liu, Wenyu and Wang, Xinggang}, + journal={arXiv preprint arXiv:2110.06864}, + year={2021} +} +``` + +## Results and models on MOT17 + +Please note that the performance on `MOT17-half-val` is comparable with the performance reported in the manuscript, while the performance on `MOT17-test` is lower than the performance reported in the manuscript. + +The reason is that ByteTrack tunes customized hyper-parameters (e.g., image resolution and the high threshold of detection score) for each video in `MOT17-test` set, while we use unified parameters. + +| Method | Detector | Train Set | Test Set | Public | Inf time (fps) | HOTA | MOTA | IDF1 | FP | FN | IDSw. | Config | Download | +| :-------: | :------: | :---------------------------: | :------------: | :----: | :------------: | :--: | :--: | :--: | :---: | :---: | :---: | :-------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| ByteTrack | YOLOX-X | CrowdHuman + MOT17-half-train | MOT17-half-val | N | - | 67.5 | 78.6 | 78.5 | 12852 | 21060 | 672 | [config](bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py) | [model](https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500-1985c9f0.pth) \| [log](https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500.log.json) | +| ByteTrack | YOLOX-X | CrowdHuman + MOT17-half-train | MOT17-test | N | - | 61.7 | 78.1 | 74.8 | 36705 | 85032 | 2049 | [config](bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17test.py) | [model](https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500-1985c9f0.pth) \| [log](https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500.log.json) | + +## Results and models on MOT20 + +Since there are only 4 videos in `MOT20-train`, ByteTrack is validated on `MOT17-train` rather than `MOT20-half-train`. + +Please note that the MOTA on `MOT20-test` is slightly lower than that reported in the manuscript, because we don't tune the threshold for each video. + +| Method | Detector | Train Set | Test Set | Public | Inf time (fps) | HOTA | MOTA | IDF1 | FP | FN | IDSw. | Config | Download | +| :-------: | :------: | :----------------------: | :---------: | :----: | :------------: | :--: | :--: | :--: | :----: | :----: | :---: | :------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| ByteTrack | YOLOX-X | CrowdHuman + MOT20-train | MOT17-train | N | - | 57.3 | 64.9 | 71.8 | 33,747 | 83,385 | 1,263 | [config](bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot20train_test-mot20test.py) | [model](https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot20-private_20220506_101040-9ce38a60.pth) \| [log](https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot20-private_20220506_101040.log.json) | +| ByteTrack | YOLOX-X | CrowdHuman + MOT20-train | MOT20-test | N | - | 61.5 | 77.0 | 75.4 | 33,083 | 84,433 | 1,345 | [config](bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot20train_test-mot20test.py) | [model](https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot20-private_20220506_101040-9ce38a60.pth) \| [log](https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot20-private_20220506_101040.log.json) | + +## Get started + +### 1. Development Environment Setup + +Tracking Development Environment Setup can refer to this [document](../../docs/en/get_started.md). + +### 2. Dataset Prepare + +Tracking Dataset Prepare can refer to this [document](../../docs/en/user_guides/tracking_dataset_prepare.md). + +### 3. Training + +Due to the influence of parameters such as learning rate in default configuration file, we recommend using 8 GPUs for training in order to reproduce accuracy. You can use the following command to start the training. + +**3.1 Joint training and tracking** + +Some algorithm like ByteTrack, OCSORT don't need reid model, so we provide joint training and tracking for convenient. + +```shell +# Training Bytetrack on crowdhuman and mot17-half-train dataset with following command +# The number after config file represents the number of GPUs used. Here we use 8 GPUs +bash tools/dist_train.sh configs/bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_test-mot17halfval.py 8 +``` + +**3.2 Separate training and tracking** + +Of course, we provide train detector independently like SORT, DeepSORT, StrongSORT. Then use this detector to track. + +```shell +# Training Bytetrack on crowdhuman and mot17-half-train dataset with following command +# The number after config file represents the number of GPUs used. Here we use 8 GPUs +bash tools/dist_train.sh configs/bytetrack/yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py 8 +``` + +If you want to know about more detailed usage of `train.py/dist_train.sh/slurm_train.sh`, +please refer to this [document](../../docs/en/user_guides/tracking_train_test.md). + +### 4. Testing and evaluation + +### 4.1 Example on MOTxx-halfval dataset + +**4.1.1 use joint trained detector to evaluating and testing** + +```shell +bash tools/dist_test_tracking.sh configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py 8 --checkpoint ${CHECKPOINT_FILE} +``` + +**4.1.2 use separate trained detector to evaluating and testing** + +```shell +bash tools/dist_test_tracking.sh configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py 8 --detector ${CHECKPOINT_FILE} +``` + +**4.1.3 use video_baesd to evaluating and testing** + +we also provide two_ways(img_based or video_based) to evaluating and testing. +if you want to use video_based to evaluating and testing, you can modify config as follows + +``` +val_dataloader = dict( + sampler=dict(type='DefaultSampler', shuffle=False, round_up=False)) +``` + +#### 4.2 Example on MOTxx-test dataset + +If you want to get the results of the [MOT Challenge](https://motchallenge.net/) test set, please use the following command to generate result files that can be used for submission. It will be stored in `./mot_17_test_res`, you can modify the saved path in `test_evaluator` of the config. + +```shell +bash tools/dist_test_tracking.sh configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17test.py 8 --checkpoint ${CHECKPOINT_FILE} +``` + +If you want to know about more detailed usage of `test_tracking.py/dist_test_tracking.sh/slurm_test_tracking.sh`, +please refer to this [document](../../docs/en/user_guides/tracking_train_test.md). + +### 5.Inference + +Use a single GPU to predict a video and save it as a video. + +```shell +python demo/mot_demo.py demo/demo_mot.mp4 configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py --checkpoint ${CHECKPOINT_FILE} --out mot.mp4 +``` + +If you want to know about more detailed usage of `mot_demo.py`, please refer to this [document](../../docs/en/user_guides/tracking_inference.md). diff --git a/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_test-mot17halfval.py b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_test-mot17halfval.py new file mode 100644 index 0000000000000000000000000000000000000000..24b3f7841947204f2ecea385dcfa8b97fa0c6e85 --- /dev/null +++ b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_test-mot17halfval.py @@ -0,0 +1,249 @@ +_base_ = ['../yolox/yolox_x_8xb8-300e_coco.py'] + +dataset_type = 'MOTChallengeDataset' +data_root = 'data/MOT17/' + +img_scale = (1440, 800) # weight, height +batch_size = 4 + +detector = _base_.model +detector.pop('data_preprocessor') +detector.bbox_head.update(dict(num_classes=1)) +detector.test_cfg.nms.update(dict(iou_threshold=0.7)) +detector['init_cfg'] = dict( + type='Pretrained', + checkpoint= # noqa: E251 + 'https://download.openmmlab.com/mmdetection/v2.0/yolox/yolox_x_8x8_300e_coco/yolox_x_8x8_300e_coco_20211126_140254-1ef88d67.pth' # noqa: E501 +) +del _base_.model + +model = dict( + type='ByteTrack', + data_preprocessor=dict( + type='TrackDataPreprocessor', + pad_size_divisor=32, + # in bytetrack, we provide joint train detector and evaluate tracking + # performance, use_det_processor means use independent detector + # data_preprocessor. of course, you can train detector independently + # like strongsort + use_det_processor=True, + batch_augments=[ + dict( + type='BatchSyncRandomResize', + random_size_range=(576, 1024), + size_divisor=32, + interval=10) + ]), + detector=detector, + tracker=dict( + type='ByteTracker', + motion=dict(type='KalmanFilter'), + obj_score_thrs=dict(high=0.6, low=0.1), + init_track_thr=0.7, + weight_iou_with_det_scores=True, + match_iou_thrs=dict(high=0.1, low=0.5, tentative=0.3), + num_frames_retain=30)) + +train_pipeline = [ + dict( + type='Mosaic', + img_scale=img_scale, + pad_val=114.0, + bbox_clip_border=False), + dict( + type='RandomAffine', + scaling_ratio_range=(0.1, 2), + border=(-img_scale[0] // 2, -img_scale[1] // 2), + bbox_clip_border=False), + dict( + type='MixUp', + img_scale=img_scale, + ratio_range=(0.8, 1.6), + pad_val=114.0, + bbox_clip_border=False), + dict(type='YOLOXHSVRandomAug'), + dict(type='RandomFlip', prob=0.5), + dict( + type='Resize', + scale=img_scale, + keep_ratio=True, + clip_object_border=False), + dict(type='Pad', size_divisor=32, pad_val=dict(img=(114.0, 114.0, 114.0))), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1, 1), keep_empty=False), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict( + type='TransformBroadcaster', + transforms=[ + dict(type='LoadImageFromFile', backend_args=_base_.backend_args), + dict(type='Resize', scale=img_scale, keep_ratio=True), + dict( + type='Pad', + size_divisor=32, + pad_val=dict(img=(114.0, 114.0, 114.0))), + dict(type='LoadTrackAnnotations'), + ]), + dict(type='PackTrackInputs') +] +train_dataloader = dict( + _delete_=True, + batch_size=batch_size, + num_workers=4, + persistent_workers=True, + pin_memory=True, + sampler=dict(type='DefaultSampler', shuffle=True), + dataset=dict( + type='MultiImageMixDataset', + dataset=dict( + type='ConcatDataset', + datasets=[ + dict( + type='CocoDataset', + data_root='data/MOT17', + ann_file='annotations/half-train_cocoformat.json', + data_prefix=dict(img='train'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + metainfo=dict(classes=('pedestrian', )), + pipeline=[ + dict( + type='LoadImageFromFile', + backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + ]), + dict( + type='CocoDataset', + data_root='data/crowdhuman', + ann_file='annotations/crowdhuman_train.json', + data_prefix=dict(img='train'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + metainfo=dict(classes=('pedestrian', )), + pipeline=[ + dict( + type='LoadImageFromFile', + backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + ]), + dict( + type='CocoDataset', + data_root='data/crowdhuman', + ann_file='annotations/crowdhuman_val.json', + data_prefix=dict(img='val'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + metainfo=dict(classes=('pedestrian', )), + pipeline=[ + dict( + type='LoadImageFromFile', + backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + ]), + ]), + pipeline=train_pipeline)) + +val_dataloader = dict( + _delete_=True, + batch_size=1, + num_workers=2, + persistent_workers=True, + pin_memory=True, + drop_last=False, + # video_based + # sampler=dict(type='DefaultSampler', shuffle=False, round_up=False), + sampler=dict(type='TrackImgSampler'), # image_based + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/half-val_cocoformat.json', + data_prefix=dict(img_path='train'), + test_mode=True, + pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# optimizer +# default 8 gpu +base_lr = 0.001 / 8 * batch_size +optim_wrapper = dict(optimizer=dict(lr=base_lr)) + +# some hyper parameters +# training settings +max_epochs = 80 +num_last_epochs = 10 +interval = 5 + +train_cfg = dict( + type='EpochBasedTrainLoop', + max_epochs=max_epochs, + val_begin=70, + val_interval=1) + +# learning policy +param_scheduler = [ + dict( + # use quadratic formula to warm up 1 epochs + type='QuadraticWarmupLR', + by_epoch=True, + begin=0, + end=1, + convert_to_iter_based=True), + dict( + # use cosine lr from 1 to 70 epoch + type='CosineAnnealingLR', + eta_min=base_lr * 0.05, + begin=1, + T_max=max_epochs - num_last_epochs, + end=max_epochs - num_last_epochs, + by_epoch=True, + convert_to_iter_based=True), + dict( + # use fixed lr during last 10 epochs + type='ConstantLR', + by_epoch=True, + factor=1, + begin=max_epochs - num_last_epochs, + end=max_epochs, + ) +] + +custom_hooks = [ + dict( + type='YOLOXModeSwitchHook', + num_last_epochs=num_last_epochs, + priority=48), + dict(type='SyncNormHook', priority=48), + dict( + type='EMAHook', + ema_type='ExpMomentumEMA', + momentum=0.0001, + update_buffers=True, + priority=49) +] + +default_hooks = dict( + checkpoint=dict( + _delete_=True, type='CheckpointHook', interval=1, max_keep_ckpts=10), + visualization=dict(type='TrackVisualizationHook', draw=False)) + +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='TrackLocalVisualizer', vis_backends=vis_backends, name='visualizer') + +# evaluator +val_evaluator = dict( + _delete_=True, + type='MOTChallengeMetric', + metric=['HOTA', 'CLEAR', 'Identity'], + postprocess_tracklet_cfg=[ + dict(type='InterpolateTracklets', min_num_frames=5, max_num_frames=20) + ]) +test_evaluator = val_evaluator + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (4 samples per GPU) +auto_scale_lr = dict(base_batch_size=32) + +del detector +del _base_.tta_model +del _base_.tta_pipeline +del _base_.train_dataset diff --git a/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot20train_test-mot20test.py b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot20train_test-mot20test.py new file mode 100644 index 0000000000000000000000000000000000000000..9202f5fbda29d2a1d4cc81322c99d638ebf475d6 --- /dev/null +++ b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot20train_test-mot20test.py @@ -0,0 +1,127 @@ +_base_ = [ + './bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py' +] + +dataset_type = 'MOTChallengeDataset' + +img_scale = (1600, 896) # weight, height + +model = dict( + data_preprocessor=dict( + type='TrackDataPreprocessor', + use_det_processor=True, + pad_size_divisor=32, + batch_augments=[ + dict(type='BatchSyncRandomResize', random_size_range=(640, 1152)) + ]), + tracker=dict( + weight_iou_with_det_scores=False, + match_iou_thrs=dict(high=0.3), + )) + +train_pipeline = [ + dict( + type='Mosaic', + img_scale=img_scale, + pad_val=114.0, + bbox_clip_border=True), + dict( + type='RandomAffine', + scaling_ratio_range=(0.1, 2), + border=(-img_scale[0] // 2, -img_scale[1] // 2), + bbox_clip_border=True), + dict( + type='MixUp', + img_scale=img_scale, + ratio_range=(0.8, 1.6), + pad_val=114.0, + bbox_clip_border=True), + dict(type='YOLOXHSVRandomAug'), + dict(type='RandomFlip', prob=0.5), + dict( + type='Resize', + scale=img_scale, + keep_ratio=True, + clip_object_border=True), + dict(type='Pad', size_divisor=32, pad_val=dict(img=(114.0, 114.0, 114.0))), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1, 1), keep_empty=False), + dict(type='PackDetInputs') +] + +test_pipeline = [ + dict( + type='TransformBroadcaster', + transforms=[ + dict(type='LoadImageFromFile', backend_args=_base_.backend_args), + dict(type='Resize', scale=img_scale, keep_ratio=True), + dict( + type='Pad', + size_divisor=32, + pad_val=dict(img=(114.0, 114.0, 114.0))), + dict(type='LoadTrackAnnotations'), + ]), + dict(type='PackTrackInputs') +] +train_dataloader = dict( + dataset=dict( + type='MultiImageMixDataset', + dataset=dict( + type='ConcatDataset', + datasets=[ + dict( + type='CocoDataset', + data_root='data/MOT20', + ann_file='annotations/train_cocoformat.json', + # TODO: mmdet use img as key, but img_path is needed + data_prefix=dict(img='train'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + metainfo=dict(classes=('pedestrian', )), + pipeline=[ + dict( + type='LoadImageFromFile', + backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + ]), + dict( + type='CocoDataset', + data_root='data/crowdhuman', + ann_file='annotations/crowdhuman_train.json', + data_prefix=dict(img='train'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + metainfo=dict(classes=('pedestrian', )), + pipeline=[ + dict( + type='LoadImageFromFile', + backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + ]), + dict( + type='CocoDataset', + data_root='data/crowdhuman', + ann_file='annotations/crowdhuman_val.json', + data_prefix=dict(img='val'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + metainfo=dict(classes=('pedestrian', )), + pipeline=[ + dict( + type='LoadImageFromFile', + backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + ]), + ]), + pipeline=train_pipeline)) +val_dataloader = dict( + dataset=dict(ann_file='annotations/train_cocoformat.json')) + +test_dataloader = dict( + dataset=dict( + data_root='data/MOT20', ann_file='annotations/test_cocoformat.json')) + +test_evaluator = dict( + type='MOTChallengeMetrics', + postprocess_tracklet_cfg=[ + dict(type='InterpolateTracklets', min_num_frames=5, max_num_frames=20) + ], + format_only=True, + outfile_prefix='./mot_20_test_res') diff --git a/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py new file mode 100644 index 0000000000000000000000000000000000000000..9c2119203a46e76cd8b6cc8f755334f58ffb086d --- /dev/null +++ b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py @@ -0,0 +1,9 @@ +_base_ = [ + './bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_' + 'test-mot17halfval.py' +] + +# fp16 settings +optim_wrapper = dict(type='AmpOptimWrapper', loss_scale='dynamic') +val_cfg = dict(type='ValLoop', fp16=True) +test_cfg = dict(type='TestLoop', fp16=True) diff --git a/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17test.py b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17test.py new file mode 100644 index 0000000000000000000000000000000000000000..3f4427c18bff66ab1fa2a9ba22517989722d0625 --- /dev/null +++ b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17test.py @@ -0,0 +1,17 @@ +_base_ = [ + './bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-' + 'mot17halftrain_test-mot17halfval.py' +] + +test_dataloader = dict( + dataset=dict( + data_root='data/MOT17/', + ann_file='annotations/test_cocoformat.json', + data_prefix=dict(img_path='test'))) +test_evaluator = dict( + type='MOTChallengeMetrics', + postprocess_tracklet_cfg=[ + dict(type='InterpolateTracklets', min_num_frames=5, max_num_frames=20) + ], + format_only=True, + outfile_prefix='./mot_17_test_res') diff --git a/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot20train_test-mot20test.py b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot20train_test-mot20test.py new file mode 100644 index 0000000000000000000000000000000000000000..1016999729263d72bbd75019be4968bc3960e368 --- /dev/null +++ b/grounding-dino/mmdetection/configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot20train_test-mot20test.py @@ -0,0 +1,8 @@ +_base_ = [ + './bytetrack_yolox_x_8xb4-80e_crowdhuman-mot20train_test-mot20test.py' +] + +# fp16 settings +optim_wrapper = dict(type='AmpOptimWrapper', loss_scale='dynamic') +val_cfg = dict(type='ValLoop', fp16=True) +test_cfg = dict(type='TestLoop', fp16=True) diff --git a/grounding-dino/mmdetection/configs/bytetrack/metafile.yml b/grounding-dino/mmdetection/configs/bytetrack/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..8ed638cf6dda0b0b3db264aa8847358d78ee0fbe --- /dev/null +++ b/grounding-dino/mmdetection/configs/bytetrack/metafile.yml @@ -0,0 +1,53 @@ +Collections: + - Name: ByteTrack + Metadata: + Training Techniques: + - SGD with Momentum + Training Resources: 8x V100 GPUs + Architecture: + - YOLOX + Paper: + URL: https://arxiv.org/abs/2110.06864 + Title: ByteTrack Multi-Object Tracking by Associating Every Detection Box + README: configs/bytetrack/README.md + +Models: + - Name: bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval + In Collection: ByteTrack + Config: configs/bytetrack/bytetrack_yolox_x_8xb4-80e_crowdhuman-mot17halftrain_test-mot17halfval.py + Metadata: + Training Data: CrowdHuman + MOT17-half-train + Results: + - Task: Multiple Object Tracking + Dataset: MOT17-half-val + Metrics: + HOTA: 67.5 + MOTA: 78.6 + IDF1: 78.5 + Weights: https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500-1985c9f0.pth + + - Name: bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17test + In Collection: ByteTrack + Config: configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17test.py + Metadata: + Training Data: CrowdHuman + MOT17-half-train + Results: + - Task: Multiple Object Tracking + Dataset: MOT17-test + Metrics: + MOTA: 78.1 + IDF1: 74.8 + Weights: https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot17-private-half_20211218_205500-1985c9f0.pth + + - Name: bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot20train_test-mot20test + In Collection: ByteTrack + Config: configs/bytetrack/bytetrack_yolox_x_8xb4-amp-80e_crowdhuman-mot20train_test-mot20test.py + Metadata: + Training Data: CrowdHuman + MOT20-train + Results: + - Task: Multiple Object Tracking + Dataset: MOT20-test + Metrics: + MOTA: 77.0 + IDF1: 75.4 + Weights: https://download.openmmlab.com/mmtracking/mot/bytetrack/bytetrack_yolox_x/bytetrack_yolox_x_crowdhuman_mot20-private_20220506_101040-9ce38a60.pth diff --git a/grounding-dino/mmdetection/configs/bytetrack/yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py b/grounding-dino/mmdetection/configs/bytetrack/yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc3acd487211d04fb3d6e4504ded5235393e4a7 --- /dev/null +++ b/grounding-dino/mmdetection/configs/bytetrack/yolox_x_8xb4-amp-80e_crowdhuman-mot17halftrain_test-mot17halfval.py @@ -0,0 +1,6 @@ +_base_ = [ + '../strongsort/yolox_x_8xb4-80e_crowdhuman-mot17halftrain_test-mot17halfval.py' # noqa: E501 +] + +# fp16 settings +optim_wrapper = dict(type='AmpOptimWrapper', loss_scale='dynamic') diff --git a/grounding-dino/mmdetection/configs/carafe/README.md b/grounding-dino/mmdetection/configs/carafe/README.md new file mode 100644 index 0000000000000000000000000000000000000000..61e1fa60fee5d1dc89539874c784c75df63b2ad3 --- /dev/null +++ b/grounding-dino/mmdetection/configs/carafe/README.md @@ -0,0 +1,42 @@ +# CARAFE + +> [CARAFE: Content-Aware ReAssembly of FEatures](https://arxiv.org/abs/1905.02188) + + + +## Abstract + +Feature upsampling is a key operation in a number of modern convolutional network architectures, e.g. feature pyramids. Its design is critical for dense prediction tasks such as object detection and semantic/instance segmentation. In this work, we propose Content-Aware ReAssembly of FEatures (CARAFE), a universal, lightweight and highly effective operator to fulfill this goal. CARAFE has several appealing properties: (1) Large field of view. Unlike previous works (e.g. bilinear interpolation) that only exploit sub-pixel neighborhood, CARAFE can aggregate contextual information within a large receptive field. (2) Content-aware handling. Instead of using a fixed kernel for all samples (e.g. deconvolution), CARAFE enables instance-specific content-aware handling, which generates adaptive kernels on-the-fly. (3) Lightweight and fast to compute. CARAFE introduces little computational overhead and can be readily integrated into modern network architectures. We conduct comprehensive evaluations on standard benchmarks in object detection, instance/semantic segmentation and inpainting. CARAFE shows consistent and substantial gains across all the tasks (1.2%, 1.3%, 1.8%, 1.1db respectively) with negligible computational overhead. It has great potential to serve as a strong building block for future research. It has great potential to serve as a strong building block for future research. + +
+ +
+ +## Results and Models + +The results on COCO 2017 val is shown in the below table. + +| Method | Backbone | Style | Lr schd | Test Proposal Num | Inf time (fps) | Box AP | Mask AP | Config | Download | +| :--------------------: | :------: | :-----: | :-----: | :---------------: | :------------: | :----: | :-----: | :-----------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| Faster R-CNN w/ CARAFE | R-50-FPN | pytorch | 1x | 1000 | 16.5 | 38.6 | 38.6 | [config](./faster-rcnn_r50_fpn-carafe_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/carafe/faster_rcnn_r50_fpn_carafe_1x_coco/faster_rcnn_r50_fpn_carafe_1x_coco_bbox_mAP-0.386_20200504_175733-385a75b7.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/carafe/faster_rcnn_r50_fpn_carafe_1x_coco/faster_rcnn_r50_fpn_carafe_1x_coco_20200504_175733.log.json) | +| - | - | - | - | 2000 | | | | | | +| Mask R-CNN w/ CARAFE | R-50-FPN | pytorch | 1x | 1000 | 14.0 | 39.3 | 35.8 | [config](./mask-rcnn_r50_fpn-carafe_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/carafe/mask_rcnn_r50_fpn_carafe_1x_coco/mask_rcnn_r50_fpn_carafe_1x_coco_bbox_mAP-0.393__segm_mAP-0.358_20200503_135957-8687f195.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/carafe/mask_rcnn_r50_fpn_carafe_1x_coco/mask_rcnn_r50_fpn_carafe_1x_coco_20200503_135957.log.json) | +| - | - | - | - | 2000 | | | | | | + +## Implementation + +The CUDA implementation of CARAFE can be find at https://github.com/myownskyW7/CARAFE. + +## Citation + +We provide config files to reproduce the object detection & instance segmentation results in the ICCV 2019 Oral paper for [CARAFE: Content-Aware ReAssembly of FEatures](https://arxiv.org/abs/1905.02188). + +```latex +@inproceedings{Wang_2019_ICCV, + title = {CARAFE: Content-Aware ReAssembly of FEatures}, + author = {Wang, Jiaqi and Chen, Kai and Xu, Rui and Liu, Ziwei and Loy, Chen Change and Lin, Dahua}, + booktitle = {The IEEE International Conference on Computer Vision (ICCV)}, + month = {October}, + year = {2019} +} +``` diff --git a/grounding-dino/mmdetection/configs/carafe/faster-rcnn_r50_fpn-carafe_1x_coco.py b/grounding-dino/mmdetection/configs/carafe/faster-rcnn_r50_fpn-carafe_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..388305cceac2e81eb1b4df6eac36662df7b8bf0d --- /dev/null +++ b/grounding-dino/mmdetection/configs/carafe/faster-rcnn_r50_fpn-carafe_1x_coco.py @@ -0,0 +1,20 @@ +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + data_preprocessor=dict(pad_size_divisor=64), + neck=dict( + type='FPN_CARAFE', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5, + start_level=0, + end_level=-1, + norm_cfg=None, + act_cfg=None, + order=('conv', 'norm', 'act'), + upsample_cfg=dict( + type='carafe', + up_kernel=5, + up_group=1, + encoder_kernel=3, + encoder_dilation=1, + compressed_channels=64))) diff --git a/grounding-dino/mmdetection/configs/carafe/mask-rcnn_r50_fpn-carafe_1x_coco.py b/grounding-dino/mmdetection/configs/carafe/mask-rcnn_r50_fpn-carafe_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce621de77aff60f39126136cb25ca9ca38a1c9f --- /dev/null +++ b/grounding-dino/mmdetection/configs/carafe/mask-rcnn_r50_fpn-carafe_1x_coco.py @@ -0,0 +1,30 @@ +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + data_preprocessor=dict(pad_size_divisor=64), + neck=dict( + type='FPN_CARAFE', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5, + start_level=0, + end_level=-1, + norm_cfg=None, + act_cfg=None, + order=('conv', 'norm', 'act'), + upsample_cfg=dict( + type='carafe', + up_kernel=5, + up_group=1, + encoder_kernel=3, + encoder_dilation=1, + compressed_channels=64)), + roi_head=dict( + mask_head=dict( + upsample_cfg=dict( + type='carafe', + scale_factor=2, + up_kernel=5, + up_group=1, + encoder_kernel=3, + encoder_dilation=1, + compressed_channels=64)))) diff --git a/grounding-dino/mmdetection/configs/carafe/metafile.yml b/grounding-dino/mmdetection/configs/carafe/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..863c0f49ae6322429e91cf068b06f713a29fcbdc --- /dev/null +++ b/grounding-dino/mmdetection/configs/carafe/metafile.yml @@ -0,0 +1,55 @@ +Collections: + - Name: CARAFE + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - RPN + - FPN_CARAFE + - ResNet + - RoIPool + Paper: + URL: https://arxiv.org/abs/1905.02188 + Title: 'CARAFE: Content-Aware ReAssembly of FEatures' + README: configs/carafe/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.12.0/mmdet/models/necks/fpn_carafe.py#L11 + Version: v2.12.0 + +Models: + - Name: faster-rcnn_r50_fpn_carafe_1x_coco + In Collection: CARAFE + Config: configs/carafe/faster-rcnn_r50_fpn-carafe_1x_coco.py + Metadata: + Training Memory (GB): 4.26 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 38.6 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 38.6 + Weights: https://download.openmmlab.com/mmdetection/v2.0/carafe/faster_rcnn_r50_fpn_carafe_1x_coco/faster_rcnn_r50_fpn_carafe_1x_coco_bbox_mAP-0.386_20200504_175733-385a75b7.pth + + - Name: mask-rcnn_r50_fpn_carafe_1x_coco + In Collection: CARAFE + Config: configs/carafe/mask-rcnn_r50_fpn-carafe_1x_coco.py + Metadata: + Training Memory (GB): 4.31 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 39.3 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 35.6 + Weights: https://download.openmmlab.com/mmdetection/v2.0/carafe/mask_rcnn_r50_fpn_carafe_1x_coco/mask_rcnn_r50_fpn_carafe_1x_coco_bbox_mAP-0.393__segm_mAP-0.358_20200503_135957-8687f195.pth diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/README.md b/grounding-dino/mmdetection/configs/cascade_rcnn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..81fce448f9daec77b3e716ac731dce13be751c74 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/README.md @@ -0,0 +1,79 @@ +# Cascade R-CNN + +> [Cascade R-CNN: High Quality Object Detection and Instance Segmentation](https://arxiv.org/abs/1906.09756) + + + +## Abstract + +In object detection, the intersection over union (IoU) threshold is frequently used to define positives/negatives. The threshold used to train a detector defines its quality. While the commonly used threshold of 0.5 leads to noisy (low-quality) detections, detection performance frequently degrades for larger thresholds. This paradox of high-quality detection has two causes: 1) overfitting, due to vanishing positive samples for large thresholds, and 2) inference-time quality mismatch between detector and test hypotheses. A multi-stage object detection architecture, the Cascade R-CNN, composed of a sequence of detectors trained with increasing IoU thresholds, is proposed to address these problems. The detectors are trained sequentially, using the output of a detector as training set for the next. This resampling progressively improves hypotheses quality, guaranteeing a positive training set of equivalent size for all detectors and minimizing overfitting. The same cascade is applied at inference, to eliminate quality mismatches between hypotheses and detectors. An implementation of the Cascade R-CNN without bells or whistles achieves state-of-the-art performance on the COCO dataset, and significantly improves high-quality detection on generic and specific object detection datasets, including VOC, KITTI, CityPerson, and WiderFace. Finally, the Cascade R-CNN is generalized to instance segmentation, with nontrivial improvements over the Mask R-CNN. + +
+ +
+ +## Results and Models + +### Cascade R-CNN + +| Backbone | Style | Lr schd | Mem (GB) | Inf time (fps) | box AP | Config | Download | +| :-------------: | :-----: | :-----: | :------: | :------------: | :----: | :-------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50-FPN | caffe | 1x | 4.2 | | 40.4 | [config](./cascade-rcnn_r50-caffe_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_caffe_fpn_1x_coco/cascade_rcnn_r50_caffe_fpn_1x_coco_bbox_mAP-0.404_20200504_174853-b857be87.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_caffe_fpn_1x_coco/cascade_rcnn_r50_caffe_fpn_1x_coco_20200504_174853.log.json) | +| R-50-FPN | pytorch | 1x | 4.4 | 16.1 | 40.3 | [config](./cascade-rcnn_r50_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco/cascade_rcnn_r50_fpn_1x_coco_20200316-3dc56deb.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco/cascade_rcnn_r50_fpn_1x_coco_20200316_214748.log.json) | +| R-50-FPN | pytorch | 20e | - | - | 41.0 | [config](./cascade-rcnn_r50_fpn_20e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_fpn_20e_coco/cascade_rcnn_r50_fpn_20e_coco_bbox_mAP-0.41_20200504_175131-e9872a90.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_fpn_20e_coco/cascade_rcnn_r50_fpn_20e_coco_20200504_175131.log.json) | +| R-101-FPN | caffe | 1x | 6.2 | | 42.3 | [config](./cascade-rcnn_r101-caffe_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_caffe_fpn_1x_coco/cascade_rcnn_r101_caffe_fpn_1x_coco_bbox_mAP-0.423_20200504_175649-cab8dbd5.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_caffe_fpn_1x_coco/cascade_rcnn_r101_caffe_fpn_1x_coco_20200504_175649.log.json) | +| R-101-FPN | pytorch | 1x | 6.4 | 13.5 | 42.0 | [config](./cascade-rcnn_r101_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_fpn_1x_coco/cascade_rcnn_r101_fpn_1x_coco_20200317-0b6a2fbf.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_fpn_1x_coco/cascade_rcnn_r101_fpn_1x_coco_20200317_101744.log.json) | +| R-101-FPN | pytorch | 20e | - | - | 42.5 | [config](./cascade-rcnn_r101_fpn_20e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_fpn_20e_coco/cascade_rcnn_r101_fpn_20e_coco_bbox_mAP-0.425_20200504_231812-5057dcc5.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_fpn_20e_coco/cascade_rcnn_r101_fpn_20e_coco_20200504_231812.log.json) | +| X-101-32x4d-FPN | pytorch | 1x | 7.6 | 10.9 | 43.7 | [config](./cascade-rcnn_x101-32x4d_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_32x4d_fpn_1x_coco/cascade_rcnn_x101_32x4d_fpn_1x_coco_20200316-95c2deb6.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_32x4d_fpn_1x_coco/cascade_rcnn_x101_32x4d_fpn_1x_coco_20200316_055608.log.json) | +| X-101-32x4d-FPN | pytorch | 20e | 7.6 | | 43.7 | [config](./cascade-rcnn_x101-32x4d_fpn_20e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_32x4d_fpn_20e_coco/cascade_rcnn_x101_32x4d_fpn_20e_coco_20200906_134608-9ae0a720.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_32x4d_fpn_20e_coco/cascade_rcnn_x101_32x4d_fpn_20e_coco_20200906_134608.log.json) | +| X-101-64x4d-FPN | pytorch | 1x | 10.7 | | 44.7 | [config](./cascade-rcnn_x101-64x4d_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_64x4d_fpn_1x_coco/cascade_rcnn_x101_64x4d_fpn_1x_coco_20200515_075702-43ce6a30.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_64x4d_fpn_1x_coco/cascade_rcnn_x101_64x4d_fpn_1x_coco_20200515_075702.log.json) | +| X-101-64x4d-FPN | pytorch | 20e | 10.7 | | 44.5 | [config](./cascade-rcnn_x101_64x4d_fpn_20e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_64x4d_fpn_20e_coco/cascade_rcnn_x101_64x4d_fpn_20e_coco_20200509_224357-051557b1.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_64x4d_fpn_20e_coco/cascade_rcnn_x101_64x4d_fpn_20e_coco_20200509_224357.log.json) | + +### Cascade Mask R-CNN + +| Backbone | Style | Lr schd | Mem (GB) | Inf time (fps) | box AP | mask AP | Config | Download | +| :-------------: | :-----: | :-----: | :------: | :------------: | :----: | :-----: | :------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50-FPN | caffe | 1x | 5.9 | | 41.2 | 36.0 | [config](./cascade-mask-rcnn_r50-caffe_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_caffe_fpn_1x_coco/cascade_mask_rcnn_r50_caffe_fpn_1x_coco_bbox_mAP-0.412__segm_mAP-0.36_20200504_174659-5004b251.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_caffe_fpn_1x_coco/cascade_mask_rcnn_r50_caffe_fpn_1x_coco_20200504_174659.log.json) | +| R-50-FPN | pytorch | 1x | 6.0 | 11.2 | 41.2 | 35.9 | [config](./cascade-mask-rcnn_r50_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco/cascade_mask_rcnn_r50_fpn_1x_coco_20200203-9d4dcb24.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco/cascade_mask_rcnn_r50_fpn_1x_coco_20200203_170449.log.json) | +| R-50-FPN | pytorch | 20e | - | - | 41.9 | 36.5 | [config](./cascade-mask-rcnn_r50_fpn_20e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_20e_coco/cascade_mask_rcnn_r50_fpn_20e_coco_bbox_mAP-0.419__segm_mAP-0.365_20200504_174711-4af8e66e.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_20e_coco/cascade_mask_rcnn_r50_fpn_20e_coco_20200504_174711.log.json) | +| R-101-FPN | caffe | 1x | 7.8 | | 43.2 | 37.6 | [config](./cascade-mask-rcnn_r101-caffe_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_caffe_fpn_1x_coco/cascade_mask_rcnn_r101_caffe_fpn_1x_coco_bbox_mAP-0.432__segm_mAP-0.376_20200504_174813-5c1e9599.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_caffe_fpn_1x_coco/cascade_mask_rcnn_r101_caffe_fpn_1x_coco_20200504_174813.log.json) | +| R-101-FPN | pytorch | 1x | 7.9 | 9.8 | 42.9 | 37.3 | [config](./cascade-mask-rcnn_r101_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_1x_coco/cascade_mask_rcnn_r101_fpn_1x_coco_20200203-befdf6ee.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_1x_coco/cascade_mask_rcnn_r101_fpn_1x_coco_20200203_092521.log.json) | +| R-101-FPN | pytorch | 20e | - | - | 43.4 | 37.8 | [config](./cascade-mask-rcnn_r101_fpn_20e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_20e_coco/cascade_mask_rcnn_r101_fpn_20e_coco_bbox_mAP-0.434__segm_mAP-0.378_20200504_174836-005947da.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_20e_coco/cascade_mask_rcnn_r101_fpn_20e_coco_20200504_174836.log.json) | +| X-101-32x4d-FPN | pytorch | 1x | 9.2 | 8.6 | 44.3 | 38.3 | [config](./cascade-mask-rcnn_x101-32x4d_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_1x_coco/cascade_mask_rcnn_x101_32x4d_fpn_1x_coco_20200201-0f411b1f.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_1x_coco/cascade_mask_rcnn_x101_32x4d_fpn_1x_coco_20200201_052416.log.json) | +| X-101-32x4d-FPN | pytorch | 20e | 9.2 | - | 45.0 | 39.0 | [config](./cascade-mask-rcnn_x101-32x4d_fpn_20e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_20e_coco/cascade_mask_rcnn_x101_32x4d_fpn_20e_coco_20200528_083917-ed1f4751.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_20e_coco/cascade_mask_rcnn_x101_32x4d_fpn_20e_coco_20200528_083917.log.json) | +| X-101-64x4d-FPN | pytorch | 1x | 12.2 | 6.7 | 45.3 | 39.2 | [config](./cascade-mask-rcnn_x101-64x4d_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco_20200203-9a2db89d.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco_20200203_044059.log.json) | +| X-101-64x4d-FPN | pytorch | 20e | 12.2 | | 45.6 | 39.5 | [config](./cascade-mask-rcnn_x101-64x4d_fpn_20e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_20e_coco/cascade_mask_rcnn_x101_64x4d_fpn_20e_coco_20200512_161033-bdb5126a.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_20e_coco/cascade_mask_rcnn_x101_64x4d_fpn_20e_coco_20200512_161033.log.json) | + +**Notes:** + +- The `20e` schedule in Cascade (Mask) R-CNN indicates decreasing the lr at 16 and 19 epochs, with a total of 20 epochs. + +## Pre-trained Models + +We also train some models with longer schedules and multi-scale training for Cascade Mask R-CNN. The users could finetune them for downstream tasks. + +| Backbone | Style | Lr schd | Mem (GB) | Inf time (fps) | box AP | mask AP | Config | Download | +| :-------------: | :-----: | :-----: | :------: | :------------: | :----: | :-----: | :--------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50-FPN | caffe | 3x | 5.7 | | 44.0 | 38.1 | [config](./cascade-mask-rcnn_r50-caffe_fpn_ms-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_caffe_fpn_mstrain_3x_coco/cascade_mask_rcnn_r50_caffe_fpn_mstrain_3x_coco_20210707_002651-6e29b3a6.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_caffe_fpn_mstrain_3x_coco/cascade_mask_rcnn_r50_caffe_fpn_mstrain_3x_coco_20210707_002651.log.json) | +| R-50-FPN | pytorch | 3x | 5.9 | | 44.3 | 38.5 | [config](./cascade-mask-rcnn_r50_fpn_ms-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco_20210628_164719-5bdc3824.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco_20210628_164719.log.json) | +| R-101-FPN | caffe | 3x | 7.7 | | 45.4 | 39.5 | [config](./cascade-mask-rcnn_r101-caffe_fpn_ms-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_caffe_fpn_mstrain_3x_coco/cascade_mask_rcnn_r101_caffe_fpn_mstrain_3x_coco_20210707_002620-a5bd2389.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_caffe_fpn_mstrain_3x_coco/cascade_mask_rcnn_r101_caffe_fpn_mstrain_3x_coco_20210707_002620.log.json) | +| R-101-FPN | pytorch | 3x | 7.8 | | 45.5 | 39.6 | [config](./cascade-mask-rcnn_r101_fpn_ms-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_mstrain_3x_coco/cascade_mask_rcnn_r101_fpn_mstrain_3x_coco_20210628_165236-51a2d363.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_mstrain_3x_coco/cascade_mask_rcnn_r101_fpn_mstrain_3x_coco_20210628_165236.log.json) | +| X-101-32x4d-FPN | pytorch | 3x | 9.0 | | 46.3 | 40.1 | [config](./cascade-mask-rcnn_x101-32x4d_fpn_ms-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco_20210706_225234-40773067.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco_20210706_225234.log.json) | +| X-101-32x8d-FPN | pytorch | 3x | 12.1 | | 46.1 | 39.9 | [config](./cascade-mask-rcnn_x101-32x8d_fpn_ms-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x8d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_32x8d_fpn_mstrain_3x_coco_20210719_180640-9ff7e76f.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x8d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_32x8d_fpn_mstrain_3x_coco_20210719_180640.log.json) | +| X-101-64x4d-FPN | pytorch | 3x | 12.0 | | 46.6 | 40.3 | [config](./cascade-mask-rcnn_x101-64x4d_fpn_ms-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_64x4d_fpn_mstrain_3x_coco_20210719_210311-d3e64ba0.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_64x4d_fpn_mstrain_3x_coco_20210719_210311.log.json) | + +## Citation + +```latex +@article{Cai_2019, + title={Cascade R-CNN: High Quality Object Detection and Instance Segmentation}, + ISSN={1939-3539}, + url={http://dx.doi.org/10.1109/tpami.2019.2956516}, + DOI={10.1109/tpami.2019.2956516}, + journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, + publisher={Institute of Electrical and Electronics Engineers (IEEE)}, + author={Cai, Zhaowei and Vasconcelos, Nuno}, + year={2019}, + pages={1–1} +} +``` diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101-caffe_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101-caffe_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..6d85340e1cb92c60293c3710d05ef708d3726fdd --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101-caffe_fpn_1x_coco.py @@ -0,0 +1,7 @@ +_base_ = './cascade-mask-rcnn_r50-caffe_fpn_1x_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet101_caffe'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101-caffe_fpn_ms-3x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101-caffe_fpn_ms-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..a6855ee8c6fffd5e8d48f6cc2bb41e9dde9f6516 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101-caffe_fpn_ms-3x_coco.py @@ -0,0 +1,7 @@ +_base_ = './cascade-mask-rcnn_r50-caffe_fpn_ms-3x_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet101_caffe'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..c3d962c229d2621e7364c13959e3c4c1137edef1 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_1x_coco.py @@ -0,0 +1,6 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_20e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_20e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..497148f513edb79ca58f719f242be6274f923a65 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_20e_coco.py @@ -0,0 +1,6 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_20e_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_ms-3x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_ms-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..183b5c50ff5563d987b2937d27d6d02bdd6cc2bd --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_ms-3x_coco.py @@ -0,0 +1,6 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_ms-3x_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50-caffe_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50-caffe_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..497f68c4ab458ec49ad1d0c89cabbb2c0eb444f3 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50-caffe_fpn_1x_coco.py @@ -0,0 +1,14 @@ +_base_ = ['./cascade-mask-rcnn_r50_fpn_1x_coco.py'] + +model = dict( + data_preprocessor=dict( + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False), + backbone=dict( + norm_cfg=dict(requires_grad=False), + norm_eval=True, + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50-caffe_fpn_ms-3x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50-caffe_fpn_ms-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..6677a9fea501a7683475dc8b865659cef5485bbe --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50-caffe_fpn_ms-3x_coco.py @@ -0,0 +1,18 @@ +_base_ = [ + '../common/ms_3x_coco-instance.py', + '../_base_/models/cascade-mask-rcnn_r50_fpn.py' +] + +model = dict( + # use caffe img_norm + data_preprocessor=dict( + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False), + backbone=dict( + norm_cfg=dict(requires_grad=False), + norm_eval=True, + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..f59bb94eaaf3e850e971268383cd0275bcddf54d --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = [ + '../_base_/models/cascade-mask-rcnn_r50_fpn.py', + '../_base_/datasets/coco_instance.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_20e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_20e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..35c8aa6748d25e4c9c834478488ee21b44c8f2bd --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_20e_coco.py @@ -0,0 +1,5 @@ +_base_ = [ + '../_base_/models/cascade-mask-rcnn_r50_fpn.py', + '../_base_/datasets/coco_instance.py', + '../_base_/schedules/schedule_20e.py', '../_base_/default_runtime.py' +] diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_ms-3x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_ms-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..b15006f451f346216243dc61140e9907535f0b20 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_ms-3x_coco.py @@ -0,0 +1,4 @@ +_base_ = [ + '../common/ms_3x_coco-instance.py', + '../_base_/models/cascade-mask-rcnn_r50_fpn.py' +] diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..87a4cc325a10b01cbf5a91e336da2281bc19a728 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_1x_coco.py @@ -0,0 +1,14 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=32, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_20e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_20e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8dcaa6891877c89acb024b9811a4fe7a87bc3b --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_20e_coco.py @@ -0,0 +1,14 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_20e_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=32, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_ms-3x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_ms-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0f61b9aee2b0ab80c5c9b998a73826e5ff45a6 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_ms-3x_coco.py @@ -0,0 +1,14 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_ms-3x_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=32, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x8d_fpn_ms-3x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x8d_fpn_ms-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf08306850bdaef776a0ce53b88b23b9013a1a0 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-32x8d_fpn_ms-3x_coco.py @@ -0,0 +1,24 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_ms-3x_coco.py' + +model = dict( + # ResNeXt-101-32x8d model trained with Caffe2 at FB, + # so the mean and std need to be changed. + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[103.530, 116.280, 123.675], + std=[57.375, 57.120, 58.395], + bgr_to_rgb=False, + pad_size_divisor=32), + backbone=dict( + type='ResNeXt', + depth=101, + groups=32, + base_width=8, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=False), + style='pytorch', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnext101_32x8d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2e6b6b9507dcf38403d38499e1d57bd792a4da --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_1x_coco.py @@ -0,0 +1,14 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=64, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_20e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_20e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..cc20c171542b5d75634d99d9ed25eea3acf8df19 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_20e_coco.py @@ -0,0 +1,14 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_20e_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=64, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_ms-3x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_ms-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..f4ecc42655903c271e7e181b719d09821118a204 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_ms-3x_coco.py @@ -0,0 +1,14 @@ +_base_ = './cascade-mask-rcnn_r50_fpn_ms-3x_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=64, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101-caffe_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101-caffe_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..b6eaee2db700b897255ed44a5fd30bc23929388f --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101-caffe_fpn_1x_coco.py @@ -0,0 +1,7 @@ +_base_ = './cascade-rcnn_r50-caffe_fpn_1x_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet101_caffe'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..1cdf5108b7d2908e420c52c59f8a9805c7989702 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_1x_coco.py @@ -0,0 +1,6 @@ +_base_ = './cascade-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_20e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_20e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..84c285fc9e59d4191e79dd337ece2baff3d38b02 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_20e_coco.py @@ -0,0 +1,6 @@ +_base_ = './cascade-rcnn_r50_fpn_20e_coco.py' +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..1fc52e9cb8e1e9c27d45e32200b0b72efa8c363d --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r101_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,7 @@ +_base_ = './cascade-rcnn_r50_fpn_8xb8-amp-lsj-200e_coco.py' + +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r18_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r18_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..aa30a3d07f5644dfc6f79f0eafc374518149e777 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r18_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,7 @@ +_base_ = './cascade-rcnn_r50_fpn_8xb8-amp-lsj-200e_coco.py' + +model = dict( + backbone=dict( + depth=18, + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18')), + neck=dict(in_channels=[64, 128, 256, 512])) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50-caffe_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50-caffe_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..ad90e259b2d8410309bfd877b74755524b94f788 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50-caffe_fpn_1x_coco.py @@ -0,0 +1,16 @@ +_base_ = './cascade-rcnn_r50_fpn_1x_coco.py' + +model = dict( + # use caffe img_norm + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False, + pad_size_divisor=32), + backbone=dict( + norm_cfg=dict(requires_grad=False), + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..1a07c8b2302b9c2337d4da2d32c388142ca1f748 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = [ + '../_base_/models/cascade-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_20e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_20e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..30f3ff106018ba51173f018c196cf62a88fdb172 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_20e_coco.py @@ -0,0 +1,5 @@ +_base_ = [ + '../_base_/models/cascade-rcnn_r50_fpn.py', + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_20e.py', '../_base_/default_runtime.py' +] diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..cd25f02608c3f51a59e35185a41080c6e8e3a1ea --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_r50_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,23 @@ +_base_ = [ + '../_base_/models/cascade-rcnn_r50_fpn.py', + '../common/lsj-200e_coco-detection.py' +] +image_size = (1024, 1024) +batch_augments = [dict(type='BatchFixedSizePad', size=image_size)] + +# disable allowed_border to avoid potential errors. +model = dict( + data_preprocessor=dict(batch_augments=batch_augments), + train_cfg=dict(rpn=dict(allowed_border=-1))) + +train_dataloader = dict(batch_size=8, num_workers=4) +# Enable automatic-mixed-precision training with AmpOptimWrapper. +optim_wrapper = dict( + type='AmpOptimWrapper', + optimizer=dict( + type='SGD', lr=0.02 * 4, momentum=0.9, weight_decay=0.00004)) + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (8 samples per GPU) +auto_scale_lr = dict(base_batch_size=64) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..50e0b9544592d61b3c14ec7f64f3e6eaa2e96a57 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_1x_coco.py @@ -0,0 +1,14 @@ +_base_ = './cascade-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=32, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_20e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_20e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..6120189205d883d98b2d323a160ec54ea26aab13 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_20e_coco.py @@ -0,0 +1,14 @@ +_base_ = './cascade-rcnn_r50_fpn_20e_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=32, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-64x4d_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-64x4d_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..29475e39273dccad13058e9114728770e77f71ef --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-64x4d_fpn_1x_coco.py @@ -0,0 +1,15 @@ +_base_ = './cascade-rcnn_r50_fpn_1x_coco.py' +model = dict( + type='CascadeRCNN', + backbone=dict( + type='ResNeXt', + depth=101, + groups=64, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101_64x4d_fpn_20e_coco.py b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101_64x4d_fpn_20e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..e2aa57eaaf43788fc3628f1463e94405279c7416 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101_64x4d_fpn_20e_coco.py @@ -0,0 +1,15 @@ +_base_ = './cascade-rcnn_r50_fpn_20e_coco.py' +model = dict( + type='CascadeRCNN', + backbone=dict( + type='ResNeXt', + depth=101, + groups=64, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d'))) diff --git a/grounding-dino/mmdetection/configs/cascade_rcnn/metafile.yml b/grounding-dino/mmdetection/configs/cascade_rcnn/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..7e0385daeed3f3310dc7f9a8b64c99b5cb8324b4 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rcnn/metafile.yml @@ -0,0 +1,545 @@ +Collections: + - Name: Cascade R-CNN + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - Cascade R-CNN + - FPN + - RPN + - ResNet + - RoIAlign + Paper: + URL: http://dx.doi.org/10.1109/tpami.2019.2956516 + Title: 'Cascade R-CNN: Delving into High Quality Object Detection' + README: configs/cascade_rcnn/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.0.0/mmdet/models/detectors/cascade_rcnn.py#L6 + Version: v2.0.0 + - Name: Cascade Mask R-CNN + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - Cascade R-CNN + - FPN + - RPN + - ResNet + - RoIAlign + Paper: + URL: http://dx.doi.org/10.1109/tpami.2019.2956516 + Title: 'Cascade R-CNN: Delving into High Quality Object Detection' + README: configs/cascade_rcnn/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.0.0/mmdet/models/detectors/cascade_rcnn.py#L6 + Version: v2.0.0 + +Models: + - Name: cascade-rcnn_r50-caffe_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_r50-caffe_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.2 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 40.4 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_caffe_fpn_1x_coco/cascade_rcnn_r50_caffe_fpn_1x_coco_bbox_mAP-0.404_20200504_174853-b857be87.pth + + - Name: cascade-rcnn_r50_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.4 + inference time (ms/im): + - value: 62.11 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 40.3 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco/cascade_rcnn_r50_fpn_1x_coco_20200316-3dc56deb.pth + + - Name: cascade-rcnn_r50_fpn_20e_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_r50_fpn_20e_coco.py + Metadata: + Training Memory (GB): 4.4 + inference time (ms/im): + - value: 62.11 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 20 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.0 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r50_fpn_20e_coco/cascade_rcnn_r50_fpn_20e_coco_bbox_mAP-0.41_20200504_175131-e9872a90.pth + + - Name: cascade-rcnn_r101-caffe_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_r101-caffe_fpn_1x_coco.py + Metadata: + Training Memory (GB): 6.2 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 42.3 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_caffe_fpn_1x_coco/cascade_rcnn_r101_caffe_fpn_1x_coco_bbox_mAP-0.423_20200504_175649-cab8dbd5.pth + + - Name: cascade-rcnn_r101_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_r101_fpn_1x_coco.py + Metadata: + Training Memory (GB): 6.4 + inference time (ms/im): + - value: 74.07 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 42.0 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_fpn_1x_coco/cascade_rcnn_r101_fpn_1x_coco_20200317-0b6a2fbf.pth + + - Name: cascade-rcnn_r101_fpn_20e_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_r101_fpn_20e_coco.py + Metadata: + Training Memory (GB): 6.4 + inference time (ms/im): + - value: 74.07 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 20 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 42.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_r101_fpn_20e_coco/cascade_rcnn_r101_fpn_20e_coco_bbox_mAP-0.425_20200504_231812-5057dcc5.pth + + - Name: cascade-rcnn_x101-32x4d_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_1x_coco.py + Metadata: + Training Memory (GB): 7.6 + inference time (ms/im): + - value: 91.74 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 43.7 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_32x4d_fpn_1x_coco/cascade_rcnn_x101_32x4d_fpn_1x_coco_20200316-95c2deb6.pth + + - Name: cascade-rcnn_x101-32x4d_fpn_20e_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_20e_coco.py + Metadata: + Training Memory (GB): 7.6 + Epochs: 20 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 43.7 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_32x4d_fpn_20e_coco/cascade_rcnn_x101_32x4d_fpn_20e_coco_20200906_134608-9ae0a720.pth + + - Name: cascade-rcnn_x101-64x4d_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_x101-64x4d_fpn_1x_coco.py + Metadata: + Training Memory (GB): 10.7 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 44.7 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_64x4d_fpn_1x_coco/cascade_rcnn_x101_64x4d_fpn_1x_coco_20200515_075702-43ce6a30.pth + + - Name: cascade-rcnn_x101_64x4d_fpn_20e_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-rcnn_x101_64x4d_fpn_20e_coco.py + Metadata: + Training Memory (GB): 10.7 + Epochs: 20 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 44.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_64x4d_fpn_20e_coco/cascade_rcnn_x101_64x4d_fpn_20e_coco_20200509_224357-051557b1.pth + + - Name: cascade-mask-rcnn_r50-caffe_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r50-caffe_fpn_1x_coco.py + Metadata: + Training Memory (GB): 5.9 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.2 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 36.0 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_caffe_fpn_1x_coco/cascade_mask_rcnn_r50_caffe_fpn_1x_coco_bbox_mAP-0.412__segm_mAP-0.36_20200504_174659-5004b251.pth + + - Name: cascade-mask-rcnn_r50_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py + Metadata: + Training Memory (GB): 6.0 + inference time (ms/im): + - value: 89.29 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.2 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 35.9 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_1x_coco/cascade_mask_rcnn_r50_fpn_1x_coco_20200203-9d4dcb24.pth + + - Name: cascade-mask-rcnn_r50_fpn_20e_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_20e_coco.py + Metadata: + Training Memory (GB): 6.0 + inference time (ms/im): + - value: 89.29 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 20 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.9 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 36.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_20e_coco/cascade_mask_rcnn_r50_fpn_20e_coco_bbox_mAP-0.419__segm_mAP-0.365_20200504_174711-4af8e66e.pth + + - Name: cascade-mask-rcnn_r101-caffe_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r101-caffe_fpn_1x_coco.py + Metadata: + Training Memory (GB): 7.8 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 43.2 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 37.6 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_caffe_fpn_1x_coco/cascade_mask_rcnn_r101_caffe_fpn_1x_coco_bbox_mAP-0.432__segm_mAP-0.376_20200504_174813-5c1e9599.pth + + - Name: cascade-mask-rcnn_r101_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_1x_coco.py + Metadata: + Training Memory (GB): 7.9 + inference time (ms/im): + - value: 102.04 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 42.9 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 37.3 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_1x_coco/cascade_mask_rcnn_r101_fpn_1x_coco_20200203-befdf6ee.pth + + - Name: cascade-mask-rcnn_r101_fpn_20e_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_20e_coco.py + Metadata: + Training Memory (GB): 7.9 + inference time (ms/im): + - value: 102.04 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 20 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 43.4 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 37.8 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_20e_coco/cascade_mask_rcnn_r101_fpn_20e_coco_bbox_mAP-0.434__segm_mAP-0.378_20200504_174836-005947da.pth + + - Name: cascade-mask-rcnn_x101-32x4d_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_1x_coco.py + Metadata: + Training Memory (GB): 9.2 + inference time (ms/im): + - value: 116.28 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 44.3 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 38.3 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_1x_coco/cascade_mask_rcnn_x101_32x4d_fpn_1x_coco_20200201-0f411b1f.pth + + - Name: cascade-mask-rcnn_x101-32x4d_fpn_20e_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_20e_coco.py + Metadata: + Training Memory (GB): 9.2 + inference time (ms/im): + - value: 116.28 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 20 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 45.0 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 39.0 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_20e_coco/cascade_mask_rcnn_x101_32x4d_fpn_20e_coco_20200528_083917-ed1f4751.pth + + - Name: cascade-mask-rcnn_x101-64x4d_fpn_1x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_1x_coco.py + Metadata: + Training Memory (GB): 12.2 + inference time (ms/im): + - value: 149.25 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 45.3 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 39.2 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco/cascade_mask_rcnn_x101_64x4d_fpn_1x_coco_20200203-9a2db89d.pth + + - Name: cascade-mask-rcnn_x101-64x4d_fpn_20e_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_20e_coco.py + Metadata: + Training Memory (GB): 12.2 + Epochs: 20 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 45.6 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 39.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_20e_coco/cascade_mask_rcnn_x101_64x4d_fpn_20e_coco_20200512_161033-bdb5126a.pth + + - Name: cascade-mask-rcnn_r50-caffe_fpn_ms-3x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r50-caffe_fpn_ms-3x_coco.py + Metadata: + Training Memory (GB): 5.7 + Epochs: 36 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 44.0 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 38.1 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_caffe_fpn_mstrain_3x_coco/cascade_mask_rcnn_r50_caffe_fpn_mstrain_3x_coco_20210707_002651-6e29b3a6.pth + + - Name: cascade-mask-rcnn_r50_fpn_mstrain_3x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r50_fpn_ms-3x_coco.py + Metadata: + Training Memory (GB): 5.9 + Epochs: 36 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 44.3 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 38.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco_20210628_164719-5bdc3824.pth + + - Name: cascade-mask-rcnn_r101-caffe_fpn_ms-3x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r101-caffe_fpn_ms-3x_coco.py + Metadata: + Training Memory (GB): 7.7 + Epochs: 36 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 45.4 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 39.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_caffe_fpn_mstrain_3x_coco/cascade_mask_rcnn_r101_caffe_fpn_mstrain_3x_coco_20210707_002620-a5bd2389.pth + + - Name: cascade-mask-rcnn_r101_fpn_ms-3x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_r101_fpn_ms-3x_coco.py + Metadata: + Training Memory (GB): 7.8 + Epochs: 36 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 45.5 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 39.6 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_r101_fpn_mstrain_3x_coco/cascade_mask_rcnn_r101_fpn_mstrain_3x_coco_20210628_165236-51a2d363.pth + + - Name: cascade-mask-rcnn_x101-32x4d_fpn_ms-3x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_ms-3x_coco.py + Metadata: + Training Memory (GB): 9.0 + Epochs: 36 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 46.3 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 40.1 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco_20210706_225234-40773067.pth + + - Name: cascade-mask-rcnn_x101-32x8d_fpn_ms-3x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_x101-32x8d_fpn_ms-3x_coco.py + Metadata: + Training Memory (GB): 12.1 + Epochs: 36 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 46.1 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 39.9 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_32x8d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_32x8d_fpn_mstrain_3x_coco_20210719_180640-9ff7e76f.pth + + - Name: cascade-mask-rcnn_x101-64x4d_fpn_ms-3x_coco + In Collection: Cascade R-CNN + Config: configs/cascade_rcnn/cascade-mask-rcnn_x101-64x4d_fpn_ms-3x_coco.py + Metadata: + Training Memory (GB): 12.0 + Epochs: 36 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 46.6 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 40.3 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_mask_rcnn_x101_64x4d_fpn_mstrain_3x_coco/cascade_mask_rcnn_x101_64x4d_fpn_mstrain_3x_coco_20210719_210311-d3e64ba0.pth diff --git a/grounding-dino/mmdetection/configs/cascade_rpn/README.md b/grounding-dino/mmdetection/configs/cascade_rpn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..868a25eda26967576db85dc0686dda53a1d9c9b1 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rpn/README.md @@ -0,0 +1,41 @@ +# Cascade RPN + +> [Cascade RPN: Delving into High-Quality Region Proposal Network with Adaptive Convolution](https://arxiv.org/abs/1909.06720) + + + +## Abstract + +This paper considers an architecture referred to as Cascade Region Proposal Network (Cascade RPN) for improving the region-proposal quality and detection performance by systematically addressing the limitation of the conventional RPN that heuristically defines the anchors and aligns the features to the anchors. First, instead of using multiple anchors with predefined scales and aspect ratios, Cascade RPN relies on a single anchor per location and performs multi-stage refinement. Each stage is progressively more stringent in defining positive samples by starting out with an anchor-free metric followed by anchor-based metrics in the ensuing stages. Second, to attain alignment between the features and the anchors throughout the stages, adaptive convolution is proposed that takes the anchors in addition to the image features as its input and learns the sampled features guided by the anchors. A simple implementation of a two-stage Cascade RPN achieves AR 13.4 points higher than that of the conventional RPN, surpassing any existing region proposal methods. When adopting to Fast R-CNN and Faster R-CNN, Cascade RPN can improve the detection mAP by 3.1 and 3.5 points, respectively. + +
+ +
+ +## Results and Models + +### Region proposal performance + +| Method | Backbone | Style | Mem (GB) | Train time (s/iter) | Inf time (fps) | AR 1000 | Config | Download | +| :----: | :------: | :---: | :------: | :-----------------: | :------------: | :-----: | :----------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------: | +| CRPN | R-50-FPN | caffe | - | - | - | 72.0 | [config](./cascade-rpn_r50-caffe_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rpn/crpn_r50_caffe_fpn_1x_coco/cascade_rpn_r50_caffe_fpn_1x_coco-7aa93cef.pth) | + +### Detection performance + +| Method | Proposal | Backbone | Style | Schedule | Mem (GB) | Train time (s/iter) | Inf time (fps) | box AP | Config | Download | +| :----------: | :---------: | :------: | :---: | :------: | :------: | :-----------------: | :------------: | :----: | :----------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| Fast R-CNN | Cascade RPN | R-50-FPN | caffe | 1x | - | - | - | 39.9 | [config](./cascade-rpn_fast-rcnn_r50-caffe_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rpn/crpn_fast_rcnn_r50_caffe_fpn_1x_coco/crpn_fast_rcnn_r50_caffe_fpn_1x_coco-cb486e66.pth) | +| Faster R-CNN | Cascade RPN | R-50-FPN | caffe | 1x | - | - | - | 40.4 | [config](./cascade-rpn_faster-rcnn_r50-caffe_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cascade_rpn/crpn_faster_rcnn_r50_caffe_fpn_1x_coco/crpn_faster_rcnn_r50_caffe_fpn_1x_coco-c8283cca.pth) | + +## Citation + +We provide the code for reproducing experiment results of [Cascade RPN](https://arxiv.org/abs/1909.06720). + +```latex +@inproceedings{vu2019cascade, + title={Cascade RPN: Delving into High-Quality Region Proposal Network with Adaptive Convolution}, + author={Vu, Thang and Jang, Hyunjun and Pham, Trung X and Yoo, Chang D}, + booktitle={Conference on Neural Information Processing Systems (NeurIPS)}, + year={2019} +} +``` diff --git a/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_fast-rcnn_r50-caffe_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_fast-rcnn_r50-caffe_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..ba23ce90652d2ab2e9362be9a6231742d1815a70 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_fast-rcnn_r50-caffe_fpn_1x_coco.py @@ -0,0 +1,27 @@ +_base_ = '../fast_rcnn/fast-rcnn_r50-caffe_fpn_1x_coco.py' +model = dict( + roi_head=dict( + bbox_head=dict( + bbox_coder=dict(target_stds=[0.04, 0.04, 0.08, 0.08]), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.5), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))), + # model training and testing settings + train_cfg=dict( + rcnn=dict( + assigner=dict( + pos_iou_thr=0.65, neg_iou_thr=0.65, min_pos_iou=0.65), + sampler=dict(num=256))), + test_cfg=dict(rcnn=dict(score_thr=1e-3))) + +# MMEngine support the following two ways, users can choose +# according to convenience +# train_dataloader = dict(dataset=dict(proposal_file='proposals/crpn_r50_caffe_fpn_1x_train2017.pkl')) # noqa +_base_.train_dataloader.dataset.proposal_file = 'proposals/crpn_r50_caffe_fpn_1x_train2017.pkl' # noqa + +# val_dataloader = dict(dataset=dict(proposal_file='proposals/crpn_r50_caffe_fpn_1x_val2017.pkl')) # noqa +# test_dataloader = val_dataloader +_base_.val_dataloader.dataset.proposal_file = 'proposals/crpn_r50_caffe_fpn_1x_val2017.pkl' # noqa +test_dataloader = _base_.val_dataloader + +optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2)) diff --git a/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_faster-rcnn_r50-caffe_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_faster-rcnn_r50-caffe_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..2f7eced00144fb8fff1f234210a2b3f3fe475c8f --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_faster-rcnn_r50-caffe_fpn_1x_coco.py @@ -0,0 +1,89 @@ +_base_ = '../faster_rcnn/faster-rcnn_r50-caffe_fpn_1x_coco.py' +rpn_weight = 0.7 +model = dict( + rpn_head=dict( + _delete_=True, + type='CascadeRPNHead', + num_stages=2, + stages=[ + dict( + type='StageCascadeRPNHead', + in_channels=256, + feat_channels=256, + anchor_generator=dict( + type='AnchorGenerator', + scales=[8], + ratios=[1.0], + strides=[4, 8, 16, 32, 64]), + adapt_cfg=dict(type='dilation', dilation=3), + bridged_feature=True, + with_cls=False, + reg_decoded_bbox=True, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=(.0, .0, .0, .0), + target_stds=(0.1, 0.1, 0.5, 0.5)), + loss_bbox=dict( + type='IoULoss', linear=True, + loss_weight=10.0 * rpn_weight)), + dict( + type='StageCascadeRPNHead', + in_channels=256, + feat_channels=256, + adapt_cfg=dict(type='offset'), + bridged_feature=False, + with_cls=True, + reg_decoded_bbox=True, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=(.0, .0, .0, .0), + target_stds=(0.05, 0.05, 0.1, 0.1)), + loss_cls=dict( + type='CrossEntropyLoss', + use_sigmoid=True, + loss_weight=1.0 * rpn_weight), + loss_bbox=dict( + type='IoULoss', linear=True, + loss_weight=10.0 * rpn_weight)) + ]), + roi_head=dict( + bbox_head=dict( + bbox_coder=dict(target_stds=[0.04, 0.04, 0.08, 0.08]), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.5), + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))), + # model training and testing settings + train_cfg=dict( + rpn=[ + dict( + assigner=dict( + type='RegionAssigner', center_ratio=0.2, ignore_ratio=0.5), + allowed_border=-1, + pos_weight=-1, + debug=False), + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.7, + min_pos_iou=0.3, + ignore_iof_thr=-1), + sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + allowed_border=-1, + pos_weight=-1, + debug=False) + ], + rpn_proposal=dict(max_per_img=300, nms=dict(iou_threshold=0.8)), + rcnn=dict( + assigner=dict( + pos_iou_thr=0.65, neg_iou_thr=0.65, min_pos_iou=0.65), + sampler=dict(type='RandomSampler', num=256))), + test_cfg=dict( + rpn=dict(max_per_img=300, nms=dict(iou_threshold=0.8)), + rcnn=dict(score_thr=1e-3))) +optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2)) diff --git a/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_r50-caffe_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_r50-caffe_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..6eba24d11368ee0cdaae4fa316020ea3750be7f0 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rpn/cascade-rpn_r50-caffe_fpn_1x_coco.py @@ -0,0 +1,76 @@ +_base_ = '../rpn/rpn_r50-caffe_fpn_1x_coco.py' +model = dict( + rpn_head=dict( + _delete_=True, + type='CascadeRPNHead', + num_stages=2, + stages=[ + dict( + type='StageCascadeRPNHead', + in_channels=256, + feat_channels=256, + anchor_generator=dict( + type='AnchorGenerator', + scales=[8], + ratios=[1.0], + strides=[4, 8, 16, 32, 64]), + adapt_cfg=dict(type='dilation', dilation=3), + bridged_feature=True, + sampling=False, + with_cls=False, + reg_decoded_bbox=True, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=(.0, .0, .0, .0), + target_stds=(0.1, 0.1, 0.5, 0.5)), + loss_bbox=dict(type='IoULoss', linear=True, loss_weight=10.0)), + dict( + type='StageCascadeRPNHead', + in_channels=256, + feat_channels=256, + adapt_cfg=dict(type='offset'), + bridged_feature=False, + sampling=True, + with_cls=True, + reg_decoded_bbox=True, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=(.0, .0, .0, .0), + target_stds=(0.05, 0.05, 0.1, 0.1)), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=True, + loss_weight=1.0), + loss_bbox=dict(type='IoULoss', linear=True, loss_weight=10.0)) + ]), + train_cfg=dict(rpn=[ + dict( + assigner=dict( + type='RegionAssigner', center_ratio=0.2, ignore_ratio=0.5), + allowed_border=-1, + pos_weight=-1, + debug=False), + dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=0.7, + min_pos_iou=0.3, + ignore_iof_thr=-1, + iou_calculator=dict(type='BboxOverlaps2D')), + sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + allowed_border=-1, + pos_weight=-1, + debug=False) + ]), + test_cfg=dict( + rpn=dict( + nms_pre=2000, + max_per_img=2000, + nms=dict(type='nms', iou_threshold=0.8), + min_bbox_size=0))) +optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2)) diff --git a/grounding-dino/mmdetection/configs/cascade_rpn/metafile.yml b/grounding-dino/mmdetection/configs/cascade_rpn/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..62a88c5d2185ffd3aa7884f7a8c7d68cc3d60c8f --- /dev/null +++ b/grounding-dino/mmdetection/configs/cascade_rpn/metafile.yml @@ -0,0 +1,44 @@ +Collections: + - Name: Cascade RPN + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - Cascade RPN + - FPN + - ResNet + Paper: + URL: https://arxiv.org/abs/1909.06720 + Title: 'Cascade RPN: Delving into High-Quality Region Proposal Network with Adaptive Convolution' + README: configs/cascade_rpn/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.8.0/mmdet/models/dense_heads/cascade_rpn_head.py#L538 + Version: v2.8.0 + +Models: + - Name: cascade-rpn_fast-rcnn_r50-caffe_fpn_1x_coco + In Collection: Cascade RPN + Config: configs/cascade_rpn/cascade-rpn_fast-rcnn_r50-caffe_fpn_1x_coco.py + Metadata: + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 39.9 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rpn/crpn_fast_rcnn_r50_caffe_fpn_1x_coco/crpn_fast_rcnn_r50_caffe_fpn_1x_coco-cb486e66.pth + + - Name: cascade-rpn_faster-rcnn_r50-caffe_fpn_1x_coco + In Collection: Cascade RPN + Config: configs/cascade_rpn/cascade-rpn_faster-rcnn_r50-caffe_fpn_1x_coco.py + Metadata: + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 40.4 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cascade_rpn/crpn_faster_rcnn_r50_caffe_fpn_1x_coco/crpn_faster_rcnn_r50_caffe_fpn_1x_coco-c8283cca.pth diff --git a/grounding-dino/mmdetection/configs/centernet/README.md b/grounding-dino/mmdetection/configs/centernet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..81e229c62f7816f20459a53132bfca676c01ac78 --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/README.md @@ -0,0 +1,58 @@ +# CenterNet + +> [Objects as Points](https://arxiv.org/abs/1904.07850) + + + +## Abstract + +Detection identifies objects as axis-aligned boxes in an image. Most successful object detectors enumerate a nearly exhaustive list of potential object locations and classify each. This is wasteful, inefficient, and requires additional post-processing. In this paper, we take a different approach. We model an object as a single point --- the center point of its bounding box. Our detector uses keypoint estimation to find center points and regresses to all other object properties, such as size, 3D location, orientation, and even pose. Our center point based approach, CenterNet, is end-to-end differentiable, simpler, faster, and more accurate than corresponding bounding box based detectors. CenterNet achieves the best speed-accuracy trade-off on the MS COCO dataset, with 28.1% AP at 142 FPS, 37.4% AP at 52 FPS, and 45.1% AP with multi-scale testing at 1.4 FPS. We use the same approach to estimate 3D bounding box in the KITTI benchmark and human pose on the COCO keypoint dataset. Our method performs competitively with sophisticated multi-stage methods and runs in real-time. + +
+ +
+ +## Results and Models + +| Backbone | DCN | Mem (GB) | Box AP | Flip box AP | Config | Download | +| :-------: | :-: | :------: | :----: | :---------: | :--------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| ResNet-18 | N | 3.45 | 25.9 | 27.3 | [config](./centernet_r18_8xb16-crop512-140e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/centernet/centernet_resnet18_140e_coco/centernet_resnet18_140e_coco_20210705_093630-bb5b3bf7.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/centernet/centernet_resnet18_140e_coco/centernet_resnet18_140e_coco_20210705_093630.log.json) | +| ResNet-18 | Y | 3.47 | 29.5 | 30.9 | [config](./centernet_r18-dcnv2_8xb16-crop512-140e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/centernet/centernet_resnet18_dcnv2_140e_coco/centernet_resnet18_dcnv2_140e_coco_20210702_155131-c8cd631f.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/centernet/centernet_resnet18_dcnv2_140e_coco/centernet_resnet18_dcnv2_140e_coco_20210702_155131.log.json) | + +Note: + +- Flip box AP setting is single-scale and `flip=True`. +- Due to complex data enhancement, we find that the performance is unstable and may fluctuate by about 0.4 mAP. mAP 29.4 ~ 29.8 is acceptable in ResNet-18-DCNv2. +- Compared to the source code, we refer to [CenterNet-Better](https://github.com/FateScript/CenterNet-better), and make the following changes + - fix wrong image mean and variance in image normalization to be compatible with the pre-trained backbone. + - Use SGD rather than ADAM optimizer and add warmup and grad clip. + - Use DistributedDataParallel as other models in MMDetection rather than using DataParallel. + +## CenterNet Update + +| Backbone | Style | Lr schd | MS train | Mem (GB) | Box AP | Config | Download | +| :-------: | :---: | :-----: | :------: | :------: | :----: | :------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| ResNet-50 | caffe | 1x | True | 3.3 | 40.2 | [config](./centernet-update_r50-caffe_fpn_ms-1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v3.0/centernet/centernet-update_r50-caffe_fpn_ms-1x_coco/centernet-update_r50-caffe_fpn_ms-1x_coco_20230512_203845-8306baf2.pth) \| [log](https://download.openmmlab.com/mmdetection/v3.0/centernet/centernet-update_r50-caffe_fpn_ms-1x_coco/centernet-update_r50-caffe_fpn_ms-1x_coco_20230512_203845.log.json) | + +CenterNet Update from the paper of [Probabilistic two-stage detection](https://arxiv.org/abs/2103.07461). The author has updated CenterNet to greatly improve performance and convergence speed. +The [Details](https://github.com/xingyizhou/CenterNet2/blob/master/docs/MODEL_ZOO.md) are as follows: + +- Using top-left-right-bottom box encoding and GIoU Loss +- Adding regression loss to the center 3x3 region +- Adding more positive pixels for the heatmap loss whose regression loss is small and is within the center3x3 region +- Using RetinaNet-style optimizer (SGD), learning rate rule (0.01 for each batch size 16), and schedule (12 epochs) +- Added FPN neck layers, and assigns objects to FPN levels based on a fixed size range. +- Using standard NMS instead of max pooling + +Note: We found that the performance of the r50 model fluctuates greatly and sometimes it does not converge. If the model does not converge, you can try running it again or reduce the learning rate. + +## Citation + +```latex +@article{zhou2019objects, + title={Objects as Points}, + author={Zhou, Xingyi and Wang, Dequan and Kr{\"a}henb{\"u}hl, Philipp}, + booktitle={arXiv preprint arXiv:1904.07850}, + year={2019} +} +``` diff --git a/grounding-dino/mmdetection/configs/centernet/centernet-update_r101_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/centernet/centernet-update_r101_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..4fc65e0f8aeb1f02a0bea675146ced7a56800251 --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/centernet-update_r101_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,7 @@ +_base_ = './centernet-update_r50_fpn_8xb8-amp-lsj-200e_coco.py' + +model = dict( + backbone=dict( + depth=101, + init_cfg=dict(type='Pretrained', + checkpoint='torchvision://resnet101'))) diff --git a/grounding-dino/mmdetection/configs/centernet/centernet-update_r18_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/centernet/centernet-update_r18_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3ae32ecd54cd08664e883a0888ef43040528d1 --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/centernet-update_r18_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,7 @@ +_base_ = './centernet-update_r50_fpn_8xb8-amp-lsj-200e_coco.py' + +model = dict( + backbone=dict( + depth=18, + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18')), + neck=dict(in_channels=[64, 128, 256, 512])) diff --git a/grounding-dino/mmdetection/configs/centernet/centernet-update_r50-caffe_fpn_ms-1x_coco.py b/grounding-dino/mmdetection/configs/centernet/centernet-update_r50-caffe_fpn_ms-1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..1f6e2b3919d6d2197c0ae9e1d721dc4eab00cf9c --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/centernet-update_r50-caffe_fpn_ms-1x_coco.py @@ -0,0 +1,105 @@ +_base_ = [ + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +model = dict( + type='CenterNet', + # use caffe img_norm + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[103.530, 116.280, 123.675], + std=[1.0, 1.0, 1.0], + bgr_to_rgb=False, + pad_size_divisor=32), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=False), + norm_eval=True, + style='caffe', + init_cfg=dict( + type='Pretrained', + checkpoint='open-mmlab://detectron2/resnet50_caffe')), + neck=dict( + type='FPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + start_level=1, + add_extra_convs='on_output', + num_outs=5, + # There is a chance to get 40.3 after switching init_cfg, + # otherwise it is about 39.9~40.1 + init_cfg=dict(type='Caffe2Xavier', layer='Conv2d'), + relu_before_extra_convs=True), + bbox_head=dict( + type='CenterNetUpdateHead', + num_classes=80, + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + hm_min_radius=4, + hm_min_overlap=0.8, + more_pos_thresh=0.2, + more_pos_topk=9, + soft_weight_on_reg=False, + loss_cls=dict( + type='GaussianFocalLoss', + pos_weight=0.25, + neg_weight=0.75, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + ), + train_cfg=None, + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + +# single-scale training is about 39.3 +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomChoiceResize', + scales=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] + +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', + start_factor=0.00025, + by_epoch=False, + begin=0, + end=4000), + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[8, 11], + gamma=0.1) +] + +optim_wrapper = dict( + optimizer=dict(lr=0.01), + # Experiments show that there is no need to turn on clip_grad. + paramwise_cfg=dict(norm_decay_mult=0.)) + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (2 samples per GPU) +auto_scale_lr = dict(base_batch_size=16) diff --git a/grounding-dino/mmdetection/configs/centernet/centernet-update_r50_fpn_8xb8-amp-lsj-200e_coco.py b/grounding-dino/mmdetection/configs/centernet/centernet-update_r50_fpn_8xb8-amp-lsj-200e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..34e0c680d39486467464f0ea7d6e1e08bf0c5240 --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/centernet-update_r50_fpn_8xb8-amp-lsj-200e_coco.py @@ -0,0 +1,83 @@ +_base_ = '../common/lsj-200e_coco-detection.py' + +image_size = (1024, 1024) +batch_augments = [dict(type='BatchFixedSizePad', size=image_size)] + +model = dict( + type='CenterNet', + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_size_divisor=32, + batch_augments=batch_augments), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=True, + style='pytorch', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict( + type='FPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + start_level=1, + add_extra_convs='on_output', + num_outs=5, + init_cfg=dict(type='Caffe2Xavier', layer='Conv2d'), + relu_before_extra_convs=True), + bbox_head=dict( + type='CenterNetUpdateHead', + num_classes=80, + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + loss_cls=dict( + type='GaussianFocalLoss', + pos_weight=0.25, + neg_weight=0.75, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=2.0), + ), + train_cfg=None, + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100)) + +train_dataloader = dict(batch_size=8, num_workers=4) +# Enable automatic-mixed-precision training with AmpOptimWrapper. +optim_wrapper = dict( + type='AmpOptimWrapper', + optimizer=dict( + type='SGD', lr=0.01 * 4, momentum=0.9, weight_decay=0.00004), + paramwise_cfg=dict(norm_decay_mult=0.)) + +param_scheduler = [ + dict( + type='LinearLR', + start_factor=0.00025, + by_epoch=False, + begin=0, + end=4000), + dict( + type='MultiStepLR', + begin=0, + end=25, + by_epoch=True, + milestones=[22, 24], + gamma=0.1) +] + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (8 samples per GPU) +auto_scale_lr = dict(base_batch_size=64) diff --git a/grounding-dino/mmdetection/configs/centernet/centernet_r18-dcnv2_8xb16-crop512-140e_coco.py b/grounding-dino/mmdetection/configs/centernet/centernet_r18-dcnv2_8xb16-crop512-140e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..732a55d59ad7dee175d8b72f798f0be044f23326 --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/centernet_r18-dcnv2_8xb16-crop512-140e_coco.py @@ -0,0 +1,136 @@ +_base_ = [ + '../_base_/datasets/coco_detection.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py', + './centernet_tta.py' +] + +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# model settings +model = dict( + type='CenterNet', + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True), + backbone=dict( + type='ResNet', + depth=18, + norm_eval=False, + norm_cfg=dict(type='BN'), + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18')), + neck=dict( + type='CTResNetNeck', + in_channels=512, + num_deconv_filters=(256, 128, 64), + num_deconv_kernels=(4, 4, 4), + use_dcn=True), + bbox_head=dict( + type='CenterNetHead', + num_classes=80, + in_channels=64, + feat_channels=64, + loss_center_heatmap=dict(type='GaussianFocalLoss', loss_weight=1.0), + loss_wh=dict(type='L1Loss', loss_weight=0.1), + loss_offset=dict(type='L1Loss', loss_weight=1.0)), + train_cfg=None, + test_cfg=dict(topk=100, local_maximum_kernel=3, max_per_img=100)) + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PhotoMetricDistortion', + brightness_delta=32, + contrast_range=(0.5, 1.5), + saturation_range=(0.5, 1.5), + hue_delta=18), + dict( + type='RandomCenterCropPad', + # The cropped images are padded into squares during training, + # but may be less than crop_size. + crop_size=(512, 512), + ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3), + mean=[0, 0, 0], + std=[1, 1, 1], + to_rgb=True, + test_pad_mode=None), + # Make sure the output is always crop_size. + dict(type='Resize', scale=(512, 512), keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict( + type='LoadImageFromFile', + backend_args={{_base_.backend_args}}, + to_float32=True), + # don't need Resize + dict( + type='RandomCenterCropPad', + ratios=None, + border=None, + mean=[0, 0, 0], + std=[1, 1, 1], + to_rgb=True, + test_mode=True, + test_pad_mode=['logical_or', 31], + test_pad_add_pix=1), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'border')) +] + +# Use RepeatDataset to speed up training +train_dataloader = dict( + batch_size=16, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + dataset=dict( + _delete_=True, + type='RepeatDataset', + times=5, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args={{_base_.backend_args}}, + ))) + +val_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# optimizer +# Based on the default settings of modern detectors, the SGD effect is better +# than the Adam in the source code, so we use SGD default settings and +# if you use adam+lr5e-4, the map is 29.1. +optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2)) + +max_epochs = 28 +# learning policy +# Based on the default settings of modern detectors, we added warmup settings. +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[18, 24], # the real step is [18*5, 24*5] + gamma=0.1) +] +train_cfg = dict(max_epochs=max_epochs) # the real epoch is 28*5=140 + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (16 samples per GPU) +auto_scale_lr = dict(base_batch_size=128) diff --git a/grounding-dino/mmdetection/configs/centernet/centernet_r18_8xb16-crop512-140e_coco.py b/grounding-dino/mmdetection/configs/centernet/centernet_r18_8xb16-crop512-140e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..6094b64221bd91eaafc9868e01c718d4421b418a --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/centernet_r18_8xb16-crop512-140e_coco.py @@ -0,0 +1,3 @@ +_base_ = './centernet_r18-dcnv2_8xb16-crop512-140e_coco.py' + +model = dict(neck=dict(use_dcn=False)) diff --git a/grounding-dino/mmdetection/configs/centernet/centernet_tta.py b/grounding-dino/mmdetection/configs/centernet/centernet_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..edd7b03ecdeb272870919dcbd4842d6b8e32d8d4 --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/centernet_tta.py @@ -0,0 +1,39 @@ +# This is different from the TTA of official CenterNet. + +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict(nms=dict(type='nms', iou_threshold=0.5), max_per_img=100)) + +tta_pipeline = [ + dict(type='LoadImageFromFile', to_float32=True, backend_args=None), + dict( + type='TestTimeAug', + transforms=[ + [ + # ``RandomFlip`` must be placed before ``RandomCenterCropPad``, + # otherwise bounding box coordinates after flipping cannot be + # recovered correctly. + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], + [ + dict( + type='RandomCenterCropPad', + ratios=None, + border=None, + mean=[0, 0, 0], + std=[1, 1, 1], + to_rgb=True, + test_mode=True, + test_pad_mode=['logical_or', 31], + test_pad_add_pix=1), + ], + [dict(type='LoadAnnotations', with_bbox=True)], + [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'flip', 'flip_direction', 'border')) + ] + ]) +] diff --git a/grounding-dino/mmdetection/configs/centernet/metafile.yml b/grounding-dino/mmdetection/configs/centernet/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..496b8ea22df0ac1e757a40c2750893034e08a81c --- /dev/null +++ b/grounding-dino/mmdetection/configs/centernet/metafile.yml @@ -0,0 +1,60 @@ +Collections: + - Name: CenterNet + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x TITANXP GPUs + Architecture: + - ResNet + Paper: + URL: https://arxiv.org/abs/1904.07850 + Title: 'Objects as Points' + README: configs/centernet/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.13.0/mmdet/models/detectors/centernet.py#L10 + Version: v2.13.0 + +Models: + - Name: centernet_r18-dcnv2_8xb16-crop512-140e_coco + In Collection: CenterNet + Config: configs/centernet/centernet_r18-dcnv2_8xb16-crop512-140e_coco.py + Metadata: + Batch Size: 128 + Training Memory (GB): 3.47 + Epochs: 140 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 29.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/centernet/centernet_resnet18_dcnv2_140e_coco/centernet_resnet18_dcnv2_140e_coco_20210702_155131-c8cd631f.pth + + - Name: centernet_r18_8xb16-crop512-140e_coco + In Collection: CenterNet + Config: configs/centernet/centernet_r18_8xb16-crop512-140e_coco.py + Metadata: + Batch Size: 128 + Training Memory (GB): 3.45 + Epochs: 140 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 25.9 + Weights: https://download.openmmlab.com/mmdetection/v2.0/centernet/centernet_resnet18_140e_coco/centernet_resnet18_140e_coco_20210705_093630-bb5b3bf7.pth + + - Name: centernet-update_r50-caffe_fpn_ms-1x_coco + In Collection: CenterNet + Config: configs/centernet/centernet-update_r50-caffe_fpn_ms-1x_coco.py + Metadata: + Batch Size: 16 + Training Memory (GB): 3.3 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 40.2 + Weights: https://download.openmmlab.com/mmdetection/v3.0/centernet/centernet-update_r50-caffe_fpn_ms-1x_coco/centernet-update_r50-caffe_fpn_ms-1x_coco_20230512_203845-8306baf2.pth diff --git a/grounding-dino/mmdetection/configs/centripetalnet/README.md b/grounding-dino/mmdetection/configs/centripetalnet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..21edbd261af502d41fc6a24323bc28474a6d1c5a --- /dev/null +++ b/grounding-dino/mmdetection/configs/centripetalnet/README.md @@ -0,0 +1,36 @@ +# CentripetalNet + +> [CentripetalNet: Pursuing High-quality Keypoint Pairs for Object Detection](https://arxiv.org/abs/2003.09119) + + + +## Abstract + +Keypoint-based detectors have achieved pretty-well performance. However, incorrect keypoint matching is still widespread and greatly affects the performance of the detector. In this paper, we propose CentripetalNet which uses centripetal shift to pair corner keypoints from the same instance. CentripetalNet predicts the position and the centripetal shift of the corner points and matches corners whose shifted results are aligned. Combining position information, our approach matches corner points more accurately than the conventional embedding approaches do. Corner pooling extracts information inside the bounding boxes onto the border. To make this information more aware at the corners, we design a cross-star deformable convolution network to conduct feature adaption. Furthermore, we explore instance segmentation on anchor-free detectors by equipping our CentripetalNet with a mask prediction module. On MS-COCO test-dev, our CentripetalNet not only outperforms all existing anchor-free detectors with an AP of 48.0% but also achieves comparable performance to the state-of-the-art instance segmentation approaches with a 40.2% MaskAP. + +
+ +
+ +## Results and Models + +| Backbone | Batch Size | Step/Total Epochs | Mem (GB) | Inf time (fps) | box AP | Config | Download | +| :--------------: | :-----------------------------------------------------------------------: | :---------------: | :------: | :------------: | :----: | :-----------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| HourglassNet-104 | [16 x 6](./centripetalnet_hourglass104_16xb6-crop511-210e-mstest_coco.py) | 190/210 | 16.7 | 3.7 | 44.8 | [config](./centripetalnet_hourglass104_16xb6-crop511-210e-mstest_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/centripetalnet/centripetalnet_hourglass104_mstest_16x6_210e_coco/centripetalnet_hourglass104_mstest_16x6_210e_coco_20200915_204804-3ccc61e5.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/centripetalnet/centripetalnet_hourglass104_mstest_16x6_210e_coco/centripetalnet_hourglass104_mstest_16x6_210e_coco_20200915_204804.log.json) | + +Note: + +- TTA setting is single-scale and `flip=True`. If you want to reproduce the TTA performance, please add `--tta` in the test command. +- The model we released is the best checkpoint rather than the latest checkpoint (box AP 44.8 vs 44.6 in our experiment). + +## Citation + +```latex +@InProceedings{Dong_2020_CVPR, +author = {Dong, Zhiwei and Li, Guoxuan and Liao, Yue and Wang, Fei and Ren, Pengju and Qian, Chen}, +title = {CentripetalNet: Pursuing High-Quality Keypoint Pairs for Object Detection}, +booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, +month = {June}, +year = {2020} +} +``` diff --git a/grounding-dino/mmdetection/configs/centripetalnet/centripetalnet_hourglass104_16xb6-crop511-210e-mstest_coco.py b/grounding-dino/mmdetection/configs/centripetalnet/centripetalnet_hourglass104_16xb6-crop511-210e-mstest_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..b757ffd16dca2d2b51d27ad413fdba889252c87f --- /dev/null +++ b/grounding-dino/mmdetection/configs/centripetalnet/centripetalnet_hourglass104_16xb6-crop511-210e-mstest_coco.py @@ -0,0 +1,181 @@ +_base_ = [ + '../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py' +] + +data_preprocessor = dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True) + +# model settings +model = dict( + type='CornerNet', + data_preprocessor=data_preprocessor, + backbone=dict( + type='HourglassNet', + downsample_times=5, + num_stacks=2, + stage_channels=[256, 256, 384, 384, 384, 512], + stage_blocks=[2, 2, 2, 2, 2, 4], + norm_cfg=dict(type='BN', requires_grad=True)), + neck=None, + bbox_head=dict( + type='CentripetalHead', + num_classes=80, + in_channels=256, + num_feat_levels=2, + corner_emb_channels=0, + loss_heatmap=dict( + type='GaussianFocalLoss', alpha=2.0, gamma=4.0, loss_weight=1), + loss_offset=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1), + loss_guiding_shift=dict( + type='SmoothL1Loss', beta=1.0, loss_weight=0.05), + loss_centripetal_shift=dict( + type='SmoothL1Loss', beta=1.0, loss_weight=1)), + # training and testing settings + train_cfg=None, + test_cfg=dict( + corner_topk=100, + local_maximum_kernel=3, + distance_threshold=0.5, + score_thr=0.05, + max_per_img=100, + nms=dict(type='soft_nms', iou_threshold=0.5, method='gaussian'))) + +# data settings +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PhotoMetricDistortion', + brightness_delta=32, + contrast_range=(0.5, 1.5), + saturation_range=(0.5, 1.5), + hue_delta=18), + dict( + # The cropped images are padded into squares during training, + # but may be smaller than crop_size. + type='RandomCenterCropPad', + crop_size=(511, 511), + ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3), + test_mode=False, + test_pad_mode=None, + mean=data_preprocessor['mean'], + std=data_preprocessor['std'], + # Image data is not converted to rgb. + to_rgb=data_preprocessor['bgr_to_rgb']), + dict(type='Resize', scale=(511, 511), keep_ratio=False), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs'), +] + +test_pipeline = [ + dict( + type='LoadImageFromFile', + to_float32=True, + backend_args=_base_.backend_args), + # don't need Resize + dict( + type='RandomCenterCropPad', + crop_size=None, + ratios=None, + border=None, + test_mode=True, + test_pad_mode=['logical_or', 127], + mean=data_preprocessor['mean'], + std=data_preprocessor['std'], + # Image data is not converted to rgb. + to_rgb=data_preprocessor['bgr_to_rgb']), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'border')) +] + +train_dataloader = dict( + batch_size=6, + num_workers=3, + batch_sampler=None, + dataset=dict(pipeline=train_pipeline)) +val_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='Adam', lr=0.0005), + clip_grad=dict(max_norm=35, norm_type=2)) + +max_epochs = 210 + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', + start_factor=1.0 / 3, + by_epoch=False, + begin=0, + end=500), + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[190], + gamma=0.1) +] + +train_cfg = dict( + type='EpochBasedTrainLoop', max_epochs=max_epochs, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (16 GPUs) x (6 samples per GPU) +auto_scale_lr = dict(base_batch_size=96) + +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict( + nms=dict(type='soft_nms', iou_threshold=0.5, method='gaussian'), + max_per_img=100)) + +tta_pipeline = [ + dict( + type='LoadImageFromFile', + to_float32=True, + backend_args=_base_.backend_args), + dict( + type='TestTimeAug', + transforms=[ + [ + # ``RandomFlip`` must be placed before ``RandomCenterCropPad``, + # otherwise bounding box coordinates after flipping cannot be + # recovered correctly. + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], + [ + dict( + type='RandomCenterCropPad', + crop_size=None, + ratios=None, + border=None, + test_mode=True, + test_pad_mode=['logical_or', 127], + mean=data_preprocessor['mean'], + std=data_preprocessor['std'], + # Image data is not converted to rgb. + to_rgb=data_preprocessor['bgr_to_rgb']) + ], + [dict(type='LoadAnnotations', with_bbox=True)], + [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'flip', 'flip_direction', 'border')) + ] + ]) +] diff --git a/grounding-dino/mmdetection/configs/centripetalnet/metafile.yml b/grounding-dino/mmdetection/configs/centripetalnet/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..526572dfed0d158b55205c23031b5dfdbdfa9dc0 --- /dev/null +++ b/grounding-dino/mmdetection/configs/centripetalnet/metafile.yml @@ -0,0 +1,39 @@ +Collections: + - Name: CentripetalNet + Metadata: + Training Data: COCO + Training Techniques: + - Adam + Training Resources: 16x V100 GPUs + Architecture: + - Corner Pooling + - Stacked Hourglass Network + Paper: + URL: https://arxiv.org/abs/2003.09119 + Title: 'CentripetalNet: Pursuing High-quality Keypoint Pairs for Object Detection' + README: configs/centripetalnet/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.5.0/mmdet/models/detectors/cornernet.py#L9 + Version: v2.5.0 + +Models: + - Name: centripetalnet_hourglass104_16xb6-crop511-210e-mstest_coco + In Collection: CentripetalNet + Config: configs/centripetalnet/centripetalnet_hourglass104_16xb6-crop511-210e-mstest_coco.py + Metadata: + Batch Size: 96 + Training Memory (GB): 16.7 + inference time (ms/im): + - value: 270.27 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 210 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 44.8 + Weights: https://download.openmmlab.com/mmdetection/v2.0/centripetalnet/centripetalnet_hourglass104_mstest_16x6_210e_coco/centripetalnet_hourglass104_mstest_16x6_210e_coco_20200915_204804-3ccc61e5.pth diff --git a/grounding-dino/mmdetection/configs/cityscapes/README.md b/grounding-dino/mmdetection/configs/cityscapes/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9e37b64edb7eded69bafa37244aa5a411e475d2c --- /dev/null +++ b/grounding-dino/mmdetection/configs/cityscapes/README.md @@ -0,0 +1,46 @@ +# Cityscapes + +> [The Cityscapes Dataset for Semantic Urban Scene Understanding](https://arxiv.org/abs/1604.01685) + + + +## Abstract + +Visual understanding of complex urban street scenes is an enabling factor for a wide range of applications. Object detection has benefited enormously from large-scale datasets, especially in the context of deep learning. For semantic urban scene understanding, however, no current dataset adequately captures the complexity of real-world urban scenes. +To address this, we introduce Cityscapes, a benchmark suite and large-scale dataset to train and test approaches for pixel-level and instance-level semantic labeling. Cityscapes is comprised of a large, diverse set of stereo video sequences recorded in streets from 50 different cities. 5000 of these images have high quality pixel-level annotations; 20000 additional images have coarse annotations to enable methods that leverage large volumes of weakly-labeled data. Crucially, our effort exceeds previous attempts in terms of dataset size, annotation richness, scene variability, and complexity. Our accompanying empirical study provides an in-depth analysis of the dataset characteristics, as well as a performance evaluation of several state-of-the-art approaches based on our benchmark. + +
+ +
+ +## Common settings + +- All baselines were trained using 8 GPU with a batch size of 8 (1 images per GPU) using the [linear scaling rule](https://arxiv.org/abs/1706.02677) to scale the learning rate. +- All models were trained on `cityscapes_train`, and tested on `cityscapes_val`. +- 1x training schedule indicates 64 epochs which corresponds to slightly less than the 24k iterations reported in the original schedule from the [Mask R-CNN paper](https://arxiv.org/abs/1703.06870) +- COCO pre-trained weights are used to initialize. +- A conversion [script](../../tools/dataset_converters/cityscapes.py) is provided to convert Cityscapes into COCO format. Please refer to [install.md](../../docs/1_exist_data_model.md#prepare-datasets) for details. +- `CityscapesDataset` implemented three evaluation methods. `bbox` and `segm` are standard COCO bbox/mask AP. `cityscapes` is the cityscapes dataset official evaluation, which may be slightly higher than COCO. + +### Faster R-CNN + +| Backbone | Style | Lr schd | Scale | Mem (GB) | Inf time (fps) | box AP | Config | Download | +| :------: | :-----: | :-----: | :------: | :------: | :------------: | :----: | :----------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50-FPN | pytorch | 1x | 800-1024 | 5.2 | - | 40.3 | [config](./faster-rcnn_r50_fpn_1x_cityscapes.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cityscapes/faster_rcnn_r50_fpn_1x_cityscapes_20200502-829424c0.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cityscapes/faster_rcnn_r50_fpn_1x_cityscapes_20200502_114915.log.json) | + +### Mask R-CNN + +| Backbone | Style | Lr schd | Scale | Mem (GB) | Inf time (fps) | box AP | mask AP | Config | Download | +| :------: | :-----: | :-----: | :------: | :------: | :------------: | :----: | :-----: | :--------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50-FPN | pytorch | 1x | 800-1024 | 5.3 | - | 40.9 | 36.4 | [config](./mask-rcnn_r50_fpn_1x_cityscapes.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cityscapes/mask_rcnn_r50_fpn_1x_cityscapes/mask_rcnn_r50_fpn_1x_cityscapes_20201211_133733-d2858245.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cityscapes/mask_rcnn_r50_fpn_1x_cityscapes/mask_rcnn_r50_fpn_1x_cityscapes_20201211_133733.log.json) | + +## Citation + +```latex +@inproceedings{Cordts2016Cityscapes, + title={The Cityscapes Dataset for Semantic Urban Scene Understanding}, + author={Cordts, Marius and Omran, Mohamed and Ramos, Sebastian and Rehfeld, Timo and Enzweiler, Markus and Benenson, Rodrigo and Franke, Uwe and Roth, Stefan and Schiele, Bernt}, + booktitle={Proc. of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, + year={2016} +} +``` diff --git a/grounding-dino/mmdetection/configs/cityscapes/faster-rcnn_r50_fpn_1x_cityscapes.py b/grounding-dino/mmdetection/configs/cityscapes/faster-rcnn_r50_fpn_1x_cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd0de2aff1c1f3071e70e67dbf94b1c1cfe7e8b --- /dev/null +++ b/grounding-dino/mmdetection/configs/cityscapes/faster-rcnn_r50_fpn_1x_cityscapes.py @@ -0,0 +1,41 @@ +_base_ = [ + '../_base_/models/faster-rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_detection.py', + '../_base_/default_runtime.py', '../_base_/schedules/schedule_1x.py' +] +model = dict( + backbone=dict(init_cfg=None), + roi_head=dict( + bbox_head=dict( + num_classes=8, + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)))) + +# optimizer +# lr is set for a batch size of 8 +optim_wrapper = dict(optimizer=dict(lr=0.01)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=8, + by_epoch=True, + # [7] yields higher performance than [6] + milestones=[7], + gamma=0.1) +] + +# actual epoch = 8 * 8 = 64 +train_cfg = dict(max_epochs=8) + +# For better, more stable performance initialize from COCO +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' # noqa + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (1 samples per GPU) +# TODO: support auto scaling lr +# auto_scale_lr = dict(base_batch_size=8) diff --git a/grounding-dino/mmdetection/configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py b/grounding-dino/mmdetection/configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..772268b121e7b8858c4cfcf3b6820e6146634d0d --- /dev/null +++ b/grounding-dino/mmdetection/configs/cityscapes/mask-rcnn_r50_fpn_1x_cityscapes.py @@ -0,0 +1,43 @@ +_base_ = [ + '../_base_/models/mask-rcnn_r50_fpn.py', + '../_base_/datasets/cityscapes_instance.py', + '../_base_/default_runtime.py', '../_base_/schedules/schedule_1x.py' +] +model = dict( + backbone=dict(init_cfg=None), + roi_head=dict( + bbox_head=dict( + type='Shared2FCBBoxHead', + num_classes=8, + loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), + mask_head=dict(num_classes=8))) + +# optimizer +# lr is set for a batch size of 8 +optim_wrapper = dict(optimizer=dict(lr=0.01)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=8, + by_epoch=True, + # [7] yields higher performance than [6] + milestones=[7], + gamma=0.1) +] + +# actual epoch = 8 * 8 = 64 +train_cfg = dict(max_epochs=8) + +# For better, more stable performance initialize from COCO +load_from = 'https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_fpn_1x_coco/mask_rcnn_r50_fpn_1x_coco_20200205-d4b0c5d6.pth' # noqa + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (1 samples per GPU) +# TODO: support auto scaling lr +# auto_scale_lr = dict(base_batch_size=8) diff --git a/grounding-dino/mmdetection/configs/common/lsj-100e_coco-detection.py b/grounding-dino/mmdetection/configs/common/lsj-100e_coco-detection.py new file mode 100644 index 0000000000000000000000000000000000000000..bb631e5d5c1253cc3a5d81a8cdc6cd86133d9b53 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/lsj-100e_coco-detection.py @@ -0,0 +1,122 @@ +_base_ = '../_base_/default_runtime.py' +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' +image_size = (1024, 1024) + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomResize', + scale=image_size, + ratio_range=(0.1, 2.0), + keep_ratio=True), + dict( + type='RandomCrop', + crop_type='absolute_range', + crop_size=image_size, + recompute_bbox=True, + allow_negative_crop=True), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +# Use RepeatDataset to speed up training +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + dataset=dict( + type='RepeatDataset', + times=4, # simply change this from 2 to 16 for 50e - 400e training. + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +max_epochs = 25 + +train_cfg = dict( + type='EpochBasedTrainLoop', max_epochs=max_epochs, val_interval=5) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# optimizer assumes bs=64 +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.00004)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.067, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[22, 24], + gamma=0.1) +] + +# only keep latest 2 checkpoints +default_hooks = dict(checkpoint=dict(max_keep_ckpts=2)) + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (32 GPUs) x (2 samples per GPU) +auto_scale_lr = dict(base_batch_size=64) diff --git a/grounding-dino/mmdetection/configs/common/lsj-100e_coco-instance.py b/grounding-dino/mmdetection/configs/common/lsj-100e_coco-instance.py new file mode 100644 index 0000000000000000000000000000000000000000..6e62729d639c7659115a7f5f6449fa9021338be6 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/lsj-100e_coco-instance.py @@ -0,0 +1,122 @@ +_base_ = '../_base_/default_runtime.py' +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' +image_size = (1024, 1024) + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', + scale=image_size, + ratio_range=(0.1, 2.0), + keep_ratio=True), + dict( + type='RandomCrop', + crop_type='absolute_range', + crop_size=image_size, + recompute_bbox=True, + allow_negative_crop=True), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +# Use RepeatDataset to speed up training +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + dataset=dict( + type='RepeatDataset', + times=4, # simply change this from 2 to 16 for 50e - 400e training. + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +max_epochs = 25 + +train_cfg = dict( + type='EpochBasedTrainLoop', max_epochs=max_epochs, val_interval=5) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# optimizer assumes bs=64 +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.00004)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.067, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[22, 24], + gamma=0.1) +] + +# only keep latest 2 checkpoints +default_hooks = dict(checkpoint=dict(max_keep_ckpts=2)) + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (32 GPUs) x (2 samples per GPU) +auto_scale_lr = dict(base_batch_size=64) diff --git a/grounding-dino/mmdetection/configs/common/lsj-200e_coco-detection.py b/grounding-dino/mmdetection/configs/common/lsj-200e_coco-detection.py new file mode 100644 index 0000000000000000000000000000000000000000..83d12947fed900f05d748b6f90ef29cc5fbc407a --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/lsj-200e_coco-detection.py @@ -0,0 +1,18 @@ +_base_ = './lsj-100e_coco-detection.py' + +# 8x25=200e +train_dataloader = dict(dataset=dict(times=8)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.067, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=25, + by_epoch=True, + milestones=[22, 24], + gamma=0.1) +] diff --git a/grounding-dino/mmdetection/configs/common/lsj-200e_coco-instance.py b/grounding-dino/mmdetection/configs/common/lsj-200e_coco-instance.py new file mode 100644 index 0000000000000000000000000000000000000000..af3e4bf160c01045c6e36d67bdee796e7bf96cd3 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/lsj-200e_coco-instance.py @@ -0,0 +1,18 @@ +_base_ = './lsj-100e_coco-instance.py' + +# 8x25=200e +train_dataloader = dict(dataset=dict(times=8)) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.067, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=25, + by_epoch=True, + milestones=[22, 24], + gamma=0.1) +] diff --git a/grounding-dino/mmdetection/configs/common/ms-90k_coco.py b/grounding-dino/mmdetection/configs/common/ms-90k_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..e2d6c3dafb61d59bbbe9d0c6188a1bbff3b736b3 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/ms-90k_coco.py @@ -0,0 +1,122 @@ +_base_ = '../_base_/default_runtime.py' + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +# Align with Detectron2 +backend = 'pillow' +train_pipeline = [ + dict( + type='LoadImageFromFile', + backend_args=backend_args, + imdecode_backend=backend), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomChoiceResize', + scales=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True, + backend=backend), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict( + type='LoadImageFromFile', + backend_args=backend_args, + imdecode_backend=backend), + dict(type='Resize', scale=(1333, 800), keep_ratio=True, backend=backend), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + pin_memory=True, + sampler=dict(type='InfiniteSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + pin_memory=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# training schedule for 90k +max_iter = 90000 +train_cfg = dict( + type='IterBasedTrainLoop', max_iters=max_iter, val_interval=10000) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=max_iter, + by_epoch=False, + milestones=[60000, 80000], + gamma=0.1) +] + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) +# Default setting for scaling LR automatically +# - `enable` means enable scaling LR automatically +# or not by default. +# - `base_batch_size` = (8 GPUs) x (2 samples per GPU). +auto_scale_lr = dict(enable=False, base_batch_size=16) + +default_hooks = dict(checkpoint=dict(by_epoch=False, interval=10000)) +log_processor = dict(by_epoch=False) diff --git a/grounding-dino/mmdetection/configs/common/ms-poly-90k_coco-instance.py b/grounding-dino/mmdetection/configs/common/ms-poly-90k_coco-instance.py new file mode 100644 index 0000000000000000000000000000000000000000..d5566b3c3b8bfe0a49c8c062fb0fc972d5ae1f55 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/ms-poly-90k_coco-instance.py @@ -0,0 +1,130 @@ +_base_ = '../_base_/default_runtime.py' + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +# Align with Detectron2 +backend = 'pillow' +train_pipeline = [ + dict( + type='LoadImageFromFile', + backend_args=backend_args, + imdecode_backend=backend), + dict( + type='LoadAnnotations', + with_bbox=True, + with_mask=True, + poly2mask=False), + dict( + type='RandomChoiceResize', + scales=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), + (1333, 768), (1333, 800)], + keep_ratio=True, + backend=backend), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict( + type='LoadImageFromFile', + backend_args=backend_args, + imdecode_backend=backend), + dict(type='Resize', scale=(1333, 800), keep_ratio=True, backend=backend), + dict( + type='LoadAnnotations', + with_bbox=True, + with_mask=True, + poly2mask=False), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + pin_memory=True, + sampler=dict(type='InfiniteSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + pin_memory=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# training schedule for 90k +max_iter = 90000 +train_cfg = dict( + type='IterBasedTrainLoop', max_iters=max_iter, val_interval=10000) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=max_iter, + by_epoch=False, + milestones=[60000, 80000], + gamma=0.1) +] + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) +# Default setting for scaling LR automatically +# - `enable` means enable scaling LR automatically +# or not by default. +# - `base_batch_size` = (8 GPUs) x (2 samples per GPU). +auto_scale_lr = dict(enable=False, base_batch_size=16) + +default_hooks = dict(checkpoint=dict(by_epoch=False, interval=10000)) +log_processor = dict(by_epoch=False) diff --git a/grounding-dino/mmdetection/configs/common/ms-poly_3x_coco-instance.py b/grounding-dino/mmdetection/configs/common/ms-poly_3x_coco-instance.py new file mode 100644 index 0000000000000000000000000000000000000000..04072f9b84c06d546767649f7e17736444db7ce2 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/ms-poly_3x_coco-instance.py @@ -0,0 +1,118 @@ +_base_ = '../_base_/default_runtime.py' +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +# In mstrain 3x config, img_scale=[(1333, 640), (1333, 800)], +# multiscale_mode='range' +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict( + type='LoadAnnotations', + with_bbox=True, + with_mask=True, + poly2mask=False), + dict( + type='RandomResize', scale=[(1333, 640), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs'), +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict( + type='LoadAnnotations', + with_bbox=True, + with_mask=True, + poly2mask=False), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=3, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + backend_args=backend_args) +test_evaluator = val_evaluator + +# training schedule for 3x with `RepeatDataset` +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# learning rate +# Experiments show that using milestones=[9, 11] has higher performance +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[9, 11], + gamma=0.1) +] + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) + +# Default setting for scaling LR automatically +# - `enable` means enable scaling LR automatically +# or not by default. +# - `base_batch_size` = (8 GPUs) x (2 samples per GPU). +auto_scale_lr = dict(enable=False, base_batch_size=16) diff --git a/grounding-dino/mmdetection/configs/common/ms_3x_coco-instance.py b/grounding-dino/mmdetection/configs/common/ms_3x_coco-instance.py new file mode 100644 index 0000000000000000000000000000000000000000..f80cf88e9b1e770dce3157abc852aea996eec624 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/ms_3x_coco-instance.py @@ -0,0 +1,108 @@ +_base_ = '../_base_/default_runtime.py' + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', scale=[(1333, 640), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=3, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + backend_args=backend_args) +test_evaluator = val_evaluator + +# training schedule for 3x with `RepeatDataset` +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# learning rate +# Experiments show that using milestones=[9, 11] has higher performance +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[9, 11], + gamma=0.1) +] + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) + +# Default setting for scaling LR automatically +# - `enable` means enable scaling LR automatically +# or not by default. +# - `base_batch_size` = (8 GPUs) x (2 samples per GPU). +auto_scale_lr = dict(enable=False, base_batch_size=16) diff --git a/grounding-dino/mmdetection/configs/common/ms_3x_coco.py b/grounding-dino/mmdetection/configs/common/ms_3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..facbb34cf05088d8832502d3c9a38d812d328308 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/ms_3x_coco.py @@ -0,0 +1,108 @@ +_base_ = '../_base_/default_runtime.py' + +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='RandomResize', scale=[(1333, 640), (1333, 800)], + keep_ratio=True), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=dict(type='AspectRatioBatchSampler'), + dataset=dict( + type='RepeatDataset', + times=3, + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args))) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric='bbox', + backend_args=backend_args) +test_evaluator = val_evaluator + +# training schedule for 3x with `RepeatDataset` +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# learning rate +# Experiments show that using milestones=[9, 11] has higher performance +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500), + dict( + type='MultiStepLR', + begin=0, + end=12, + by_epoch=True, + milestones=[9, 11], + gamma=0.1) +] + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)) + +# Default setting for scaling LR automatically +# - `enable` means enable scaling LR automatically +# or not by default. +# - `base_batch_size` = (8 GPUs) x (2 samples per GPU). +auto_scale_lr = dict(enable=False, base_batch_size=16) diff --git a/grounding-dino/mmdetection/configs/common/ssj_270k_coco-instance.py b/grounding-dino/mmdetection/configs/common/ssj_270k_coco-instance.py new file mode 100644 index 0000000000000000000000000000000000000000..7407644fd59bb03d6e0afde83f8893a351ddc356 --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/ssj_270k_coco-instance.py @@ -0,0 +1,125 @@ +_base_ = '../_base_/default_runtime.py' +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +image_size = (1024, 1024) + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +# Standard Scale Jittering (SSJ) resizes and crops an image +# with a resize range of 0.8 to 1.25 of the original image size. +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', + scale=image_size, + ratio_range=(0.8, 1.25), + keep_ratio=True), + dict( + type='RandomCrop', + crop_type='absolute_range', + crop_size=image_size, + recompute_bbox=True, + allow_negative_crop=True), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs') +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1333, 800), keep_ratio=True), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=2, + persistent_workers=True, + sampler=dict(type='InfiniteSampler'), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_val2017.json', + data_prefix=dict(img='val2017/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CocoMetric', + ann_file=data_root + 'annotations/instances_val2017.json', + metric=['bbox', 'segm'], + format_only=False, + backend_args=backend_args) +test_evaluator = val_evaluator + +# The model is trained by 270k iterations with batch_size 64, +# which is roughly equivalent to 144 epochs. + +max_iters = 270000 +train_cfg = dict( + type='IterBasedTrainLoop', max_iters=max_iters, val_interval=10000) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# optimizer assumes bs=64 +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.00004)) + +# learning rate policy +# lr steps at [0.9, 0.95, 0.975] of the maximum iterations +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=270000, + by_epoch=False, + milestones=[243000, 256500, 263250], + gamma=0.1) +] + +default_hooks = dict(checkpoint=dict(by_epoch=False, interval=10000)) +log_processor = dict(by_epoch=False) + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (32 GPUs) x (2 samples per GPU) +auto_scale_lr = dict(base_batch_size=64) diff --git a/grounding-dino/mmdetection/configs/common/ssj_scp_270k_coco-instance.py b/grounding-dino/mmdetection/configs/common/ssj_scp_270k_coco-instance.py new file mode 100644 index 0000000000000000000000000000000000000000..06159dd40312ec935ac383701fa7b052b863e1bf --- /dev/null +++ b/grounding-dino/mmdetection/configs/common/ssj_scp_270k_coco-instance.py @@ -0,0 +1,60 @@ +_base_ = 'ssj_270k_coco-instance.py' +# dataset settings +dataset_type = 'CocoDataset' +data_root = 'data/coco/' + +image_size = (1024, 1024) + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/detection/coco/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/detection/', +# 'data/': 's3://openmmlab/datasets/detection/' +# })) +backend_args = None + +# Standard Scale Jittering (SSJ) resizes and crops an image +# with a resize range of 0.8 to 1.25 of the original image size. +load_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict( + type='RandomResize', + scale=image_size, + ratio_range=(0.8, 1.25), + keep_ratio=True), + dict( + type='RandomCrop', + crop_type='absolute_range', + crop_size=image_size, + recompute_bbox=True, + allow_negative_crop=True), + dict(type='FilterAnnotations', min_gt_bbox_wh=(1e-2, 1e-2)), + dict(type='RandomFlip', prob=0.5), + dict(type='Pad', size=image_size), +] +train_pipeline = [ + dict(type='CopyPaste', max_num_pasted=100), + dict(type='PackDetInputs') +] + +train_dataloader = dict( + dataset=dict( + _delete_=True, + type='MultiImageMixDataset', + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotations/instances_train2017.json', + data_prefix=dict(img='train2017/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=load_pipeline, + backend_args=backend_args), + pipeline=train_pipeline)) diff --git a/grounding-dino/mmdetection/configs/condinst/README.md b/grounding-dino/mmdetection/configs/condinst/README.md new file mode 100644 index 0000000000000000000000000000000000000000..01deb0ecff4e2a5526029aed31d4cf8a87c8545f --- /dev/null +++ b/grounding-dino/mmdetection/configs/condinst/README.md @@ -0,0 +1,40 @@ +# CondInst + +> [CondInst: Conditional Convolutions for Instance +> Segmentation](https://arxiv.org/pdf/2003.05664.pdf) + + + +## Abstract + +We propose a simple yet effective instance segmentation framework, termed CondInst (conditional convolutions for instance segmentation). Top-performing instance segmentation methods such as Mask +R-CNN rely on ROI operations (typically ROIPool or ROIAlign) to +obtain the final instance masks. In contrast, we propose to solve instance segmentation from a new perspective. Instead of using instancewise ROIs as inputs to a network of fixed weights, we employ dynamic +instance-aware networks, conditioned on instances. CondInst enjoys two +advantages: 1) Instance segmentation is solved by a fully convolutional +network, eliminating the need for ROI cropping and feature alignment. +2\) Due to the much improved capacity of dynamically-generated conditional convolutions, the mask head can be very compact (e.g., 3 conv. +layers, each having only 8 channels), leading to significantly faster inference. We demonstrate a simpler instance segmentation method that can +achieve improved performance in both accuracy and inference speed. On +the COCO dataset, we outperform a few recent methods including welltuned Mask R-CNN baselines, without longer training schedules needed. + +
+ +
+ +## Results and Models + +| Backbone | Style | MS train | Lr schd | bbox AP | mask AP | Config | Download | +| :------: | :-----: | :------: | :-----: | :-----: | :-----: | :-------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50 | pytorch | Y | 1x | 39.8 | 36.0 | [config](./condinst_r50_fpn_ms-poly-90k_coco_instance.py) | [model](https://download.openmmlab.com/mmdetection/v3.0/condinst/condinst_r50_fpn_ms-poly-90k_coco_instance/condinst_r50_fpn_ms-poly-90k_coco_instance_20221129_125223-4c186406.pth) \| [log](https://download.openmmlab.com/mmdetection/v3.0/condinst/condinst_r50_fpn_ms-poly-90k_coco_instance/condinst_r50_fpn_ms-poly-90k_coco_instance_20221129_125223.json) | + +## Citation + +```latex +@inproceedings{tian2020conditional, + title = {Conditional Convolutions for Instance Segmentation}, + author = {Tian, Zhi and Shen, Chunhua and Chen, Hao}, + booktitle = {Proc. Eur. Conf. Computer Vision (ECCV)}, + year = {2020} +} +``` diff --git a/grounding-dino/mmdetection/configs/condinst/condinst_r50_fpn_ms-poly-90k_coco_instance.py b/grounding-dino/mmdetection/configs/condinst/condinst_r50_fpn_ms-poly-90k_coco_instance.py new file mode 100644 index 0000000000000000000000000000000000000000..39639d874cbeb54b64a2789f251f1f6dad585ce3 --- /dev/null +++ b/grounding-dino/mmdetection/configs/condinst/condinst_r50_fpn_ms-poly-90k_coco_instance.py @@ -0,0 +1,85 @@ +_base_ = '../common/ms-poly-90k_coco-instance.py' + +# model settings +model = dict( + type='CondInst', + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_mask=True, + pad_size_divisor=32), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=True, + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), + style='pytorch'), + neck=dict( + type='FPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + start_level=1, + add_extra_convs='on_output', # use P5 + num_outs=5, + relu_before_extra_convs=True), + bbox_head=dict( + type='CondInstBboxHead', + num_params=169, + num_classes=80, + in_channels=256, + stacked_convs=4, + feat_channels=256, + strides=[8, 16, 32, 64, 128], + norm_on_bbox=True, + centerness_on_reg=True, + dcn_on_last_conv=False, + center_sampling=True, + conv_bias=True, + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=1.0), + loss_centerness=dict( + type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)), + mask_head=dict( + type='CondInstMaskHead', + num_layers=3, + feat_channels=8, + size_of_interest=8, + mask_out_stride=4, + max_masks_to_train=300, + mask_feature_head=dict( + in_channels=256, + feat_channels=128, + start_level=0, + end_level=2, + out_channels=8, + mask_stride=8, + num_stacked_convs=4, + norm_cfg=dict(type='BN', requires_grad=True)), + loss_mask=dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + eps=5e-6, + loss_weight=1.0)), + # model training and testing settings + test_cfg=dict( + nms_pre=1000, + min_bbox_size=0, + score_thr=0.05, + nms=dict(type='nms', iou_threshold=0.6), + max_per_img=100, + mask_thr=0.5)) + +# optimizer +optim_wrapper = dict(optimizer=dict(lr=0.01)) diff --git a/grounding-dino/mmdetection/configs/condinst/metafile.yml b/grounding-dino/mmdetection/configs/condinst/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..1237b74d77a8b1f1e4b0ba74c6bdc5e5595d9816 --- /dev/null +++ b/grounding-dino/mmdetection/configs/condinst/metafile.yml @@ -0,0 +1,32 @@ +Collections: + - Name: CondInst + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x A100 GPUs + Architecture: + - FPN + - FCOS + - ResNet + Paper: https://arxiv.org/abs/2003.05664 + README: configs/condinst/README.md + +Models: + - Name: condinst_r50_fpn_ms-poly-90k_coco_instance + In Collection: CondInst + Config: configs/condinst/condinst_r50_fpn_ms-poly-90k_coco_instance.py + Metadata: + Training Memory (GB): 4.4 + Iterations: 90000 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 39.8 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 36.0 + Weights: https://download.openmmlab.com/mmdetection/v3.0/condinst/condinst_r50_fpn_ms-poly-90k_coco_instance/condinst_r50_fpn_ms-poly-90k_coco_instance_20221129_125223-4c186406.pth diff --git a/grounding-dino/mmdetection/configs/conditional_detr/README.md b/grounding-dino/mmdetection/configs/conditional_detr/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4043571c576bba7f287e16e7e464950b5568543e --- /dev/null +++ b/grounding-dino/mmdetection/configs/conditional_detr/README.md @@ -0,0 +1,39 @@ +# Conditional DETR + +> [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152) + + + +## Abstract + +The DETR approach applies the transformer encoder and decoder architecture to object detection and achieves promising performance. In this paper, we handle the critical issue, slow training convergence, and present a conditional cross-attention mechanism for fast DETR training. Our approach is motivated by that the cross-attention in DETR relies highly on the content embeddings and that the spatial embeddings make minor contributions, increasing the need for high-quality content embeddings and thus increasing the training difficulty. + +
+ +
+ +Our conditional DETR learns a conditional spatial query from the decoder embedding for decoder multi-head cross-attention. The benefit is that through the conditional spatial query, each cross-attention head is able to attend to a band containing a distinct region, e.g., one object extremity or a region inside the object box (Figure 1). This narrows down the spatial range for localizing the distinct regions for object classification and box regression, thus relaxing the dependence on the content embeddings and easing the training. Empirical results show that conditional DETR converges 6.7x faster for the backbones R50 and R101 and 10x faster for stronger backbones DC5-R50 and DC5-R101. + +
+ + +
+ +## Results and Models + +We provide the config files and models for Conditional DETR: [Conditional DETR for Fast Training Convergence](https://arxiv.org/abs/2108.06152). + +| Backbone | Model | Lr schd | Mem (GB) | Inf time (fps) | box AP | Config | Download | +| :------: | :--------------: | :-----: | :------: | :------------: | :----: | :-----------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50 | Conditional DETR | 50e | | | 41.1 | [config](./conditional-detr_r50_8xb2-50e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v3.0/conditional_detr/conditional-detr_r50_8xb2-50e_coco/conditional-detr_r50_8xb2-50e_coco_20221121_180202-c83a1dc0.pth) \| [log](https://download.openmmlab.com/mmdetection/v3.0/conditional_detr/conditional-detr_r50_8xb2-50e_coco/conditional-detr_r50_8xb2-50e_coco_20221121_180202.log.json) | + +## Citation + +```latex +@inproceedings{meng2021-CondDETR, + title = {Conditional DETR for Fast Training Convergence}, + author = {Meng, Depu and Chen, Xiaokang and Fan, Zejia and Zeng, Gang and Li, Houqiang and Yuan, Yuhui and Sun, Lei and Wang, Jingdong}, + booktitle = {Proceedings of the IEEE International Conference on Computer Vision (ICCV)}, + year = {2021} +} +``` diff --git a/grounding-dino/mmdetection/configs/conditional_detr/conditional-detr_r50_8xb2-50e_coco.py b/grounding-dino/mmdetection/configs/conditional_detr/conditional-detr_r50_8xb2-50e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..a21476448d0cbab6b6e4b94aa46d686e38667879 --- /dev/null +++ b/grounding-dino/mmdetection/configs/conditional_detr/conditional-detr_r50_8xb2-50e_coco.py @@ -0,0 +1,42 @@ +_base_ = ['../detr/detr_r50_8xb2-150e_coco.py'] +model = dict( + type='ConditionalDETR', + num_queries=300, + decoder=dict( + num_layers=6, + layer_cfg=dict( + self_attn_cfg=dict( + _delete_=True, + embed_dims=256, + num_heads=8, + attn_drop=0.1, + cross_attn=False), + cross_attn_cfg=dict( + _delete_=True, + embed_dims=256, + num_heads=8, + attn_drop=0.1, + cross_attn=True))), + bbox_head=dict( + type='ConditionalDETRHead', + loss_cls=dict( + _delete_=True, + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=2.0)), + # training and testing settings + train_cfg=dict( + assigner=dict( + type='HungarianAssigner', + match_costs=[ + dict(type='FocalLossCost', weight=2.0), + dict(type='BBoxL1Cost', weight=5.0, box_format='xywh'), + dict(type='IoUCost', iou_mode='giou', weight=2.0) + ]))) + +# learning policy +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=50, val_interval=1) + +param_scheduler = [dict(type='MultiStepLR', end=50, milestones=[40])] diff --git a/grounding-dino/mmdetection/configs/conditional_detr/metafile.yml b/grounding-dino/mmdetection/configs/conditional_detr/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..83f5532ce380c903d644b36055c4c2610455472a --- /dev/null +++ b/grounding-dino/mmdetection/configs/conditional_detr/metafile.yml @@ -0,0 +1,32 @@ +Collections: + - Name: Conditional DETR + Metadata: + Training Data: COCO + Training Techniques: + - AdamW + - Multi Scale Train + - Gradient Clip + Training Resources: 8x A100 GPUs + Architecture: + - ResNet + - Transformer + Paper: + URL: https://arxiv.org/abs/2108.06152 + Title: 'Conditional DETR for Fast Training Convergence' + README: configs/conditional_detr/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/f4112c9e5611468ffbd57cfba548fd1289264b52/mmdet/models/detectors/conditional_detr.py#L14 + Version: v3.0.0rc6 + +Models: + - Name: conditional-detr_r50_8xb2-50e_coco + In Collection: Conditional DETR + Config: configs/conditional_detr/conditional-detr_r50_8xb2-50e_coco.py + Metadata: + Epochs: 50 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 40.9 + Weights: https://download.openmmlab.com/mmdetection/v3.0/conditional_detr/conditional-detr_r50_8xb2-50e_coco/conditional-detr_r50_8xb2-50e_coco_20221121_180202-c83a1dc0.pth diff --git a/grounding-dino/mmdetection/configs/convnext/README.md b/grounding-dino/mmdetection/configs/convnext/README.md new file mode 100644 index 0000000000000000000000000000000000000000..33497bb57aa9ae89b91ee16ac81e1ce02bf2ae0d --- /dev/null +++ b/grounding-dino/mmdetection/configs/convnext/README.md @@ -0,0 +1,42 @@ +# ConvNeXt + +> [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) + + + +## Abstract + +The "Roaring 20s" of visual recognition began with the introduction of Vision Transformers (ViTs), which quickly superseded ConvNets as the state-of-the-art image classification model. A vanilla ViT, on the other hand, faces difficulties when applied to general computer vision tasks such as object detection and semantic segmentation. It is the hierarchical Transformers (e.g., Swin Transformers) that reintroduced several ConvNet priors, making Transformers practically viable as a generic vision backbone and demonstrating remarkable performance on a wide variety of vision tasks. However, the effectiveness of such hybrid approaches is still largely credited to the intrinsic superiority of Transformers, rather than the inherent inductive biases of convolutions. In this work, we reexamine the design spaces and test the limits of what a pure ConvNet can achieve. We gradually "modernize" a standard ResNet toward the design of a vision Transformer, and discover several key components that contribute to the performance difference along the way. The outcome of this exploration is a family of pure ConvNet models dubbed ConvNeXt. Constructed entirely from standard ConvNet modules, ConvNeXts compete favorably with Transformers in terms of accuracy and scalability, achieving 87.8% ImageNet top-1 accuracy and outperforming Swin Transformers on COCO detection and ADE20K segmentation, while maintaining the simplicity and efficiency of standard ConvNets. + +
+ +
+ +## Results and models + +| Method | Backbone | Pretrain | Lr schd | Multi-scale crop | FP16 | Mem (GB) | box AP | mask AP | Config | Download | +| :----------------: | :--------: | :---------: | :-----: | :--------------: | :--: | :------: | :----: | :-----: | :-------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| Mask R-CNN | ConvNeXt-T | ImageNet-1K | 3x | yes | yes | 7.3 | 46.2 | 41.7 | [config](./mask-rcnn_convnext-t-p4-w7_fpn_amp-ms-crop-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/convnext/mask_rcnn_convnext-t_p4_w7_fpn_fp16_ms-crop_3x_coco/mask_rcnn_convnext-t_p4_w7_fpn_fp16_ms-crop_3x_coco_20220426_154953-050731f4.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/convnext/mask_rcnn_convnext-t_p4_w7_fpn_fp16_ms-crop_3x_coco/mask_rcnn_convnext-t_p4_w7_fpn_fp16_ms-crop_3x_coco_20220426_154953.log.json) | +| Cascade Mask R-CNN | ConvNeXt-T | ImageNet-1K | 3x | yes | yes | 9.0 | 50.3 | 43.6 | [config](./cascade-mask-rcnn_convnext-t-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/convnext/cascade_mask_rcnn_convnext-t_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco/cascade_mask_rcnn_convnext-t_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco_20220509_204200-8f07c40b.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/convnext/cascade_mask_rcnn_convnext-t_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco/cascade_mask_rcnn_convnext-t_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco_20220509_204200.log.json) | +| Cascade Mask R-CNN | ConvNeXt-S | ImageNet-1K | 3x | yes | yes | 12.3 | 51.8 | 44.8 | [config](./cascade-mask-rcnn_convnext-s-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/convnext/cascade_mask_rcnn_convnext-s_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco/cascade_mask_rcnn_convnext-s_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco_20220510_201004-3d24f5a4.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/convnext/cascade_mask_rcnn_convnext-s_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco/cascade_mask_rcnn_convnext-s_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco_20220510_201004.log.json) | + +**Note**: + +- ConvNeXt backbone needs to install [MMPreTrain](https://github.com/open-mmlab/mmpretrain) first, which has abundant backbones for downstream tasks. + +```shell +pip install mmpretrain +``` + +- The performance is unstable. `Cascade Mask R-CNN` may fluctuate about 0.2 mAP. + +## Citation + +```bibtex +@article{liu2022convnet, + title={A ConvNet for the 2020s}, + author={Liu, Zhuang and Mao, Hanzi and Wu, Chao-Yuan and Feichtenhofer, Christoph and Darrell, Trevor and Xie, Saining}, + journal={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, + year={2022} +} +``` diff --git a/grounding-dino/mmdetection/configs/convnext/cascade-mask-rcnn_convnext-s-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py b/grounding-dino/mmdetection/configs/convnext/cascade-mask-rcnn_convnext-s-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..9a5fbedcaa78636f11a5718f1123d33e7e2ac273 --- /dev/null +++ b/grounding-dino/mmdetection/configs/convnext/cascade-mask-rcnn_convnext-s-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py @@ -0,0 +1,26 @@ +_base_ = './cascade-mask-rcnn_convnext-t-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py' # noqa + +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict( + imports=['mmpretrain.models'], allow_failed_imports=False) +checkpoint_file = 'https://download.openmmlab.com/mmclassification/v0/convnext/downstream/convnext-small_3rdparty_32xb128-noema_in1k_20220301-303e75e3.pth' # noqa + +model = dict( + backbone=dict( + _delete_=True, + type='mmpretrain.ConvNeXt', + arch='small', + out_indices=[0, 1, 2, 3], + drop_path_rate=0.6, + layer_scale_init_value=1.0, + gap_before_final_norm=False, + init_cfg=dict( + type='Pretrained', checkpoint=checkpoint_file, + prefix='backbone.'))) + +optim_wrapper = dict(paramwise_cfg={ + 'decay_rate': 0.7, + 'decay_type': 'layer_wise', + 'num_layers': 12 +}) diff --git a/grounding-dino/mmdetection/configs/convnext/cascade-mask-rcnn_convnext-t-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py b/grounding-dino/mmdetection/configs/convnext/cascade-mask-rcnn_convnext-t-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..c92f86838c31710dd550c36d9abc11d79bb6e2eb --- /dev/null +++ b/grounding-dino/mmdetection/configs/convnext/cascade-mask-rcnn_convnext-t-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py @@ -0,0 +1,154 @@ +_base_ = [ + '../_base_/models/cascade-mask-rcnn_r50_fpn.py', + '../_base_/datasets/coco_instance.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict( + imports=['mmpretrain.models'], allow_failed_imports=False) +checkpoint_file = 'https://download.openmmlab.com/mmclassification/v0/convnext/downstream/convnext-tiny_3rdparty_32xb128-noema_in1k_20220301-795e9634.pth' # noqa + +model = dict( + backbone=dict( + _delete_=True, + type='mmpretrain.ConvNeXt', + arch='tiny', + out_indices=[0, 1, 2, 3], + drop_path_rate=0.4, + layer_scale_init_value=1.0, + gap_before_final_norm=False, + init_cfg=dict( + type='Pretrained', checkpoint=checkpoint_file, + prefix='backbone.')), + neck=dict(in_channels=[96, 192, 384, 768]), + roi_head=dict(bbox_head=[ + dict( + type='ConvFCBBoxHead', + num_shared_convs=4, + num_shared_fcs=1, + in_channels=256, + conv_out_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=80, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.1, 0.1, 0.2, 0.2]), + reg_class_agnostic=False, + reg_decoded_bbox=True, + norm_cfg=dict(type='SyncBN', requires_grad=True), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=10.0)), + dict( + type='ConvFCBBoxHead', + num_shared_convs=4, + num_shared_fcs=1, + in_channels=256, + conv_out_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=80, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.05, 0.05, 0.1, 0.1]), + reg_class_agnostic=False, + reg_decoded_bbox=True, + norm_cfg=dict(type='SyncBN', requires_grad=True), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=10.0)), + dict( + type='ConvFCBBoxHead', + num_shared_convs=4, + num_shared_fcs=1, + in_channels=256, + conv_out_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=80, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.033, 0.033, 0.067, 0.067]), + reg_class_agnostic=False, + reg_decoded_bbox=True, + norm_cfg=dict(type='SyncBN', requires_grad=True), + loss_cls=dict( + type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), + loss_bbox=dict(type='GIoULoss', loss_weight=10.0)) + ])) + +# augmentation strategy originates from DETR / Sparse RCNN +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomChoice', + transforms=[[ + dict( + type='RandomChoiceResize', + scales=[(480, 1333), (512, 1333), (544, 1333), (576, 1333), + (608, 1333), (640, 1333), (672, 1333), (704, 1333), + (736, 1333), (768, 1333), (800, 1333)], + keep_ratio=True) + ], + [ + dict( + type='RandomChoiceResize', + scales=[(400, 1333), (500, 1333), (600, 1333)], + keep_ratio=True), + dict( + type='RandomCrop', + crop_type='absolute_range', + crop_size=(384, 600), + allow_negative_crop=True), + dict( + type='RandomChoiceResize', + scales=[(480, 1333), (512, 1333), (544, 1333), + (576, 1333), (608, 1333), (640, 1333), + (672, 1333), (704, 1333), (736, 1333), + (768, 1333), (800, 1333)], + keep_ratio=True) + ]]), + dict(type='PackDetInputs') +] +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) + +max_epochs = 36 +train_cfg = dict(max_epochs=max_epochs) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[27, 33], + gamma=0.1) +] + +# Enable automatic-mixed-precision training with AmpOptimWrapper. +optim_wrapper = dict( + type='AmpOptimWrapper', + constructor='LearningRateDecayOptimizerConstructor', + paramwise_cfg={ + 'decay_rate': 0.7, + 'decay_type': 'layer_wise', + 'num_layers': 6 + }, + optimizer=dict( + _delete_=True, + type='AdamW', + lr=0.0002, + betas=(0.9, 0.999), + weight_decay=0.05)) diff --git a/grounding-dino/mmdetection/configs/convnext/mask-rcnn_convnext-t-p4-w7_fpn_amp-ms-crop-3x_coco.py b/grounding-dino/mmdetection/configs/convnext/mask-rcnn_convnext-t-p4-w7_fpn_amp-ms-crop-3x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..5792b5b5c5a03c85a7d69040dd9a0b5381bc7995 --- /dev/null +++ b/grounding-dino/mmdetection/configs/convnext/mask-rcnn_convnext-t-p4-w7_fpn_amp-ms-crop-3x_coco.py @@ -0,0 +1,96 @@ +_base_ = [ + '../_base_/models/mask-rcnn_r50_fpn.py', + '../_base_/datasets/coco_instance.py', + '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' +] + +# please install mmpretrain +# import mmpretrain.models to trigger register_module in mmpretrain +custom_imports = dict( + imports=['mmpretrain.models'], allow_failed_imports=False) +checkpoint_file = 'https://download.openmmlab.com/mmclassification/v0/convnext/downstream/convnext-tiny_3rdparty_32xb128-noema_in1k_20220301-795e9634.pth' # noqa + +model = dict( + backbone=dict( + _delete_=True, + type='mmpretrain.ConvNeXt', + arch='tiny', + out_indices=[0, 1, 2, 3], + drop_path_rate=0.4, + layer_scale_init_value=1.0, + gap_before_final_norm=False, + init_cfg=dict( + type='Pretrained', checkpoint=checkpoint_file, + prefix='backbone.')), + neck=dict(in_channels=[96, 192, 384, 768])) + +# augmentation strategy originates from DETR / Sparse RCNN +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), + dict(type='LoadAnnotations', with_bbox=True, with_mask=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomChoice', + transforms=[[ + dict( + type='RandomChoiceResize', + scales=[(480, 1333), (512, 1333), (544, 1333), (576, 1333), + (608, 1333), (640, 1333), (672, 1333), (704, 1333), + (736, 1333), (768, 1333), (800, 1333)], + keep_ratio=True) + ], + [ + dict( + type='RandomChoiceResize', + scales=[(400, 1333), (500, 1333), (600, 1333)], + keep_ratio=True), + dict( + type='RandomCrop', + crop_type='absolute_range', + crop_size=(384, 600), + allow_negative_crop=True), + dict( + type='RandomChoiceResize', + scales=[(480, 1333), (512, 1333), (544, 1333), + (576, 1333), (608, 1333), (640, 1333), + (672, 1333), (704, 1333), (736, 1333), + (768, 1333), (800, 1333)], + keep_ratio=True) + ]]), + dict(type='PackDetInputs') +] +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) + +max_epochs = 36 +train_cfg = dict(max_epochs=max_epochs) + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, + end=1000), + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[27, 33], + gamma=0.1) +] + +# Enable automatic-mixed-precision training with AmpOptimWrapper. +optim_wrapper = dict( + type='AmpOptimWrapper', + constructor='LearningRateDecayOptimizerConstructor', + paramwise_cfg={ + 'decay_rate': 0.95, + 'decay_type': 'layer_wise', + 'num_layers': 6 + }, + optimizer=dict( + _delete_=True, + type='AdamW', + lr=0.0001, + betas=(0.9, 0.999), + weight_decay=0.05, + )) diff --git a/grounding-dino/mmdetection/configs/convnext/metafile.yml b/grounding-dino/mmdetection/configs/convnext/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..b9fd7506cf46896d6c5f2238b594d32558ed3195 --- /dev/null +++ b/grounding-dino/mmdetection/configs/convnext/metafile.yml @@ -0,0 +1,93 @@ +Models: + - Name: mask-rcnn_convnext-t-p4-w7_fpn_amp-ms-crop-3x_coco + In Collection: Mask R-CNN + Config: configs/convnext/mask-rcnn_convnext-t-p4-w7_fpn_amp-ms-crop-3x_coco.py + Metadata: + Training Memory (GB): 7.3 + Epochs: 36 + Training Data: COCO + Training Techniques: + - AdamW + - Mixed Precision Training + Training Resources: 8x A100 GPUs + Architecture: + - ConvNeXt + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 46.2 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 41.7 + Weights: https://download.openmmlab.com/mmdetection/v2.0/convnext/mask_rcnn_convnext-t_p4_w7_fpn_fp16_ms-crop_3x_coco/mask_rcnn_convnext-t_p4_w7_fpn_fp16_ms-crop_3x_coco_20220426_154953-050731f4.pth + Paper: + URL: https://arxiv.org/abs/2201.03545 + Title: 'A ConvNet for the 2020s' + README: configs/convnext/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.16.0/mmdet/models/backbones/swin.py#L465 + Version: v2.16.0 + + - Name: cascade-mask-rcnn_convnext-t-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco + In Collection: Cascade Mask R-CNN + Config: configs/convnext/cascade-mask-rcnn_convnext-t-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py + Metadata: + Training Memory (GB): 9.0 + Epochs: 36 + Training Data: COCO + Training Techniques: + - AdamW + - Mixed Precision Training + Training Resources: 8x A100 GPUs + Architecture: + - ConvNeXt + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 50.3 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 43.6 + Weights: https://download.openmmlab.com/mmdetection/v2.0/convnext/cascade_mask_rcnn_convnext-t_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco/cascade_mask_rcnn_convnext-t_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco_20220509_204200-8f07c40b.pth + Paper: + URL: https://arxiv.org/abs/2201.03545 + Title: 'A ConvNet for the 2020s' + README: configs/convnext/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.16.0/mmdet/models/backbones/swin.py#L465 + Version: v2.25.0 + + - Name: cascade-mask-rcnn_convnext-s-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco + In Collection: Cascade Mask R-CNN + Config: configs/convnext/cascade-mask-rcnn_convnext-s-p4-w7_fpn_4conv1fc-giou_amp-ms-crop-3x_coco.py + Metadata: + Training Memory (GB): 12.3 + Epochs: 36 + Training Data: COCO + Training Techniques: + - AdamW + - Mixed Precision Training + Training Resources: 8x A100 GPUs + Architecture: + - ConvNeXt + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 51.8 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 44.8 + Weights: https://download.openmmlab.com/mmdetection/v2.0/convnext/cascade_mask_rcnn_convnext-s_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco/cascade_mask_rcnn_convnext-s_p4_w7_fpn_giou_4conv1f_fp16_ms-crop_3x_coco_20220510_201004-3d24f5a4.pth + Paper: + URL: https://arxiv.org/abs/2201.03545 + Title: 'A ConvNet for the 2020s' + README: configs/convnext/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.16.0/mmdet/models/backbones/swin.py#L465 + Version: v2.25.0 diff --git a/grounding-dino/mmdetection/configs/cornernet/README.md b/grounding-dino/mmdetection/configs/cornernet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e44964d8eac120f7313e7891b1771393b66bd9ae --- /dev/null +++ b/grounding-dino/mmdetection/configs/cornernet/README.md @@ -0,0 +1,43 @@ +# CornerNet + +> [Cornernet: Detecting objects as paired keypoints](https://arxiv.org/abs/1808.01244) + + + +## Abstract + +We propose CornerNet, a new approach to object detection where we detect an object bounding box as a pair of keypoints, the top-left corner and the bottom-right corner, using a single convolution neural network. By detecting objects as paired keypoints, we eliminate the need for designing a set of anchor boxes commonly used in prior single-stage detectors. In addition to our novel formulation, we introduce corner pooling, a new type of pooling layer that helps the network better localize corners. Experiments show that CornerNet achieves a 42.2% AP on MS COCO, outperforming all existing one-stage detectors. + +
+ +
+ +## Results and Models + +| Backbone | Batch Size | Step/Total Epochs | Mem (GB) | Inf time (fps) | box AP | Config | Download | +| :--------------: | :------------------------------------------------------------------: | :---------------: | :------: | :------------: | :----: | :------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| HourglassNet-104 | [10 x 5](./cornernet_hourglass104_10xb5-crop511-210e-mstest_coco.py) | 180/210 | 13.9 | 4.2 | 41.2 | [config](./cornernet_hourglass104_10xb5-crop511-210e-mstest_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_10x5_210e_coco/cornernet_hourglass104_mstest_10x5_210e_coco_20200824_185720-5fefbf1c.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_10x5_210e_coco/cornernet_hourglass104_mstest_10x5_210e_coco_20200824_185720.log.json) | +| HourglassNet-104 | [8 x 6](./cornernet_hourglass104_8xb6-210e-mstest_coco.py) | 180/210 | 15.9 | 4.2 | 41.2 | [config](./cornernet_hourglass104_8xb6-210e-mstest_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_8x6_210e_coco/cornernet_hourglass104_mstest_8x6_210e_coco_20200825_150618-79b44c30.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_8x6_210e_coco/cornernet_hourglass104_mstest_8x6_210e_coco_20200825_150618.log.json) | +| HourglassNet-104 | [32 x 3](./cornernet_hourglass104_32xb3-210e-mstest_coco.py) | 180/210 | 9.5 | 3.9 | 40.4 | [config](./cornernet_hourglass104_32xb3-210e-mstest_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_32x3_210e_coco/cornernet_hourglass104_mstest_32x3_210e_coco_20200819_203110-1efaea91.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_32x3_210e_coco/cornernet_hourglass104_mstest_32x3_210e_coco_20200819_203110.log.json) | + +Note: + +- TTA setting is single-scale and `flip=True`. If you want to reproduce the TTA performance, please add `--tta` in the test command. +- Experiments with `images_per_gpu=6` are conducted on Tesla V100-SXM2-32GB, `images_per_gpu=3` are conducted on GeForce GTX 1080 Ti. +- Here are the descriptions of each experiment setting: + - 10 x 5: 10 GPUs with 5 images per gpu. This is the same setting as that reported in the original paper. + - 8 x 6: 8 GPUs with 6 images per gpu. The total batchsize is similar to paper and only need 1 node to train. + - 32 x 3: 32 GPUs with 3 images per gpu. The default setting for 1080TI and need 4 nodes to train. + +## Citation + +```latex +@inproceedings{law2018cornernet, + title={Cornernet: Detecting objects as paired keypoints}, + author={Law, Hei and Deng, Jia}, + booktitle={15th European Conference on Computer Vision, ECCV 2018}, + pages={765--781}, + year={2018}, + organization={Springer Verlag} +} +``` diff --git a/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_10xb5-crop511-210e-mstest_coco.py b/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_10xb5-crop511-210e-mstest_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..76339163b618a5a9d41a542ec75192aedb409eea --- /dev/null +++ b/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_10xb5-crop511-210e-mstest_coco.py @@ -0,0 +1,8 @@ +_base_ = './cornernet_hourglass104_8xb6-210e-mstest_coco.py' + +train_dataloader = dict(batch_size=5) + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (10 GPUs) x (5 samples per GPU) +auto_scale_lr = dict(base_batch_size=50) diff --git a/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_32xb3-210e-mstest_coco.py b/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_32xb3-210e-mstest_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..51a4740318a1d85a62b6b4482c53808c98fb8a62 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_32xb3-210e-mstest_coco.py @@ -0,0 +1,8 @@ +_base_ = './cornernet_hourglass104_8xb6-210e-mstest_coco.py' + +train_dataloader = dict(batch_size=3) + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (32 GPUs) x (3 samples per GPU) +auto_scale_lr = dict(base_batch_size=96) diff --git a/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py b/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb46fff164f796d9333c123deb701c341bdc1e3 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py @@ -0,0 +1,183 @@ +_base_ = [ + '../_base_/default_runtime.py', '../_base_/datasets/coco_detection.py' +] + +data_preprocessor = dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True) + +# model settings +model = dict( + type='CornerNet', + data_preprocessor=data_preprocessor, + backbone=dict( + type='HourglassNet', + downsample_times=5, + num_stacks=2, + stage_channels=[256, 256, 384, 384, 384, 512], + stage_blocks=[2, 2, 2, 2, 2, 4], + norm_cfg=dict(type='BN', requires_grad=True)), + neck=None, + bbox_head=dict( + type='CornerHead', + num_classes=80, + in_channels=256, + num_feat_levels=2, + corner_emb_channels=1, + loss_heatmap=dict( + type='GaussianFocalLoss', alpha=2.0, gamma=4.0, loss_weight=1), + loss_embedding=dict( + type='AssociativeEmbeddingLoss', + pull_weight=0.10, + push_weight=0.10), + loss_offset=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1)), + # training and testing settings + train_cfg=None, + test_cfg=dict( + corner_topk=100, + local_maximum_kernel=3, + distance_threshold=0.5, + score_thr=0.05, + max_per_img=100, + nms=dict(type='soft_nms', iou_threshold=0.5, method='gaussian'))) + +# data settings +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PhotoMetricDistortion', + brightness_delta=32, + contrast_range=(0.5, 1.5), + saturation_range=(0.5, 1.5), + hue_delta=18), + dict( + # The cropped images are padded into squares during training, + # but may be smaller than crop_size. + type='RandomCenterCropPad', + crop_size=(511, 511), + ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3), + test_mode=False, + test_pad_mode=None, + mean=data_preprocessor['mean'], + std=data_preprocessor['std'], + # Image data is not converted to rgb. + to_rgb=data_preprocessor['bgr_to_rgb']), + # Make sure the output is always crop_size. + dict(type='Resize', scale=(511, 511), keep_ratio=False), + dict(type='RandomFlip', prob=0.5), + dict(type='PackDetInputs'), +] + +test_pipeline = [ + dict( + type='LoadImageFromFile', + to_float32=True, + backend_args=_base_.backend_args, + ), + # don't need Resize + dict( + type='RandomCenterCropPad', + crop_size=None, + ratios=None, + border=None, + test_mode=True, + test_pad_mode=['logical_or', 127], + mean=data_preprocessor['mean'], + std=data_preprocessor['std'], + # Image data is not converted to rgb. + to_rgb=data_preprocessor['bgr_to_rgb']), + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'border')) +] + +train_dataloader = dict( + batch_size=6, + num_workers=3, + batch_sampler=None, + dataset=dict(pipeline=train_pipeline)) +val_dataloader = dict(dataset=dict(pipeline=test_pipeline)) +test_dataloader = val_dataloader + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='Adam', lr=0.0005), + clip_grad=dict(max_norm=35, norm_type=2)) + +max_epochs = 210 + +# learning rate +param_scheduler = [ + dict( + type='LinearLR', + start_factor=1.0 / 3, + by_epoch=False, + begin=0, + end=500), + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[180], + gamma=0.1) +] + +train_cfg = dict( + type='EpochBasedTrainLoop', max_epochs=max_epochs, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (6 samples per GPU) +auto_scale_lr = dict(base_batch_size=48) + +tta_model = dict( + type='DetTTAModel', + tta_cfg=dict( + nms=dict(type='soft_nms', iou_threshold=0.5, method='gaussian'), + max_per_img=100)) + +tta_pipeline = [ + dict( + type='LoadImageFromFile', + to_float32=True, + backend_args=_base_.backend_args), + dict( + type='TestTimeAug', + transforms=[ + [ + # ``RandomFlip`` must be placed before ``RandomCenterCropPad``, + # otherwise bounding box coordinates after flipping cannot be + # recovered correctly. + dict(type='RandomFlip', prob=1.), + dict(type='RandomFlip', prob=0.) + ], + [ + dict( + type='RandomCenterCropPad', + crop_size=None, + ratios=None, + border=None, + test_mode=True, + test_pad_mode=['logical_or', 127], + mean=data_preprocessor['mean'], + std=data_preprocessor['std'], + # Image data is not converted to rgb. + to_rgb=data_preprocessor['bgr_to_rgb']) + ], + [dict(type='LoadAnnotations', with_bbox=True)], + [ + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'flip', 'flip_direction', 'border')) + ] + ]) +] diff --git a/grounding-dino/mmdetection/configs/cornernet/metafile.yml b/grounding-dino/mmdetection/configs/cornernet/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..f915cf37e8e157405a66431dfb21595db319b8b6 --- /dev/null +++ b/grounding-dino/mmdetection/configs/cornernet/metafile.yml @@ -0,0 +1,83 @@ +Collections: + - Name: CornerNet + Metadata: + Training Data: COCO + Training Techniques: + - Adam + Training Resources: 8x V100 GPUs + Architecture: + - Corner Pooling + - Stacked Hourglass Network + Paper: + URL: https://arxiv.org/abs/1808.01244 + Title: 'CornerNet: Detecting Objects as Paired Keypoints' + README: configs/cornernet/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.3.0/mmdet/models/detectors/cornernet.py#L9 + Version: v2.3.0 + +Models: + - Name: cornernet_hourglass104_10xb5-crop511-210e-mstest_coco + In Collection: CornerNet + Config: configs/cornernet/cornernet_hourglass104_10xb5-crop511-210e-mstest_coco.py + Metadata: + Training Resources: 10x V100 GPUs + Batch Size: 50 + Training Memory (GB): 13.9 + inference time (ms/im): + - value: 238.1 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 210 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.2 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_10x5_210e_coco/cornernet_hourglass104_mstest_10x5_210e_coco_20200824_185720-5fefbf1c.pth + + - Name: cornernet_hourglass104_8xb6-210e-mstest_coco + In Collection: CornerNet + Config: configs/cornernet/cornernet_hourglass104_8xb6-210e-mstest_coco.py + Metadata: + Batch Size: 48 + Training Memory (GB): 15.9 + inference time (ms/im): + - value: 238.1 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 210 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.2 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_8x6_210e_coco/cornernet_hourglass104_mstest_8x6_210e_coco_20200825_150618-79b44c30.pth + + - Name: cornernet_hourglass104_32xb3-210e-mstest_coco + In Collection: CornerNet + Config: configs/cornernet/cornernet_hourglass104_32xb3-210e-mstest_coco.py + Metadata: + Training Resources: 32x V100 GPUs + Batch Size: 96 + Training Memory (GB): 9.5 + inference time (ms/im): + - value: 256.41 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 210 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 40.4 + Weights: https://download.openmmlab.com/mmdetection/v2.0/cornernet/cornernet_hourglass104_mstest_32x3_210e_coco/cornernet_hourglass104_mstest_32x3_210e_coco_20200819_203110-1efaea91.pth diff --git a/grounding-dino/mmdetection/configs/crowddet/README.md b/grounding-dino/mmdetection/configs/crowddet/README.md new file mode 100644 index 0000000000000000000000000000000000000000..abc0f2d2dfac8fa64cab267c20f58c9113737d07 --- /dev/null +++ b/grounding-dino/mmdetection/configs/crowddet/README.md @@ -0,0 +1,37 @@ +# CrowdDet + +> [Detection in Crowded Scenes: One Proposal, Multiple Predictions](https://arxiv.org/abs/2003.09163) + + + +## Abstract + +We propose a simple yet effective proposal-based object detector, aiming at detecting highly-overlapped instances in crowded scenes. The key of our approach is to let each proposal predict a set of correlated instances rather than a single one in previous proposal-based frameworks. Equipped with new techniques such as EMD Loss and Set NMS, our detector can effectively handle the difficulty of detecting highly overlapped objects. On a FPN-Res50 baseline, our detector can obtain 4.9% AP gains on challenging CrowdHuman dataset and 1.0% MR^−2 improvements on CityPersons dataset, without bells and whistles. Moreover, on less crowed datasets like COCO, our approach can still achieve moderate improvement, suggesting the proposed method is robust to crowdedness. Code and pre-trained models will be released at https://github.com/megvii-model/CrowdDetection. + +
+ +
+ +## Results and Models + +| Backbone | RM | Style | Mem (GB) | Inf time (fps) | box AP | Config | Download | +| :------: | :---: | :-----: | :------: | :------------: | :----: | :-------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50-FPN | False | pytorch | 4.4 | - | 90.0 | [config](./crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman.py) | [model](https://download.openmmlab.com/mmdetection/v3.0/crowddet/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman_20221023_174954-dc319c2d.pth) \| [log](https://download.openmmlab.com/mmdetection/v3.0/crowddet/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman_20221023_174954.log.json) | +| R-50-FPN | True | pytorch | 4.8 | - | 90.32 | [config](./crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman.py) | [model](https://download.openmmlab.com/mmdetection/v3.0/crowddet/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman_20221024_215917-45602806.pth) \| [log](https://download.openmmlab.com/mmdetection/v3.0/crowddet/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman_20221024_215917.log.json) | + +Note: + +- RM indicates whether to use the refine module. +- The dataset for training and testing this model is `CrowdHuman`, and the metric of `box AP` is calculated by `mmdet/evaluation/metrics/crowdhuman_metric.py`. + +## Citation + +```latex +@inproceedings{Chu_2020_CVPR, + title={Detection in Crowded Scenes: One Proposal, Multiple Predictions}, + author={Chu, Xuangeng and Zheng, Anlin and Zhang, Xiangyu and Sun, Jian}, + booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, + month = {June}, + year = {2020} +} +``` diff --git a/grounding-dino/mmdetection/configs/crowddet/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman.py b/grounding-dino/mmdetection/configs/crowddet/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman.py new file mode 100644 index 0000000000000000000000000000000000000000..8815be77d49cf77afff6f888ee225e928e43b402 --- /dev/null +++ b/grounding-dino/mmdetection/configs/crowddet/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman.py @@ -0,0 +1,227 @@ +_base_ = ['../_base_/default_runtime.py'] + +model = dict( + type='CrowdDet', + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[103.53, 116.28, 123.675], + std=[57.375, 57.12, 58.395], + bgr_to_rgb=False, + pad_size_divisor=64, + # This option is set according to https://github.com/Purkialo/CrowdDet/ + # blob/master/lib/data/CrowdHuman.py The images in the entire batch are + # resize together. + batch_augments=[ + dict(type='BatchResize', scale=(1400, 800), pad_size_divisor=64) + ]), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + norm_eval=True, + style='pytorch', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict( + type='FPN', + in_channels=[256, 512, 1024, 2048], + out_channels=256, + num_outs=5, + upsample_cfg=dict(mode='bilinear', align_corners=False)), + rpn_head=dict( + type='RPNHead', + in_channels=256, + feat_channels=256, + anchor_generator=dict( + type='AnchorGenerator', + scales=[8], + ratios=[1.0, 2.0, 3.0], + strides=[4, 8, 16, 32, 64], + centers=[(8, 8), (8, 8), (8, 8), (8, 8), (8, 8)]), + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0.0, 0.0, 0.0, 0.0], + target_stds=[1.0, 1.0, 1.0, 1.0], + clip_border=False), + loss_cls=dict(type='CrossEntropyLoss', loss_weight=1.0), + loss_bbox=dict(type='L1Loss', loss_weight=1.0)), + roi_head=dict( + type='MultiInstanceRoIHead', + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + type='RoIAlign', + output_size=7, + sampling_ratio=-1, + aligned=True, + use_torchvision=True), + out_channels=256, + featmap_strides=[4, 8, 16, 32]), + bbox_head=dict( + type='MultiInstanceBBoxHead', + with_refine=False, + num_shared_fcs=2, + in_channels=256, + fc_out_channels=1024, + roi_feat_size=7, + num_classes=1, + bbox_coder=dict( + type='DeltaXYWHBBoxCoder', + target_means=[0., 0., 0., 0.], + target_stds=[0.1, 0.1, 0.2, 0.2]), + reg_class_agnostic=False, + loss_cls=dict( + type='CrossEntropyLoss', + loss_weight=1.0, + use_sigmoid=False, + reduction='none'), + loss_bbox=dict( + type='SmoothL1Loss', loss_weight=1.0, reduction='none'))), + # model training and testing settings + train_cfg=dict( + rpn=dict( + assigner=dict( + type='MaxIoUAssigner', + pos_iou_thr=0.7, + neg_iou_thr=(0.3, 0.7), + min_pos_iou=0.3, + match_low_quality=True, + ignore_iof_thr=-1), + sampler=dict( + type='RandomSampler', + num=256, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + allowed_border=-1, + pos_weight=-1, + debug=False), + rpn_proposal=dict( + nms_pre=2400, + max_per_img=2000, + nms=dict(type='nms', iou_threshold=0.7), + min_bbox_size=2), + rcnn=dict( + assigner=dict( + type='MultiInstanceAssigner', + pos_iou_thr=0.5, + neg_iou_thr=0.5, + min_pos_iou=0.3, + match_low_quality=False, + ignore_iof_thr=-1), + sampler=dict( + type='MultiInsRandomSampler', + num=512, + pos_fraction=0.5, + neg_pos_ub=-1, + add_gt_as_proposals=False), + pos_weight=-1, + debug=False)), + test_cfg=dict( + rpn=dict( + nms_pre=1200, + max_per_img=1000, + nms=dict(type='nms', iou_threshold=0.7), + min_bbox_size=2), + rcnn=dict( + nms=dict(type='nms', iou_threshold=0.5), + score_thr=0.01, + max_per_img=500))) + +dataset_type = 'CrowdHumanDataset' +data_root = 'data/CrowdHuman/' + +# Example to use different file client +# Method 1: simply set the data root and let the file I/O module +# automatically infer from prefix (not support LMDB and Memcache yet) + +# data_root = 's3://openmmlab/datasets/tracking/CrowdHuman/' + +# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6 +# backend_args = dict( +# backend='petrel', +# path_mapping=dict({ +# './data/': 's3://openmmlab/datasets/tracking/', +# 'data/': 's3://openmmlab/datasets/tracking/' +# })) +backend_args = None + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'flip', + 'flip_direction')) +] +test_pipeline = [ + dict(type='LoadImageFromFile', backend_args=backend_args), + dict(type='Resize', scale=(1400, 800), keep_ratio=True), + # avoid bboxes being resized + dict(type='LoadAnnotations', with_bbox=True), + dict( + type='PackDetInputs', + meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', + 'scale_factor')) +] + +train_dataloader = dict( + batch_size=2, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=True), + batch_sampler=None, # The 'batch_sampler' may decrease the precision + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotation_train.odgt', + data_prefix=dict(img='Images/'), + filter_cfg=dict(filter_empty_gt=True, min_size=32), + pipeline=train_pipeline, + backend_args=backend_args)) +val_dataloader = dict( + batch_size=1, + num_workers=2, + persistent_workers=True, + drop_last=False, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + ann_file='annotation_val.odgt', + data_prefix=dict(img='Images/'), + test_mode=True, + pipeline=test_pipeline, + backend_args=backend_args)) +test_dataloader = val_dataloader + +val_evaluator = dict( + type='CrowdHumanMetric', + ann_file=data_root + 'annotation_val.odgt', + metric=['AP', 'MR', 'JI'], + backend_args=backend_args) +test_evaluator = val_evaluator + +train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=30, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') +param_scheduler = [ + dict( + type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=800), + dict( + type='MultiStepLR', + begin=0, + end=30, + by_epoch=True, + milestones=[24, 27], + gamma=0.1) +] + +# optimizer +auto_scale_lr = dict(base_batch_size=16) +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='SGD', lr=0.002, momentum=0.9, weight_decay=0.0001)) diff --git a/grounding-dino/mmdetection/configs/crowddet/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman.py b/grounding-dino/mmdetection/configs/crowddet/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman.py new file mode 100644 index 0000000000000000000000000000000000000000..80277ce1c1436c37c4e2a4d13293d0ecb8ba4722 --- /dev/null +++ b/grounding-dino/mmdetection/configs/crowddet/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman.py @@ -0,0 +1,3 @@ +_base_ = './crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman.py' + +model = dict(roi_head=dict(bbox_head=dict(with_refine=True))) diff --git a/grounding-dino/mmdetection/configs/crowddet/metafile.yml b/grounding-dino/mmdetection/configs/crowddet/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..4f191dea9cc599f64091434152000e67289f9180 --- /dev/null +++ b/grounding-dino/mmdetection/configs/crowddet/metafile.yml @@ -0,0 +1,47 @@ +Collections: + - Name: CrowdDet + Metadata: + Training Data: CrowdHuman + Training Techniques: + - SGD + - EMD Loss + Training Resources: 8x A100 GPUs + Architecture: + - FPN + - RPN + - ResNet + - RoIPool + Paper: + URL: https://arxiv.org/abs/2003.09163 + Title: 'Detection in Crowded Scenes: One Proposal, Multiple Predictions' + README: configs/crowddet/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v3.0.0rc3/mmdet/models/detectors/crowddet.py + Version: v3.0.0rc3 + +Models: + - Name: crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman + In Collection: CrowdDet + Config: configs/crowddet/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman.py + Metadata: + Training Memory (GB): 4.8 + Epochs: 30 + Results: + - Task: Object Detection + Dataset: CrowdHuman + Metrics: + box AP: 90.32 + Weights: https://download.openmmlab.com/mmdetection/v3.0/crowddet/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman/crowddet-rcnn_refine_r50_fpn_8xb2-30e_crowdhuman_20221024_215917-45602806.pth + + - Name: crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman + In Collection: CrowdDet + Config: configs/crowddet/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman.py + Metadata: + Training Memory (GB): 4.4 + Epochs: 30 + Results: + - Task: Object Detection + Dataset: CrowdHuman + Metrics: + box AP: 90.0 + Weights: https://download.openmmlab.com/mmdetection/v3.0/crowddet/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman/crowddet-rcnn_r50_fpn_8xb2-30e_crowdhuman_20221023_174954-dc319c2d.pth diff --git a/grounding-dino/mmdetection/configs/dab_detr/README.md b/grounding-dino/mmdetection/configs/dab_detr/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5661f27a30268a9a50a956e51e948c36c9287356 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dab_detr/README.md @@ -0,0 +1,40 @@ +# DAB-DETR + +> [DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR](https://arxiv.org/abs/2201.12329) + + + +## Abstract + +We present in this paper a novel query formulation using dynamic anchor boxes for DETR (DEtection TRansformer) and offer a deeper understanding of the role of queries in DETR. This new formulation directly uses box coordinates as queries in Transformer decoders and dynamically updates them layer-by-layer. Using box coordinates not only helps using explicit positional priors to improve the query-to-feature similarity and eliminate the slow training convergence issue in DETR, but also allows us to modulate the positional attention map using the box width and height information. Such a design makes it clear that queries in DETR can be implemented as performing soft ROI pooling layer-by-layer in a cascade manner. As a result, it leads to the best performance on MS-COCO benchmark among the DETR-like detection models under the same setting, e.g., AP 45.7% using ResNet50-DC5 as backbone trained in 50 epochs. We also conducted extensive experiments to confirm our analysis and verify the effectiveness of our methods. + +
+ +
+
+ +
+
+ +
+ +## Results and Models + +We provide the config files and models for DAB-DETR: [DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR](https://arxiv.org/abs/2201.12329). + +| Backbone | Model | Lr schd | Mem (GB) | Inf time (fps) | box AP | Config | Download | +| :------: | :------: | :-----: | :------: | :------------: | :----: | :---------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50 | DAB-DETR | 50e | | | 42.3 | [config](./dab-detr_r50_8xb2-50e_coco.py) | [model](https://download.openmmlab.com/mmdetection/v3.0/dab_detr/dab-detr_r50_8xb2-50e_coco/dab-detr_r50_8xb2-50e_coco_20221122_120837-c1035c8c.pth) \| [log](https://download.openmmlab.com/mmdetection/v3.0/dab_detr/dab-detr_r50_8xb2-50e_coco/dab-detr_r50_8xb2-50e_coco_20221122_120837.log.json) | + +## Citation + +```latex +@inproceedings{ + liu2022dabdetr, + title={{DAB}-{DETR}: Dynamic Anchor Boxes are Better Queries for {DETR}}, + author={Shilong Liu and Feng Li and Hao Zhang and Xiao Yang and Xianbiao Qi and Hang Su and Jun Zhu and Lei Zhang}, + booktitle={International Conference on Learning Representations}, + year={2022}, + url={https://openreview.net/forum?id=oMI9PjOb9Jl} +} +``` diff --git a/grounding-dino/mmdetection/configs/dab_detr/dab-detr_r50_8xb2-50e_coco.py b/grounding-dino/mmdetection/configs/dab_detr/dab-detr_r50_8xb2-50e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..314ed97e2d80ae3c95119abf9166f95d416c010e --- /dev/null +++ b/grounding-dino/mmdetection/configs/dab_detr/dab-detr_r50_8xb2-50e_coco.py @@ -0,0 +1,159 @@ +_base_ = [ + '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py' +] +model = dict( + type='DABDETR', + num_queries=300, + with_random_refpoints=False, + num_patterns=0, + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_size_divisor=1), + backbone=dict( + type='ResNet', + depth=50, + num_stages=4, + out_indices=(3, ), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=False), + norm_eval=True, + style='pytorch', + init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')), + neck=dict( + type='ChannelMapper', + in_channels=[2048], + kernel_size=1, + out_channels=256, + act_cfg=None, + norm_cfg=None, + num_outs=1), + encoder=dict( + num_layers=6, + layer_cfg=dict( + self_attn_cfg=dict( + embed_dims=256, num_heads=8, dropout=0., batch_first=True), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + ffn_drop=0., + act_cfg=dict(type='PReLU')))), + decoder=dict( + num_layers=6, + query_dim=4, + query_scale_type='cond_elewise', + with_modulated_hw_attn=True, + layer_cfg=dict( + self_attn_cfg=dict( + embed_dims=256, + num_heads=8, + attn_drop=0., + proj_drop=0., + cross_attn=False), + cross_attn_cfg=dict( + embed_dims=256, + num_heads=8, + attn_drop=0., + proj_drop=0., + cross_attn=True), + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, + num_fcs=2, + ffn_drop=0., + act_cfg=dict(type='PReLU'))), + return_intermediate=True), + positional_encoding=dict(num_feats=128, temperature=20, normalize=True), + bbox_head=dict( + type='DABDETRHead', + num_classes=80, + embed_dims=256, + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='L1Loss', loss_weight=5.0), + loss_iou=dict(type='GIoULoss', loss_weight=2.0)), + # training and testing settings + train_cfg=dict( + assigner=dict( + type='HungarianAssigner', + match_costs=[ + dict(type='FocalLossCost', weight=2., eps=1e-8), + dict(type='BBoxL1Cost', weight=5.0, box_format='xywh'), + dict(type='IoUCost', iou_mode='giou', weight=2.0) + ])), + test_cfg=dict(max_per_img=300)) + +# train_pipeline, NOTE the img_scale and the Pad's size_divisor is different +# from the default setting in mmdet. +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomChoice', + transforms=[[ + dict( + type='RandomChoiceResize', + scales=[(480, 1333), (512, 1333), (544, 1333), (576, 1333), + (608, 1333), (640, 1333), (672, 1333), (704, 1333), + (736, 1333), (768, 1333), (800, 1333)], + keep_ratio=True) + ], + [ + dict( + type='RandomChoiceResize', + scales=[(400, 1333), (500, 1333), (600, 1333)], + keep_ratio=True), + dict( + type='RandomCrop', + crop_type='absolute_range', + crop_size=(384, 600), + allow_negative_crop=True), + dict( + type='RandomChoiceResize', + scales=[(480, 1333), (512, 1333), (544, 1333), + (576, 1333), (608, 1333), (640, 1333), + (672, 1333), (704, 1333), (736, 1333), + (768, 1333), (800, 1333)], + keep_ratio=True) + ]]), + dict(type='PackDetInputs') +] +train_dataloader = dict(dataset=dict(pipeline=train_pipeline)) + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='AdamW', lr=0.0001, weight_decay=0.0001), + clip_grad=dict(max_norm=0.1, norm_type=2), + paramwise_cfg=dict( + custom_keys={'backbone': dict(lr_mult=0.1, decay_mult=1.0)})) + +# learning policy +max_epochs = 50 +train_cfg = dict( + type='EpochBasedTrainLoop', max_epochs=max_epochs, val_interval=1) +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +param_scheduler = [ + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[40], + gamma=0.1) +] + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (2 samples per GPU) +auto_scale_lr = dict(base_batch_size=16, enable=False) diff --git a/grounding-dino/mmdetection/configs/dab_detr/metafile.yml b/grounding-dino/mmdetection/configs/dab_detr/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..94383a0493b86a730181f78ab2f0e94a2ab2de73 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dab_detr/metafile.yml @@ -0,0 +1,32 @@ +Collections: + - Name: DAB-DETR + Metadata: + Training Data: COCO + Training Techniques: + - AdamW + - Multi Scale Train + - Gradient Clip + Training Resources: 8x A100 GPUs + Architecture: + - ResNet + - Transformer + Paper: + URL: https://arxiv.org/abs/2201.12329 + Title: 'DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR' + README: configs/dab_detr/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/f4112c9e5611468ffbd57cfba548fd1289264b52/mmdet/models/detectors/dab_detr.py#L15 + Version: v3.0.0rc6 + +Models: + - Name: dab-detr_r50_8xb2-50e_coco + In Collection: DAB-DETR + Config: configs/dab_detr/dab-detr_r50_8xb2-50e_coco.py + Metadata: + Epochs: 50 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 42.3 + Weights: https://download.openmmlab.com/mmdetection/v3.0/dab_detr/dab-detr_r50_8xb2-50e_coco/dab-detr_r50_8xb2-50e_coco_20221122_120837-c1035c8c.pth diff --git a/grounding-dino/mmdetection/configs/dcn/README.md b/grounding-dino/mmdetection/configs/dcn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e287e1d5ef99e68dd2d7f2fccbacddde7428522e --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/README.md @@ -0,0 +1,48 @@ +# DCN + +> [Deformable Convolutional Networks](https://arxiv.org/abs/1703.06211) + + + +## Abstract + +Convolutional neural networks (CNNs) are inherently limited to model geometric transformations due to the fixed geometric structures in its building modules. In this work, we introduce two new modules to enhance the transformation modeling capacity of CNNs, namely, deformable convolution and deformable RoI pooling. Both are based on the idea of augmenting the spatial sampling locations in the modules with additional offsets and learning the offsets from target tasks, without additional supervision. The new modules can readily replace their plain counterparts in existing CNNs and can be easily trained end-to-end by standard back-propagation, giving rise to deformable convolutional networks. Extensive experiments validate the effectiveness of our approach on sophisticated vision tasks of object detection and semantic segmentation. + +
+ +
+ +## Results and Models + +| Backbone | Model | Style | Conv | Pool | Lr schd | Mem (GB) | Inf time (fps) | box AP | mask AP | Config | Download | +| :-------------: | :----------: | :-----: | :----------: | :---: | :-----: | :------: | :------------: | :----: | :-----: | :-----------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50-FPN | Faster | pytorch | dconv(c3-c5) | - | 1x | 4.0 | 17.8 | 41.3 | | [config](./faster-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco/faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200130-d68aed1e.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco/faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200130_212941.log.json) | +| R-50-FPN | Faster | pytorch | - | dpool | 1x | 5.0 | 17.2 | 38.9 | | [config](./faster-rcnn_r50_fpn_dpool_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_dpool_1x_coco/faster_rcnn_r50_fpn_dpool_1x_coco_20200307-90d3c01d.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_dpool_1x_coco/faster_rcnn_r50_fpn_dpool_1x_coco_20200307_203250.log.json) | +| R-101-FPN | Faster | pytorch | dconv(c3-c5) | - | 1x | 6.0 | 12.5 | 42.7 | | [config](./faster-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r101_fpn_dconv_c3-c5_1x_coco/faster_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200203-1377f13d.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r101_fpn_dconv_c3-c5_1x_coco/faster_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200203_230019.log.json) | +| X-101-32x4d-FPN | Faster | pytorch | dconv(c3-c5) | - | 1x | 7.3 | 10.0 | 44.5 | | [config](./faster-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco/faster_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco_20200203-4f85c69c.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco/faster_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco_20200203_001325.log.json) | +| R-50-FPN | Mask | pytorch | dconv(c3-c5) | - | 1x | 4.5 | 15.4 | 41.8 | 37.4 | [config](./mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200203-4d9ad43b.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200203_061339.log.json) | +| R-101-FPN | Mask | pytorch | dconv(c3-c5) | - | 1x | 6.5 | 11.7 | 43.5 | 38.9 | [config](./mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco/mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200216-a71f5bce.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco/mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200216_191601.log.json) | +| R-50-FPN | Cascade | pytorch | dconv(c3-c5) | - | 1x | 4.5 | 14.6 | 43.8 | | [config](./cascade-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_rcnn_r50_fpn_dconv_c3-c5_1x_coco/cascade_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200130-2f1fca44.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_rcnn_r50_fpn_dconv_c3-c5_1x_coco/cascade_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200130_220843.log.json) | +| R-101-FPN | Cascade | pytorch | dconv(c3-c5) | - | 1x | 6.4 | 11.0 | 45.0 | | [config](./cascade-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_rcnn_r101_fpn_dconv_c3-c5_1x_coco/cascade_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200203-3b2f0594.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_rcnn_r101_fpn_dconv_c3-c5_1x_coco/cascade_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200203_224829.log.json) | +| R-50-FPN | Cascade Mask | pytorch | dconv(c3-c5) | - | 1x | 6.0 | 10.0 | 44.4 | 38.6 | [config](./cascade-mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200202-42e767a2.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200202_010309.log.json) | +| R-101-FPN | Cascade Mask | pytorch | dconv(c3-c5) | - | 1x | 8.0 | 8.6 | 45.8 | 39.7 | [config](./cascade-mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200204-df0c5f10.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200204_134006.log.json) | +| X-101-32x4d-FPN | Cascade Mask | pytorch | dconv(c3-c5) | - | 1x | 9.2 | | 47.3 | 41.1 | [config](./cascade-mask-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco-e75f90c8.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco-20200606_183737.log.json) | +| R-50-FPN (FP16) | Mask | pytorch | dconv(c3-c5) | - | 1x | 3.0 | | 41.9 | 37.5 | [config](./mask-rcnn_r50-dconv-c3-c5_fpn_amp-1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/fp16/mask_rcnn_r50_fpn_fp16_dconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_fp16_dconv_c3-c5_1x_coco_20210520_180247-c06429d2.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/fp16/mask_rcnn_r50_fpn_fp16_dconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_fp16_dconv_c3-c5_1x_coco_20210520_180247.log.json) | + +**Notes:** + +- `dconv` denotes deformable convolution, `c3-c5` means adding dconv in resnet stage 3 to 5. `dpool` denotes deformable roi pooling. +- The dcn ops are modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch, which should be more memory efficient and slightly faster. +- (\*) For R-50-FPN (dg=4), dg is short for deformable_group. This model is trained and tested on Amazon EC2 p3dn.24xlarge instance. +- **Memory, Train/Inf time is outdated.** + +## Citation + +```latex +@inproceedings{dai2017deformable, + title={Deformable Convolutional Networks}, + author={Dai, Jifeng and Qi, Haozhi and Xiong, Yuwen and Li, Yi and Zhang, Guodong and Hu, Han and Wei, Yichen}, + booktitle={Proceedings of the IEEE international conference on computer vision}, + year={2017} +} +``` diff --git a/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..8c0ff9890e82bd0c1ee4e445e37d2c7afa534161 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../cascade_rcnn/cascade-mask-rcnn_r101_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..cfcc5e73cc508e11d77c5a3557f30632b545b803 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../cascade_rcnn/cascade-mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..48b25f62125da09368c446bcd6ccff9b0219a7cc --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/cascade-mask-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../cascade_rcnn/cascade-mask-rcnn_x101-32x4d_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/cascade-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/cascade-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..8a942da754119b8d913f807907322a3d96c83ff8 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/cascade-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../cascade_rcnn/cascade-rcnn_r101_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/cascade-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/cascade-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..f6bf5b7998a972f41b52f90955ef52977adfd68c --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/cascade-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..db44e7e87b2d11555140ab2c8a19f32e1ce65770 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../faster_rcnn/faster-rcnn_r101_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..95f20467af60167a4a61f253e4354dadd832ccc7 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r50_fpn_dpool_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r50_fpn_dpool_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..c65ce5fd0267dc892455da6495cd3be9f1f99fcf --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/faster-rcnn_r50_fpn_dpool_1x_coco.py @@ -0,0 +1,12 @@ +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + roi_head=dict( + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + _delete_=True, + type='DeformRoIPoolPack', + output_size=7, + output_channels=256), + out_channels=256, + featmap_strides=[4, 8, 16, 32]))) diff --git a/grounding-dino/mmdetection/configs/dcn/faster-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/faster-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ed832f5e7ff0d050be33e57d2fa611e9ae7e8e --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/faster-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,16 @@ +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + type='ResNeXt', + depth=101, + groups=32, + base_width=4, + num_stages=4, + out_indices=(0, 1, 2, 3), + frozen_stages=1, + norm_cfg=dict(type='BN', requires_grad=True), + style='pytorch', + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True), + init_cfg=dict( + type='Pretrained', checkpoint='open-mmlab://resnext101_32x4d'))) diff --git a/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..3f36714a5301823ca401820ab9d926374428ee70 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../mask_rcnn/mask-rcnn_r101_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..0b281d417b4f6a7320201da261e5fdf6950556a1 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r50-dconv-c3-c5_fpn_amp-1x_coco.py b/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r50-dconv-c3-c5_fpn_amp-1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..9d01594314aad74bc47d7331c42a39f2ca453071 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/mask-rcnn_r50-dconv-c3-c5_fpn_amp-1x_coco.py @@ -0,0 +1,10 @@ +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) + +# MMEngine support the following two ways, users can choose +# according to convenience +# optim_wrapper = dict(type='AmpOptimWrapper') +_base_.optim_wrapper.type = 'AmpOptimWrapper' diff --git a/grounding-dino/mmdetection/configs/dcn/metafile.yml b/grounding-dino/mmdetection/configs/dcn/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..4aa35b5d95f7f531cc2bdb8a03553ae197cfe727 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcn/metafile.yml @@ -0,0 +1,272 @@ +Collections: + - Name: Deformable Convolutional Networks + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - Deformable Convolution + Paper: + URL: https://arxiv.org/abs/1703.06211 + Title: "Deformable Convolutional Networks" + README: configs/dcn/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.0.0/mmdet/ops/dcn/deform_conv.py#L15 + Version: v2.0.0 + +Models: + - Name: faster-rcnn_r50_fpn_dconv_c3-c5_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/faster-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.0 + inference time (ms/im): + - value: 56.18 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.3 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco/faster_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200130-d68aed1e.pth + + - Name: faster-rcnn_r50_fpn_dpool_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/faster-rcnn_r50_fpn_dpool_1x_coco.py + Metadata: + Training Memory (GB): 5.0 + inference time (ms/im): + - value: 58.14 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 38.9 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_dpool_1x_coco/faster_rcnn_r50_fpn_dpool_1x_coco_20200307-90d3c01d.pth + + - Name: faster-rcnn_r101-dconv-c3-c5_fpn_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/faster-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 6.0 + inference time (ms/im): + - value: 80 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 42.7 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r101_fpn_dconv_c3-c5_1x_coco/faster_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200203-1377f13d.pth + + - Name: faster-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/faster-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 7.3 + inference time (ms/im): + - value: 100 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 44.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco/faster_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco_20200203-4f85c69c.pth + + - Name: mask-rcnn_r50_fpn_dconv_c3-c5_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.5 + inference time (ms/im): + - value: 64.94 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.8 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 37.4 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200203-4d9ad43b.pth + + - Name: mask-rcnn_r50_fpn_fp16_dconv_c3-c5_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/mask-rcnn_r50-dconv-c3-c5_fpn_amp-1x_coco.py + Metadata: + Training Techniques: + - SGD with Momentum + - Weight Decay + - Mixed Precision Training + Training Memory (GB): 3.0 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.9 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 37.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/fp16/mask_rcnn_r50_fpn_fp16_dconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_fp16_dconv_c3-c5_1x_coco_20210520_180247-c06429d2.pth + + - Name: mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 6.5 + inference time (ms/im): + - value: 85.47 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 43.5 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 38.9 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco/mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200216-a71f5bce.pth + + - Name: cascade-rcnn_r50_fpn_dconv_c3-c5_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/cascade-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.5 + inference time (ms/im): + - value: 68.49 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 43.8 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_rcnn_r50_fpn_dconv_c3-c5_1x_coco/cascade_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200130-2f1fca44.pth + + - Name: cascade-rcnn_r101-dconv-c3-c5_fpn_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/cascade-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 6.4 + inference time (ms/im): + - value: 90.91 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 45.0 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_rcnn_r101_fpn_dconv_c3-c5_1x_coco/cascade_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200203-3b2f0594.pth + + - Name: cascade-mask-rcnn_r50_fpn_dconv_c3-c5_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/cascade-mask-rcnn_r50-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 6.0 + inference time (ms/im): + - value: 100 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 44.4 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 38.6 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_r50_fpn_dconv_c3-c5_1x_coco_20200202-42e767a2.pth + + - Name: cascade-mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/cascade-mask-rcnn_r101-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 8.0 + inference time (ms/im): + - value: 116.28 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 45.8 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 39.7 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_r101_fpn_dconv_c3-c5_1x_coco_20200204-df0c5f10.pth + + - Name: cascade-mask-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco + In Collection: Deformable Convolutional Networks + Config: configs/dcn/cascade-mask-rcnn_x101-32x4d-dconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 9.2 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 47.3 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 41.1 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/cascade_mask_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco/cascade_mask_rcnn_x101_32x4d_fpn_dconv_c3-c5_1x_coco-e75f90c8.pth diff --git a/grounding-dino/mmdetection/configs/dcnv2/README.md b/grounding-dino/mmdetection/configs/dcnv2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7f42c93401f836350c7b30cf5af9b4caa7ea75c7 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcnv2/README.md @@ -0,0 +1,37 @@ +# DCNv2 + +> [Deformable ConvNets v2: More Deformable, Better Results](https://arxiv.org/abs/1811.11168) + + + +## Abstract + +The superior performance of Deformable Convolutional Networks arises from its ability to adapt to the geometric variations of objects. Through an examination of its adaptive behavior, we observe that while the spatial support for its neural features conforms more closely than regular ConvNets to object structure, this support may nevertheless extend well beyond the region of interest, causing features to be influenced by irrelevant image content. To address this problem, we present a reformulation of Deformable ConvNets that improves its ability to focus on pertinent image regions, through increased modeling power and stronger training. The modeling power is enhanced through a more comprehensive integration of deformable convolution within the network, and by introducing a modulation mechanism that expands the scope of deformation modeling. To effectively harness this enriched modeling capability, we guide network training via a proposed feature mimicking scheme that helps the network to learn features that reflect the object focus and classification power of RCNN features. With the proposed contributions, this new version of Deformable ConvNets yields significant performance gains over the original model and produces leading results on the COCO benchmark for object detection and instance segmentation. + +## Results and Models + +| Backbone | Model | Style | Conv | Pool | Lr schd | Mem (GB) | Inf time (fps) | box AP | mask AP | Config | Download | +| :---------------: | :----: | :-----: | :-----------: | :----: | :-----: | :------: | :------------: | :----: | :-----: | :------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| R-50-FPN | Faster | pytorch | mdconv(c3-c5) | - | 1x | 4.1 | 17.6 | 41.4 | | [config](./faster-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdconv_c3-c5_1x_coco/faster_rcnn_r50_fpn_mdconv_c3-c5_1x_coco_20200130-d099253b.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdconv_c3-c5_1x_coco/faster_rcnn_r50_fpn_mdconv_c3-c5_1x_coco_20200130_222144.log.json) | +| \*R-50-FPN (dg=4) | Faster | pytorch | mdconv(c3-c5) | - | 1x | 4.2 | 17.4 | 41.5 | | [config](./faster-rcnn_r50-mdconv-group4-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdconv_c3-c5_group4_1x_coco/faster_rcnn_r50_fpn_mdconv_c3-c5_group4_1x_coco_20200130-01262257.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdconv_c3-c5_group4_1x_coco/faster_rcnn_r50_fpn_mdconv_c3-c5_group4_1x_coco_20200130_222058.log.json) | +| R-50-FPN | Faster | pytorch | - | mdpool | 1x | 5.8 | 16.6 | 38.7 | | [config](./faster-rcnn_r50_fpn_mdpool_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdpool_1x_coco/faster_rcnn_r50_fpn_mdpool_1x_coco_20200307-c0df27ff.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdpool_1x_coco/faster_rcnn_r50_fpn_mdpool_1x_coco_20200307_203304.log.json) | +| R-50-FPN | Mask | pytorch | mdconv(c3-c5) | - | 1x | 4.5 | 15.1 | 41.5 | 37.1 | [config](./mask-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r50_fpn_mdconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_mdconv_c3-c5_1x_coco_20200203-ad97591f.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r50_fpn_mdconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_mdconv_c3-c5_1x_coco_20200203_063443.log.json) | +| R-50-FPN (FP16) | Mask | pytorch | mdconv(c3-c5) | - | 1x | 3.1 | | 42.0 | 37.6 | [config](./mask-rcnn_r50-mdconv-c3-c5_fpn_amp-1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/fp16/mask_rcnn_r50_fpn_fp16_mdconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_fp16_mdconv_c3-c5_1x_coco_20210520_180434-cf8fefa5.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/fp16/mask_rcnn_r50_fpn_fp16_mdconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_fp16_mdconv_c3-c5_1x_coco_20210520_180434.log.json) | + +**Notes:** + +- `mdconv` denotes modulated deformable convolution, `c3-c5` means adding dconv in resnet stage 3 to 5. `mdpool` denotes modulated deformable roi pooling. +- The dcn ops are modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch, which should be more memory efficient and slightly faster. +- (\*) For R-50-FPN (dg=4), dg is short for deformable_group. This model is trained and tested on Amazon EC2 p3dn.24xlarge instance. +- **Memory, Train/Inf time is outdated.** + +## Citation + +```latex +@article{zhu2018deformable, + title={Deformable ConvNets v2: More Deformable, Better Results}, + author={Zhu, Xizhou and Hu, Han and Lin, Stephen and Dai, Jifeng}, + journal={arXiv preprint arXiv:1811.11168}, + year={2018} +} +``` diff --git a/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f7e4eecaf74418690975d54d09eeb0e31f9a1f --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50-mdconv-group4-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50-mdconv-group4-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..5c58dbed3782403a5fac3c6809598372e47cd72c --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50-mdconv-group4-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCNv2', deform_groups=4, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50_fpn_mdpool_1x_coco.py b/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50_fpn_mdpool_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..6198d6d7d72f8d012c777330f1116b46b89290be --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcnv2/faster-rcnn_r50_fpn_mdpool_1x_coco.py @@ -0,0 +1,12 @@ +_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py' +model = dict( + roi_head=dict( + bbox_roi_extractor=dict( + type='SingleRoIExtractor', + roi_layer=dict( + _delete_=True, + type='ModulatedDeformRoIPoolPack', + output_size=7, + output_channels=256), + out_channels=256, + featmap_strides=[4, 8, 16, 32]))) diff --git a/grounding-dino/mmdetection/configs/dcnv2/mask-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py b/grounding-dino/mmdetection/configs/dcnv2/mask-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a90bbf31bea3663820caa4541de3ceafeb7366 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcnv2/mask-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py @@ -0,0 +1,5 @@ +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) diff --git a/grounding-dino/mmdetection/configs/dcnv2/mask-rcnn_r50-mdconv-c3-c5_fpn_amp-1x_coco.py b/grounding-dino/mmdetection/configs/dcnv2/mask-rcnn_r50-mdconv-c3-c5_fpn_amp-1x_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3894c2d61ee3208170235ba1aa98def79a7120 --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcnv2/mask-rcnn_r50-mdconv-c3-c5_fpn_amp-1x_coco.py @@ -0,0 +1,10 @@ +_base_ = '../mask_rcnn/mask-rcnn_r50_fpn_1x_coco.py' +model = dict( + backbone=dict( + dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), + stage_with_dcn=(False, True, True, True))) + +# MMEngine support the following two ways, users can choose +# according to convenience +# optim_wrapper = dict(type='AmpOptimWrapper') +_base_.optim_wrapper.type = 'AmpOptimWrapper' diff --git a/grounding-dino/mmdetection/configs/dcnv2/metafile.yml b/grounding-dino/mmdetection/configs/dcnv2/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..dea7bfa1b531410f3c81693d7012a835781a63ca --- /dev/null +++ b/grounding-dino/mmdetection/configs/dcnv2/metafile.yml @@ -0,0 +1,123 @@ +Collections: + - Name: Deformable Convolutional Networks v2 + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - Deformable Convolution + Paper: + URL: https://arxiv.org/abs/1811.11168 + Title: "Deformable ConvNets v2: More Deformable, Better Results" + README: configs/dcnv2/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.0.0/mmdet/ops/dcn/deform_conv.py#L15 + Version: v2.0.0 + +Models: + - Name: faster-rcnn_r50_fpn_mdconv_c3-c5_1x_coco + In Collection: Deformable Convolutional Networks v2 + Config: configs/dcnv2/faster-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.1 + inference time (ms/im): + - value: 56.82 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.4 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdconv_c3-c5_1x_coco/faster_rcnn_r50_fpn_mdconv_c3-c5_1x_coco_20200130-d099253b.pth + + - Name: faster-rcnn_r50_fpn_mdconv_c3-c5_group4_1x_coco + In Collection: Deformable Convolutional Networks v2 + Config: configs/dcnv2/faster-rcnn_r50-mdconv-group4-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.2 + inference time (ms/im): + - value: 57.47 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.5 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdconv_c3-c5_group4_1x_coco/faster_rcnn_r50_fpn_mdconv_c3-c5_group4_1x_coco_20200130-01262257.pth + + - Name: faster-rcnn_r50_fpn_mdpool_1x_coco + In Collection: Deformable Convolutional Networks v2 + Config: configs/dcnv2/faster-rcnn_r50_fpn_mdpool_1x_coco.py + Metadata: + Training Memory (GB): 5.8 + inference time (ms/im): + - value: 60.24 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 38.7 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/faster_rcnn_r50_fpn_mdpool_1x_coco/faster_rcnn_r50_fpn_mdpool_1x_coco_20200307-c0df27ff.pth + + - Name: mask-rcnn_r50_fpn_mdconv_c3-c5_1x_coco + In Collection: Deformable Convolutional Networks v2 + Config: configs/dcnv2/mask-rcnn_r50-mdconv-c3-c5_fpn_1x_coco.py + Metadata: + Training Memory (GB): 4.5 + inference time (ms/im): + - value: 66.23 + hardware: V100 + backend: PyTorch + batch size: 1 + mode: FP32 + resolution: (800, 1333) + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.5 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 37.1 + Weights: https://download.openmmlab.com/mmdetection/v2.0/dcn/mask_rcnn_r50_fpn_mdconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_mdconv_c3-c5_1x_coco_20200203-ad97591f.pth + + - Name: mask-rcnn_r50_fpn_fp16_mdconv_c3-c5_1x_coco + In Collection: Deformable Convolutional Networks v2 + Config: configs/dcnv2/mask-rcnn_r50-mdconv-c3-c5_fpn_amp-1x_coco.py + Metadata: + Training Memory (GB): 3.1 + Training Techniques: + - SGD with Momentum + - Weight Decay + - Mixed Precision Training + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 42.0 + - Task: Instance Segmentation + Dataset: COCO + Metrics: + mask AP: 37.6 + Weights: https://download.openmmlab.com/mmdetection/v2.0/fp16/mask_rcnn_r50_fpn_fp16_mdconv_c3-c5_1x_coco/mask_rcnn_r50_fpn_fp16_mdconv_c3-c5_1x_coco_20210520_180434-cf8fefa5.pth diff --git a/grounding-dino/mmdetection/configs/ddod/README.md b/grounding-dino/mmdetection/configs/ddod/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d5ea9cd0cc11f7de0adf34aa4574bc20a8c11219 --- /dev/null +++ b/grounding-dino/mmdetection/configs/ddod/README.md @@ -0,0 +1,31 @@ +# DDOD + +> [Disentangle Your Dense Object Detector](https://arxiv.org/pdf/2107.02963.pdf) + + + +## Abstract + +Deep learning-based dense object detectors have achieved great success in the past few years and have been applied to numerous multimedia applications such as video understanding. However, the current training pipeline for dense detectors is compromised to lots of conjunctions that may not hold. In this paper, we investigate three such important conjunctions: 1) only samples assigned as positive in classification head are used to train the regression head; 2) classification and regression share the same input feature and computational fields defined by the parallel head architecture; and 3) samples distributed in different feature pyramid layers are treated equally when computing the loss. We first carry out a series of pilot experiments to show disentangling such conjunctions can lead to persistent performance improvement. Then, based on these findings, we propose Disentangled Dense Object Detector(DDOD), in which simple and effective disentanglement mechanisms are designed and integrated into the current state-of-the-art dense object detectors. Extensive experiments on MS COCO benchmark show that our approach can lead to 2.0 mAP, 2.4 mAP and 2.2 mAP absolute improvements on RetinaNet, FCOS, and ATSS baselines with negligible extra overhead. Notably, our best model reaches 55.0 mAP on the COCO test-dev set and 93.5 AP on the hard subset of WIDER FACE, achieving new state-of-the-art performance on these two competitive benchmarks. Code is available at https://github.com/zehuichen123/DDOD. + +
+ +
+ +## Results and Models + +| Model | Backbone | Style | Lr schd | Mem (GB) | box AP | Config | Download | +| :-------: | :------: | :-----: | :-----: | :------: | :----: | :---------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | +| DDOD-ATSS | R-50 | pytorch | 1x | 3.4 | 41.7 | [config](./ddod_r50_fpn_1x_coco.py) | [model](https://download.openmmlab.com/mmdetection/v2.0/ddod/ddod_r50_fpn_1x_coco/ddod_r50_fpn_1x_coco_20220523_223737-29b2fc67.pth) \| [log](https://download.openmmlab.com/mmdetection/v2.0/ddod/ddod_r50_fpn_1x_coco/ddod_r50_fpn_1x_coco_20220523_223737.log.json) | + +## Citation + +```latex +@inproceedings{chen2021disentangle, +title={Disentangle Your Dense Object Detector}, +author={Chen, Zehui and Yang, Chenhongyi and Li, Qiaofei and Zhao, Feng and Zha, Zheng-Jun and Wu, Feng}, +booktitle={Proceedings of the 29th ACM International Conference on Multimedia}, +pages={4939--4948}, +year={2021} +} +``` diff --git a/grounding-dino/mmdetection/configs/ddod/metafile.yml b/grounding-dino/mmdetection/configs/ddod/metafile.yml new file mode 100644 index 0000000000000000000000000000000000000000..c22395002bd614cd0e75d753320c3f9e7ce54bd1 --- /dev/null +++ b/grounding-dino/mmdetection/configs/ddod/metafile.yml @@ -0,0 +1,33 @@ +Collections: + - Name: DDOD + Metadata: + Training Data: COCO + Training Techniques: + - SGD with Momentum + - Weight Decay + Training Resources: 8x V100 GPUs + Architecture: + - DDOD + - FPN + - ResNet + Paper: + URL: https://arxiv.org/pdf/2107.02963.pdf + Title: 'Disentangle Your Dense Object Detector' + README: configs/ddod/README.md + Code: + URL: https://github.com/open-mmlab/mmdetection/blob/v2.25.0/mmdet/models/detectors/ddod.py#L6 + Version: v2.25.0 + +Models: + - Name: ddod_r50_fpn_1x_coco + In Collection: DDOD + Config: configs/ddod/ddod_r50_fpn_1x_coco.py + Metadata: + Training Memory (GB): 3.4 + Epochs: 12 + Results: + - Task: Object Detection + Dataset: COCO + Metrics: + box AP: 41.7 + Weights: https://download.openmmlab.com/mmdetection/v2.0/ddod/ddod_r50_fpn_1x_coco/ddod_r50_fpn_1x_coco_20220523_223737-29b2fc67.pth diff --git a/grounding-dino/mmdetection/configs/ddq/ddq-detr-4scale_swinl_8xb2-30e_coco.py b/grounding-dino/mmdetection/configs/ddq/ddq-detr-4scale_swinl_8xb2-30e_coco.py new file mode 100644 index 0000000000000000000000000000000000000000..d863649411e3157373961b3da339990df1e6f267 --- /dev/null +++ b/grounding-dino/mmdetection/configs/ddq/ddq-detr-4scale_swinl_8xb2-30e_coco.py @@ -0,0 +1,177 @@ +_base_ = [ + '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py' +] +pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_large_patch4_window12_384_22k.pth' # noqa: E501 +model = dict( + type='DDQDETR', + num_queries=900, # num_matching_queries + # ratio of num_dense queries to num_queries + dense_topk_ratio=1.5, + with_box_refine=True, + as_two_stage=True, + data_preprocessor=dict( + type='DetDataPreprocessor', + mean=[123.675, 116.28, 103.53], + std=[58.395, 57.12, 57.375], + bgr_to_rgb=True, + pad_size_divisor=1), + backbone=dict( + type='SwinTransformer', + pretrain_img_size=384, + embed_dims=192, + depths=[2, 2, 18, 2], + num_heads=[6, 12, 24, 48], + window_size=12, + mlp_ratio=4, + qkv_bias=True, + qk_scale=None, + drop_rate=0., + attn_drop_rate=0., + drop_path_rate=0.2, + patch_norm=True, + out_indices=(1, 2, 3), + with_cp=False, + convert_weights=True, + init_cfg=dict(type='Pretrained', checkpoint=pretrained)), + neck=dict( + type='ChannelMapper', + in_channels=[384, 768, 1536], + kernel_size=1, + out_channels=256, + act_cfg=None, + norm_cfg=dict(type='GN', num_groups=32), + num_outs=4), + # encoder class name: DeformableDetrTransformerEncoder + encoder=dict( + num_layers=6, + layer_cfg=dict( + self_attn_cfg=dict(embed_dims=256, num_levels=4, + dropout=0.0), # 0.1 for DeformDETR + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, # 1024 for DeformDETR + ffn_drop=0.0))), # 0.1 for DeformDETR + # decoder class name: DDQTransformerDecoder + decoder=dict( + num_layers=6, + return_intermediate=True, + layer_cfg=dict( + self_attn_cfg=dict(embed_dims=256, num_heads=8, + dropout=0.0), # 0.1 for DeformDETR + cross_attn_cfg=dict(embed_dims=256, num_levels=4, + dropout=0.0), # 0.1 for DeformDETR + ffn_cfg=dict( + embed_dims=256, + feedforward_channels=2048, # 1024 for DeformDETR + ffn_drop=0.0)), # 0.1 for DeformDETR + post_norm_cfg=None), + positional_encoding=dict( + num_feats=128, + normalize=True, + offset=0.0, # -0.5 for DeformDETR + temperature=20), # 10000 for DeformDETR + bbox_head=dict( + type='DDQDETRHead', + num_classes=80, + sync_cls_avg_factor=True, + loss_cls=dict( + type='FocalLoss', + use_sigmoid=True, + gamma=2.0, + alpha=0.25, + loss_weight=1.0), + loss_bbox=dict(type='L1Loss', loss_weight=5.0), + loss_iou=dict(type='GIoULoss', loss_weight=2.0)), + dn_cfg=dict( + label_noise_scale=0.5, + box_noise_scale=1.0, + group_cfg=dict(dynamic=True, num_groups=None, num_dn_queries=100)), + dqs_cfg=dict(type='nms', iou_threshold=0.8), + # training and testing settings + train_cfg=dict( + assigner=dict( + type='HungarianAssigner', + match_costs=[ + dict(type='FocalLossCost', weight=2.0), + dict(type='BBoxL1Cost', weight=5.0, box_format='xywh'), + dict(type='IoUCost', iou_mode='giou', weight=2.0) + ])), + test_cfg=dict(max_per_img=300)) + +train_pipeline = [ + dict(type='LoadImageFromFile', backend_args=_base_.backend_args), + dict(type='LoadAnnotations', with_bbox=True), + dict(type='RandomFlip', prob=0.5), + dict( + type='RandomChoice', + transforms=[ + [ + dict( + type='RandomChoiceResize', + scales=[(480, 1333), (512, 1333), (544, 1333), (576, 1333), + (608, 1333), (640, 1333), (672, 1333), (704, 1333), + (736, 1333), (768, 1333), (800, 1333)], + keep_ratio=True) + ], + [ + dict( + type='RandomChoiceResize', + # The radio of all image in train dataset < 7 + # follow the original implement + scales=[(400, 4200), (500, 4200), (600, 4200)], + keep_ratio=True), + dict( + type='RandomCrop', + crop_type='absolute_range', + crop_size=(384, 600), + allow_negative_crop=True), + dict( + type='RandomChoiceResize', + scales=[(480, 1333), (512, 1333), (544, 1333), (576, 1333), + (608, 1333), (640, 1333), (672, 1333), (704, 1333), + (736, 1333), (768, 1333), (800, 1333)], + keep_ratio=True) + ] + ]), + dict(type='PackDetInputs') +] + +train_dataloader = dict( + dataset=dict( + filter_cfg=dict(filter_empty_gt=False), pipeline=train_pipeline)) + +# optimizer +optim_wrapper = dict( + type='OptimWrapper', + optimizer=dict(type='AdamW', lr=0.0002, weight_decay=0.05), + clip_grad=dict(max_norm=0.1, norm_type=2), + paramwise_cfg=dict(custom_keys={'backbone': dict(lr_mult=0.05)})) + +# learning policy +max_epochs = 30 +train_cfg = dict( + type='EpochBasedTrainLoop', max_epochs=max_epochs, val_interval=1) + +val_cfg = dict(type='ValLoop') +test_cfg = dict(type='TestLoop') + +param_scheduler = [ + dict( + type='LinearLR', + start_factor=0.0001, + by_epoch=False, + begin=0, + end=2000), + dict( + type='MultiStepLR', + begin=0, + end=max_epochs, + by_epoch=True, + milestones=[20, 26], + gamma=0.1) +] + +# NOTE: `auto_scale_lr` is for automatically scaling LR, +# USER SHOULD NOT CHANGE ITS VALUES. +# base_batch_size = (8 GPUs) x (2 samples per GPU) +auto_scale_lr = dict(base_batch_size=16)