diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__init__.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21916243c56e306f6c18b265afc20d2095cd4e52 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__init__.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 + +"""CacheControl import Interface. + +Make it easy to import from cachecontrol without long namespaces. +""" + +__author__ = "Eric Larson" +__email__ = "eric@ionrock.org" +__version__ = "0.14.1" + +from pip._vendor.cachecontrol.adapter import CacheControlAdapter +from pip._vendor.cachecontrol.controller import CacheController +from pip._vendor.cachecontrol.wrapper import CacheControl + +__all__ = [ + "__author__", + "__email__", + "__version__", + "CacheControlAdapter", + "CacheController", + "CacheControl", +] + +import logging + +logging.getLogger(__name__).addHandler(logging.NullHandler()) diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b79bb02d0451df904fd745db009cfefe6f6c132 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..222c115a8c939a88c23bebfe7185519e7e9a8092 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/adapter.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/adapter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..234a6804686b6e5d07e21672e6a8aa523cff09ac Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/adapter.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/cache.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/cache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31d2807bd9900dd2ace69a4d23f40b31a904ad0f Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/cache.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/controller.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8d4dc66809d76d5e88e3c12864b3bd40e3baaab Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/controller.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebde07471d44652e2434855a0d3e882fded920ee Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8fbfa5224c9787b233d828dd474d8a1491899ec Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/serialize.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/serialize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..218b499f102721599998cba1efb868c4f0e53e6e Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/serialize.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b2f5e01d442b0dd297a4769e4b6afe71d8c6d92 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/_cmd.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..2c84208a5d87511cc4a63dcd9c647ac75c6f4475 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/_cmd.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import logging +from argparse import ArgumentParser +from typing import TYPE_CHECKING + +from pip._vendor import requests + +from pip._vendor.cachecontrol.adapter import CacheControlAdapter +from pip._vendor.cachecontrol.cache import DictCache +from pip._vendor.cachecontrol.controller import logger + +if TYPE_CHECKING: + from argparse import Namespace + + from pip._vendor.cachecontrol.controller import CacheController + + +def setup_logging() -> None: + logger.setLevel(logging.DEBUG) + handler = logging.StreamHandler() + logger.addHandler(handler) + + +def get_session() -> requests.Session: + adapter = CacheControlAdapter( + DictCache(), cache_etags=True, serializer=None, heuristic=None + ) + sess = requests.Session() + sess.mount("http://", adapter) + sess.mount("https://", adapter) + + sess.cache_controller = adapter.controller # type: ignore[attr-defined] + return sess + + +def get_args() -> Namespace: + parser = ArgumentParser() + parser.add_argument("url", help="The URL to try and cache") + return parser.parse_args() + + +def main() -> None: + args = get_args() + sess = get_session() + + # Make a request to get a response + resp = sess.get(args.url) + + # Turn on logging + setup_logging() + + # try setting the cache + cache_controller: CacheController = ( + sess.cache_controller # type: ignore[attr-defined] + ) + cache_controller.cache_response(resp.request, resp.raw) + + # Now try to get it + if cache_controller.cached_request(resp.request): + print("Cached!") + else: + print("Not cached :(") + + +if __name__ == "__main__": + main() diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/adapter.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..34a9eb82798715a17b9529290cd4f25a13e5d9c9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/adapter.py @@ -0,0 +1,161 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import functools +import types +import zlib +from typing import TYPE_CHECKING, Any, Collection, Mapping + +from pip._vendor.requests.adapters import HTTPAdapter + +from pip._vendor.cachecontrol.cache import DictCache +from pip._vendor.cachecontrol.controller import PERMANENT_REDIRECT_STATUSES, CacheController +from pip._vendor.cachecontrol.filewrapper import CallbackFileWrapper + +if TYPE_CHECKING: + from pip._vendor.requests import PreparedRequest, Response + from pip._vendor.urllib3 import HTTPResponse + + from pip._vendor.cachecontrol.cache import BaseCache + from pip._vendor.cachecontrol.heuristics import BaseHeuristic + from pip._vendor.cachecontrol.serialize import Serializer + + +class CacheControlAdapter(HTTPAdapter): + invalidating_methods = {"PUT", "PATCH", "DELETE"} + + def __init__( + self, + cache: BaseCache | None = None, + cache_etags: bool = True, + controller_class: type[CacheController] | None = None, + serializer: Serializer | None = None, + heuristic: BaseHeuristic | None = None, + cacheable_methods: Collection[str] | None = None, + *args: Any, + **kw: Any, + ) -> None: + super().__init__(*args, **kw) + self.cache = DictCache() if cache is None else cache + self.heuristic = heuristic + self.cacheable_methods = cacheable_methods or ("GET",) + + controller_factory = controller_class or CacheController + self.controller = controller_factory( + self.cache, cache_etags=cache_etags, serializer=serializer + ) + + def send( + self, + request: PreparedRequest, + stream: bool = False, + timeout: None | float | tuple[float, float] | tuple[float, None] = None, + verify: bool | str = True, + cert: (None | bytes | str | tuple[bytes | str, bytes | str]) = None, + proxies: Mapping[str, str] | None = None, + cacheable_methods: Collection[str] | None = None, + ) -> Response: + """ + Send a request. Use the request information to see if it + exists in the cache and cache the response if we need to and can. + """ + cacheable = cacheable_methods or self.cacheable_methods + if request.method in cacheable: + try: + cached_response = self.controller.cached_request(request) + except zlib.error: + cached_response = None + if cached_response: + return self.build_response(request, cached_response, from_cache=True) + + # check for etags and add headers if appropriate + request.headers.update(self.controller.conditional_headers(request)) + + resp = super().send(request, stream, timeout, verify, cert, proxies) + + return resp + + def build_response( # type: ignore[override] + self, + request: PreparedRequest, + response: HTTPResponse, + from_cache: bool = False, + cacheable_methods: Collection[str] | None = None, + ) -> Response: + """ + Build a response by making a request or using the cache. + + This will end up calling send and returning a potentially + cached response + """ + cacheable = cacheable_methods or self.cacheable_methods + if not from_cache and request.method in cacheable: + # Check for any heuristics that might update headers + # before trying to cache. + if self.heuristic: + response = self.heuristic.apply(response) + + # apply any expiration heuristics + if response.status == 304: + # We must have sent an ETag request. This could mean + # that we've been expired already or that we simply + # have an etag. In either case, we want to try and + # update the cache if that is the case. + cached_response = self.controller.update_cached_response( + request, response + ) + + if cached_response is not response: + from_cache = True + + # We are done with the server response, read a + # possible response body (compliant servers will + # not return one, but we cannot be 100% sure) and + # release the connection back to the pool. + response.read(decode_content=False) + response.release_conn() + + response = cached_response + + # We always cache the 301 responses + elif int(response.status) in PERMANENT_REDIRECT_STATUSES: + self.controller.cache_response(request, response) + else: + # Wrap the response file with a wrapper that will cache the + # response when the stream has been consumed. + response._fp = CallbackFileWrapper( # type: ignore[assignment] + response._fp, # type: ignore[arg-type] + functools.partial( + self.controller.cache_response, request, response + ), + ) + if response.chunked: + super_update_chunk_length = response._update_chunk_length + + def _update_chunk_length(self: HTTPResponse) -> None: + super_update_chunk_length() + if self.chunk_left == 0: + self._fp._close() # type: ignore[union-attr] + + response._update_chunk_length = types.MethodType( # type: ignore[method-assign] + _update_chunk_length, response + ) + + resp: Response = super().build_response(request, response) + + # See if we should invalidate the cache. + if request.method in self.invalidating_methods and resp.ok: + assert request.url is not None + cache_url = self.controller.cache_url(request.url) + self.cache.delete(cache_url) + + # Give the request a from_cache attr to let people use it + resp.from_cache = from_cache # type: ignore[attr-defined] + + return resp + + def close(self) -> None: + self.cache.close() + super().close() # type: ignore[no-untyped-call] diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/cache.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..91598e92034fa4f70353fbf7c9c19dc9558e320b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/cache.py @@ -0,0 +1,75 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 + +""" +The cache object API for implementing caches. The default is a thread +safe in-memory dictionary. +""" + +from __future__ import annotations + +from threading import Lock +from typing import IO, TYPE_CHECKING, MutableMapping + +if TYPE_CHECKING: + from datetime import datetime + + +class BaseCache: + def get(self, key: str) -> bytes | None: + raise NotImplementedError() + + def set( + self, key: str, value: bytes, expires: int | datetime | None = None + ) -> None: + raise NotImplementedError() + + def delete(self, key: str) -> None: + raise NotImplementedError() + + def close(self) -> None: + pass + + +class DictCache(BaseCache): + def __init__(self, init_dict: MutableMapping[str, bytes] | None = None) -> None: + self.lock = Lock() + self.data = init_dict or {} + + def get(self, key: str) -> bytes | None: + return self.data.get(key, None) + + def set( + self, key: str, value: bytes, expires: int | datetime | None = None + ) -> None: + with self.lock: + self.data.update({key: value}) + + def delete(self, key: str) -> None: + with self.lock: + if key in self.data: + self.data.pop(key) + + +class SeparateBodyBaseCache(BaseCache): + """ + In this variant, the body is not stored mixed in with the metadata, but is + passed in (as a bytes-like object) in a separate call to ``set_body()``. + + That is, the expected interaction pattern is:: + + cache.set(key, serialized_metadata) + cache.set_body(key) + + Similarly, the body should be loaded separately via ``get_body()``. + """ + + def set_body(self, key: str, body: bytes) -> None: + raise NotImplementedError() + + def get_body(self, key: str) -> IO[bytes] | None: + """ + Return the body as file-like object. + """ + raise NotImplementedError() diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__init__.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..24ff469ff98baf5a4457ba6a34330be310058cb4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 + +from pip._vendor.cachecontrol.caches.file_cache import FileCache, SeparateBodyFileCache +from pip._vendor.cachecontrol.caches.redis_cache import RedisCache + +__all__ = ["FileCache", "SeparateBodyFileCache", "RedisCache"] diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdef66bd66a55bf38c80aa575fdcd297a534f90d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e0c47952fba28cc5054db16341542974ecfbb06 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb28c006f205f88c242a495bc1cfae53d32ea5e7 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..81d2ef46cf8e9556f1bd2d03b42bc51a3ccfcf5a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py @@ -0,0 +1,182 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import hashlib +import os +from textwrap import dedent +from typing import IO, TYPE_CHECKING +from pathlib import Path + +from pip._vendor.cachecontrol.cache import BaseCache, SeparateBodyBaseCache +from pip._vendor.cachecontrol.controller import CacheController + +if TYPE_CHECKING: + from datetime import datetime + + from filelock import BaseFileLock + + +def _secure_open_write(filename: str, fmode: int) -> IO[bytes]: + # We only want to write to this file, so open it in write only mode + flags = os.O_WRONLY + + # os.O_CREAT | os.O_EXCL will fail if the file already exists, so we only + # will open *new* files. + # We specify this because we want to ensure that the mode we pass is the + # mode of the file. + flags |= os.O_CREAT | os.O_EXCL + + # Do not follow symlinks to prevent someone from making a symlink that + # we follow and insecurely open a cache file. + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + + # On Windows we'll mark this file as binary + if hasattr(os, "O_BINARY"): + flags |= os.O_BINARY + + # Before we open our file, we want to delete any existing file that is + # there + try: + os.remove(filename) + except OSError: + # The file must not exist already, so we can just skip ahead to opening + pass + + # Open our file, the use of os.O_CREAT | os.O_EXCL will ensure that if a + # race condition happens between the os.remove and this line, that an + # error will be raised. Because we utilize a lockfile this should only + # happen if someone is attempting to attack us. + fd = os.open(filename, flags, fmode) + try: + return os.fdopen(fd, "wb") + + except: + # An error occurred wrapping our FD in a file object + os.close(fd) + raise + + +class _FileCacheMixin: + """Shared implementation for both FileCache variants.""" + + def __init__( + self, + directory: str | Path, + forever: bool = False, + filemode: int = 0o0600, + dirmode: int = 0o0700, + lock_class: type[BaseFileLock] | None = None, + ) -> None: + try: + if lock_class is None: + from filelock import FileLock + + lock_class = FileLock + except ImportError: + notice = dedent( + """ + NOTE: In order to use the FileCache you must have + filelock installed. You can install it via pip: + pip install cachecontrol[filecache] + """ + ) + raise ImportError(notice) + + self.directory = directory + self.forever = forever + self.filemode = filemode + self.dirmode = dirmode + self.lock_class = lock_class + + @staticmethod + def encode(x: str) -> str: + return hashlib.sha224(x.encode()).hexdigest() + + def _fn(self, name: str) -> str: + # NOTE: This method should not change as some may depend on it. + # See: https://github.com/ionrock/cachecontrol/issues/63 + hashed = self.encode(name) + parts = list(hashed[:5]) + [hashed] + return os.path.join(self.directory, *parts) + + def get(self, key: str) -> bytes | None: + name = self._fn(key) + try: + with open(name, "rb") as fh: + return fh.read() + + except FileNotFoundError: + return None + + def set( + self, key: str, value: bytes, expires: int | datetime | None = None + ) -> None: + name = self._fn(key) + self._write(name, value) + + def _write(self, path: str, data: bytes) -> None: + """ + Safely write the data to the given path. + """ + # Make sure the directory exists + try: + os.makedirs(os.path.dirname(path), self.dirmode) + except OSError: + pass + + with self.lock_class(path + ".lock"): + # Write our actual file + with _secure_open_write(path, self.filemode) as fh: + fh.write(data) + + def _delete(self, key: str, suffix: str) -> None: + name = self._fn(key) + suffix + if not self.forever: + try: + os.remove(name) + except FileNotFoundError: + pass + + +class FileCache(_FileCacheMixin, BaseCache): + """ + Traditional FileCache: body is stored in memory, so not suitable for large + downloads. + """ + + def delete(self, key: str) -> None: + self._delete(key, "") + + +class SeparateBodyFileCache(_FileCacheMixin, SeparateBodyBaseCache): + """ + Memory-efficient FileCache: body is stored in a separate file, reducing + peak memory usage. + """ + + def get_body(self, key: str) -> IO[bytes] | None: + name = self._fn(key) + ".body" + try: + return open(name, "rb") + except FileNotFoundError: + return None + + def set_body(self, key: str, body: bytes) -> None: + name = self._fn(key) + ".body" + self._write(name, body) + + def delete(self, key: str) -> None: + self._delete(key, "") + self._delete(key, ".body") + + +def url_to_file_path(url: str, filecache: FileCache) -> str: + """Return the file cache path based on the URL. + + This does not ensure the file exists! + """ + key = CacheController.cache_url(url) + return filecache._fn(key) diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..f4f68c47bf6e82b3faea0bd558852585f5f50a81 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + + +from datetime import datetime, timezone +from typing import TYPE_CHECKING + +from pip._vendor.cachecontrol.cache import BaseCache + +if TYPE_CHECKING: + from redis import Redis + + +class RedisCache(BaseCache): + def __init__(self, conn: Redis[bytes]) -> None: + self.conn = conn + + def get(self, key: str) -> bytes | None: + return self.conn.get(key) + + def set( + self, key: str, value: bytes, expires: int | datetime | None = None + ) -> None: + if not expires: + self.conn.set(key, value) + elif isinstance(expires, datetime): + now_utc = datetime.now(timezone.utc) + if expires.tzinfo is None: + now_utc = now_utc.replace(tzinfo=None) + delta = expires - now_utc + self.conn.setex(key, int(delta.total_seconds()), value) + else: + self.conn.setex(key, expires, value) + + def delete(self, key: str) -> None: + self.conn.delete(key) + + def clear(self) -> None: + """Helper for clearing all the keys in a database. Use with + caution!""" + for key in self.conn.keys(): + self.conn.delete(key) + + def close(self) -> None: + """Redis uses connection pooling, no need to close the connection.""" + pass diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/controller.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ff6e1bedcca5d5bc741c85ae4c0be9f4a2861c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/controller.py @@ -0,0 +1,500 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 + +""" +The httplib2 algorithms ported for use with requests. +""" + +from __future__ import annotations + +import calendar +import logging +import re +import time +from email.utils import parsedate_tz +from typing import TYPE_CHECKING, Collection, Mapping + +from pip._vendor.requests.structures import CaseInsensitiveDict + +from pip._vendor.cachecontrol.cache import DictCache, SeparateBodyBaseCache +from pip._vendor.cachecontrol.serialize import Serializer + +if TYPE_CHECKING: + from typing import Literal + + from pip._vendor.requests import PreparedRequest + from pip._vendor.urllib3 import HTTPResponse + + from pip._vendor.cachecontrol.cache import BaseCache + +logger = logging.getLogger(__name__) + +URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?") + +PERMANENT_REDIRECT_STATUSES = (301, 308) + + +def parse_uri(uri: str) -> tuple[str, str, str, str, str]: + """Parses a URI using the regex given in Appendix B of RFC 3986. + + (scheme, authority, path, query, fragment) = parse_uri(uri) + """ + match = URI.match(uri) + assert match is not None + groups = match.groups() + return (groups[1], groups[3], groups[4], groups[6], groups[8]) + + +class CacheController: + """An interface to see if request should cached or not.""" + + def __init__( + self, + cache: BaseCache | None = None, + cache_etags: bool = True, + serializer: Serializer | None = None, + status_codes: Collection[int] | None = None, + ): + self.cache = DictCache() if cache is None else cache + self.cache_etags = cache_etags + self.serializer = serializer or Serializer() + self.cacheable_status_codes = status_codes or (200, 203, 300, 301, 308) + + @classmethod + def _urlnorm(cls, uri: str) -> str: + """Normalize the URL to create a safe key for the cache""" + (scheme, authority, path, query, fragment) = parse_uri(uri) + if not scheme or not authority: + raise Exception("Only absolute URIs are allowed. uri = %s" % uri) + + scheme = scheme.lower() + authority = authority.lower() + + if not path: + path = "/" + + # Could do syntax based normalization of the URI before + # computing the digest. See Section 6.2.2 of Std 66. + request_uri = query and "?".join([path, query]) or path + defrag_uri = scheme + "://" + authority + request_uri + + return defrag_uri + + @classmethod + def cache_url(cls, uri: str) -> str: + return cls._urlnorm(uri) + + def parse_cache_control(self, headers: Mapping[str, str]) -> dict[str, int | None]: + known_directives = { + # https://tools.ietf.org/html/rfc7234#section-5.2 + "max-age": (int, True), + "max-stale": (int, False), + "min-fresh": (int, True), + "no-cache": (None, False), + "no-store": (None, False), + "no-transform": (None, False), + "only-if-cached": (None, False), + "must-revalidate": (None, False), + "public": (None, False), + "private": (None, False), + "proxy-revalidate": (None, False), + "s-maxage": (int, True), + } + + cc_headers = headers.get("cache-control", headers.get("Cache-Control", "")) + + retval: dict[str, int | None] = {} + + for cc_directive in cc_headers.split(","): + if not cc_directive.strip(): + continue + + parts = cc_directive.split("=", 1) + directive = parts[0].strip() + + try: + typ, required = known_directives[directive] + except KeyError: + logger.debug("Ignoring unknown cache-control directive: %s", directive) + continue + + if not typ or not required: + retval[directive] = None + if typ: + try: + retval[directive] = typ(parts[1].strip()) + except IndexError: + if required: + logger.debug( + "Missing value for cache-control " "directive: %s", + directive, + ) + except ValueError: + logger.debug( + "Invalid value for cache-control directive " "%s, must be %s", + directive, + typ.__name__, + ) + + return retval + + def _load_from_cache(self, request: PreparedRequest) -> HTTPResponse | None: + """ + Load a cached response, or return None if it's not available. + """ + # We do not support caching of partial content: so if the request contains a + # Range header then we don't want to load anything from the cache. + if "Range" in request.headers: + return None + + cache_url = request.url + assert cache_url is not None + cache_data = self.cache.get(cache_url) + if cache_data is None: + logger.debug("No cache entry available") + return None + + if isinstance(self.cache, SeparateBodyBaseCache): + body_file = self.cache.get_body(cache_url) + else: + body_file = None + + result = self.serializer.loads(request, cache_data, body_file) + if result is None: + logger.warning("Cache entry deserialization failed, entry ignored") + return result + + def cached_request(self, request: PreparedRequest) -> HTTPResponse | Literal[False]: + """ + Return a cached response if it exists in the cache, otherwise + return False. + """ + assert request.url is not None + cache_url = self.cache_url(request.url) + logger.debug('Looking up "%s" in the cache', cache_url) + cc = self.parse_cache_control(request.headers) + + # Bail out if the request insists on fresh data + if "no-cache" in cc: + logger.debug('Request header has "no-cache", cache bypassed') + return False + + if "max-age" in cc and cc["max-age"] == 0: + logger.debug('Request header has "max_age" as 0, cache bypassed') + return False + + # Check whether we can load the response from the cache: + resp = self._load_from_cache(request) + if not resp: + return False + + # If we have a cached permanent redirect, return it immediately. We + # don't need to test our response for other headers b/c it is + # intrinsically "cacheable" as it is Permanent. + # + # See: + # https://tools.ietf.org/html/rfc7231#section-6.4.2 + # + # Client can try to refresh the value by repeating the request + # with cache busting headers as usual (ie no-cache). + if int(resp.status) in PERMANENT_REDIRECT_STATUSES: + msg = ( + "Returning cached permanent redirect response " + "(ignoring date and etag information)" + ) + logger.debug(msg) + return resp + + headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers) + if not headers or "date" not in headers: + if "etag" not in headers: + # Without date or etag, the cached response can never be used + # and should be deleted. + logger.debug("Purging cached response: no date or etag") + self.cache.delete(cache_url) + logger.debug("Ignoring cached response: no date") + return False + + now = time.time() + time_tuple = parsedate_tz(headers["date"]) + assert time_tuple is not None + date = calendar.timegm(time_tuple[:6]) + current_age = max(0, now - date) + logger.debug("Current age based on date: %i", current_age) + + # TODO: There is an assumption that the result will be a + # urllib3 response object. This may not be best since we + # could probably avoid instantiating or constructing the + # response until we know we need it. + resp_cc = self.parse_cache_control(headers) + + # determine freshness + freshness_lifetime = 0 + + # Check the max-age pragma in the cache control header + max_age = resp_cc.get("max-age") + if max_age is not None: + freshness_lifetime = max_age + logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime) + + # If there isn't a max-age, check for an expires header + elif "expires" in headers: + expires = parsedate_tz(headers["expires"]) + if expires is not None: + expire_time = calendar.timegm(expires[:6]) - date + freshness_lifetime = max(0, expire_time) + logger.debug("Freshness lifetime from expires: %i", freshness_lifetime) + + # Determine if we are setting freshness limit in the + # request. Note, this overrides what was in the response. + max_age = cc.get("max-age") + if max_age is not None: + freshness_lifetime = max_age + logger.debug( + "Freshness lifetime from request max-age: %i", freshness_lifetime + ) + + min_fresh = cc.get("min-fresh") + if min_fresh is not None: + # adjust our current age by our min fresh + current_age += min_fresh + logger.debug("Adjusted current age from min-fresh: %i", current_age) + + # Return entry if it is fresh enough + if freshness_lifetime > current_age: + logger.debug('The response is "fresh", returning cached response') + logger.debug("%i > %i", freshness_lifetime, current_age) + return resp + + # we're not fresh. If we don't have an Etag, clear it out + if "etag" not in headers: + logger.debug('The cached response is "stale" with no etag, purging') + self.cache.delete(cache_url) + + # return the original handler + return False + + def conditional_headers(self, request: PreparedRequest) -> dict[str, str]: + resp = self._load_from_cache(request) + new_headers = {} + + if resp: + headers: CaseInsensitiveDict[str] = CaseInsensitiveDict(resp.headers) + + if "etag" in headers: + new_headers["If-None-Match"] = headers["ETag"] + + if "last-modified" in headers: + new_headers["If-Modified-Since"] = headers["Last-Modified"] + + return new_headers + + def _cache_set( + self, + cache_url: str, + request: PreparedRequest, + response: HTTPResponse, + body: bytes | None = None, + expires_time: int | None = None, + ) -> None: + """ + Store the data in the cache. + """ + if isinstance(self.cache, SeparateBodyBaseCache): + # We pass in the body separately; just put a placeholder empty + # string in the metadata. + self.cache.set( + cache_url, + self.serializer.dumps(request, response, b""), + expires=expires_time, + ) + # body is None can happen when, for example, we're only updating + # headers, as is the case in update_cached_response(). + if body is not None: + self.cache.set_body(cache_url, body) + else: + self.cache.set( + cache_url, + self.serializer.dumps(request, response, body), + expires=expires_time, + ) + + def cache_response( + self, + request: PreparedRequest, + response: HTTPResponse, + body: bytes | None = None, + status_codes: Collection[int] | None = None, + ) -> None: + """ + Algorithm for caching requests. + + This assumes a requests Response object. + """ + # From httplib2: Don't cache 206's since we aren't going to + # handle byte range requests + cacheable_status_codes = status_codes or self.cacheable_status_codes + if response.status not in cacheable_status_codes: + logger.debug( + "Status code %s not in %s", response.status, cacheable_status_codes + ) + return + + response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict( + response.headers + ) + + if "date" in response_headers: + time_tuple = parsedate_tz(response_headers["date"]) + assert time_tuple is not None + date = calendar.timegm(time_tuple[:6]) + else: + date = 0 + + # If we've been given a body, our response has a Content-Length, that + # Content-Length is valid then we can check to see if the body we've + # been given matches the expected size, and if it doesn't we'll just + # skip trying to cache it. + if ( + body is not None + and "content-length" in response_headers + and response_headers["content-length"].isdigit() + and int(response_headers["content-length"]) != len(body) + ): + return + + cc_req = self.parse_cache_control(request.headers) + cc = self.parse_cache_control(response_headers) + + assert request.url is not None + cache_url = self.cache_url(request.url) + logger.debug('Updating cache with response from "%s"', cache_url) + + # Delete it from the cache if we happen to have it stored there + no_store = False + if "no-store" in cc: + no_store = True + logger.debug('Response header has "no-store"') + if "no-store" in cc_req: + no_store = True + logger.debug('Request header has "no-store"') + if no_store and self.cache.get(cache_url): + logger.debug('Purging existing cache entry to honor "no-store"') + self.cache.delete(cache_url) + if no_store: + return + + # https://tools.ietf.org/html/rfc7234#section-4.1: + # A Vary header field-value of "*" always fails to match. + # Storing such a response leads to a deserialization warning + # during cache lookup and is not allowed to ever be served, + # so storing it can be avoided. + if "*" in response_headers.get("vary", ""): + logger.debug('Response header has "Vary: *"') + return + + # If we've been given an etag, then keep the response + if self.cache_etags and "etag" in response_headers: + expires_time = 0 + if response_headers.get("expires"): + expires = parsedate_tz(response_headers["expires"]) + if expires is not None: + expires_time = calendar.timegm(expires[:6]) - date + + expires_time = max(expires_time, 14 * 86400) + + logger.debug(f"etag object cached for {expires_time} seconds") + logger.debug("Caching due to etag") + self._cache_set(cache_url, request, response, body, expires_time) + + # Add to the cache any permanent redirects. We do this before looking + # that the Date headers. + elif int(response.status) in PERMANENT_REDIRECT_STATUSES: + logger.debug("Caching permanent redirect") + self._cache_set(cache_url, request, response, b"") + + # Add to the cache if the response headers demand it. If there + # is no date header then we can't do anything about expiring + # the cache. + elif "date" in response_headers: + time_tuple = parsedate_tz(response_headers["date"]) + assert time_tuple is not None + date = calendar.timegm(time_tuple[:6]) + # cache when there is a max-age > 0 + max_age = cc.get("max-age") + if max_age is not None and max_age > 0: + logger.debug("Caching b/c date exists and max-age > 0") + expires_time = max_age + self._cache_set( + cache_url, + request, + response, + body, + expires_time, + ) + + # If the request can expire, it means we should cache it + # in the meantime. + elif "expires" in response_headers: + if response_headers["expires"]: + expires = parsedate_tz(response_headers["expires"]) + if expires is not None: + expires_time = calendar.timegm(expires[:6]) - date + else: + expires_time = None + + logger.debug( + "Caching b/c of expires header. expires in {} seconds".format( + expires_time + ) + ) + self._cache_set( + cache_url, + request, + response, + body, + expires_time, + ) + + def update_cached_response( + self, request: PreparedRequest, response: HTTPResponse + ) -> HTTPResponse: + """On a 304 we will get a new set of headers that we want to + update our cached value with, assuming we have one. + + This should only ever be called when we've sent an ETag and + gotten a 304 as the response. + """ + assert request.url is not None + cache_url = self.cache_url(request.url) + cached_response = self._load_from_cache(request) + + if not cached_response: + # we didn't have a cached response + return response + + # Lets update our headers with the headers from the new request: + # http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1 + # + # The server isn't supposed to send headers that would make + # the cached body invalid. But... just in case, we'll be sure + # to strip out ones we know that might be problmatic due to + # typical assumptions. + excluded_headers = ["content-length"] + + cached_response.headers.update( + { + k: v + for k, v in response.headers.items() + if k.lower() not in excluded_headers + } + ) + + # we want a 200 b/c we have content via the cache + cached_response.status = 200 + + # update our cache + self._cache_set(cache_url, request, cached_response) + + return cached_response diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/filewrapper.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/filewrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..37d2fa5915e098b430d802f5a578da309b4bf87f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/filewrapper.py @@ -0,0 +1,119 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import mmap +from tempfile import NamedTemporaryFile +from typing import TYPE_CHECKING, Any, Callable + +if TYPE_CHECKING: + from http.client import HTTPResponse + + +class CallbackFileWrapper: + """ + Small wrapper around a fp object which will tee everything read into a + buffer, and when that file is closed it will execute a callback with the + contents of that buffer. + + All attributes are proxied to the underlying file object. + + This class uses members with a double underscore (__) leading prefix so as + not to accidentally shadow an attribute. + + The data is stored in a temporary file until it is all available. As long + as the temporary files directory is disk-based (sometimes it's a + memory-backed-``tmpfs`` on Linux), data will be unloaded to disk if memory + pressure is high. For small files the disk usually won't be used at all, + it'll all be in the filesystem memory cache, so there should be no + performance impact. + """ + + def __init__( + self, fp: HTTPResponse, callback: Callable[[bytes], None] | None + ) -> None: + self.__buf = NamedTemporaryFile("rb+", delete=True) + self.__fp = fp + self.__callback = callback + + def __getattr__(self, name: str) -> Any: + # The vagaries of garbage collection means that self.__fp is + # not always set. By using __getattribute__ and the private + # name[0] allows looking up the attribute value and raising an + # AttributeError when it doesn't exist. This stop things from + # infinitely recursing calls to getattr in the case where + # self.__fp hasn't been set. + # + # [0] https://docs.python.org/2/reference/expressions.html#atom-identifiers + fp = self.__getattribute__("_CallbackFileWrapper__fp") + return getattr(fp, name) + + def __is_fp_closed(self) -> bool: + try: + return self.__fp.fp is None + + except AttributeError: + pass + + try: + closed: bool = self.__fp.closed + return closed + + except AttributeError: + pass + + # We just don't cache it then. + # TODO: Add some logging here... + return False + + def _close(self) -> None: + if self.__callback: + if self.__buf.tell() == 0: + # Empty file: + result = b"" + else: + # Return the data without actually loading it into memory, + # relying on Python's buffer API and mmap(). mmap() just gives + # a view directly into the filesystem's memory cache, so it + # doesn't result in duplicate memory use. + self.__buf.seek(0, 0) + result = memoryview( + mmap.mmap(self.__buf.fileno(), 0, access=mmap.ACCESS_READ) + ) + self.__callback(result) + + # We assign this to None here, because otherwise we can get into + # really tricky problems where the CPython interpreter dead locks + # because the callback is holding a reference to something which + # has a __del__ method. Setting this to None breaks the cycle + # and allows the garbage collector to do it's thing normally. + self.__callback = None + + # Closing the temporary file releases memory and frees disk space. + # Important when caching big files. + self.__buf.close() + + def read(self, amt: int | None = None) -> bytes: + data: bytes = self.__fp.read(amt) + if data: + # We may be dealing with b'', a sign that things are over: + # it's passed e.g. after we've already closed self.__buf. + self.__buf.write(data) + if self.__is_fp_closed(): + self._close() + + return data + + def _safe_read(self, amt: int) -> bytes: + data: bytes = self.__fp._safe_read(amt) # type: ignore[attr-defined] + if amt == 2 and data == b"\r\n": + # urllib executes this read to toss the CRLF at the end + # of the chunk. + return data + + self.__buf.write(data) + if self.__is_fp_closed(): + self._close() + + return data diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/heuristics.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/heuristics.py new file mode 100644 index 0000000000000000000000000000000000000000..b778c4f3f7ad5e22fca433be02a824446fb47ff5 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/heuristics.py @@ -0,0 +1,157 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import calendar +import time +from datetime import datetime, timedelta, timezone +from email.utils import formatdate, parsedate, parsedate_tz +from typing import TYPE_CHECKING, Any, Mapping + +if TYPE_CHECKING: + from pip._vendor.urllib3 import HTTPResponse + +TIME_FMT = "%a, %d %b %Y %H:%M:%S GMT" + + +def expire_after(delta: timedelta, date: datetime | None = None) -> datetime: + date = date or datetime.now(timezone.utc) + return date + delta + + +def datetime_to_header(dt: datetime) -> str: + return formatdate(calendar.timegm(dt.timetuple())) + + +class BaseHeuristic: + def warning(self, response: HTTPResponse) -> str | None: + """ + Return a valid 1xx warning header value describing the cache + adjustments. + + The response is provided too allow warnings like 113 + http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need + to explicitly say response is over 24 hours old. + """ + return '110 - "Response is Stale"' + + def update_headers(self, response: HTTPResponse) -> dict[str, str]: + """Update the response headers with any new headers. + + NOTE: This SHOULD always include some Warning header to + signify that the response was cached by the client, not + by way of the provided headers. + """ + return {} + + def apply(self, response: HTTPResponse) -> HTTPResponse: + updated_headers = self.update_headers(response) + + if updated_headers: + response.headers.update(updated_headers) + warning_header_value = self.warning(response) + if warning_header_value is not None: + response.headers.update({"Warning": warning_header_value}) + + return response + + +class OneDayCache(BaseHeuristic): + """ + Cache the response by providing an expires 1 day in the + future. + """ + + def update_headers(self, response: HTTPResponse) -> dict[str, str]: + headers = {} + + if "expires" not in response.headers: + date = parsedate(response.headers["date"]) + expires = expire_after( + timedelta(days=1), + date=datetime(*date[:6], tzinfo=timezone.utc), # type: ignore[index,misc] + ) + headers["expires"] = datetime_to_header(expires) + headers["cache-control"] = "public" + return headers + + +class ExpiresAfter(BaseHeuristic): + """ + Cache **all** requests for a defined time period. + """ + + def __init__(self, **kw: Any) -> None: + self.delta = timedelta(**kw) + + def update_headers(self, response: HTTPResponse) -> dict[str, str]: + expires = expire_after(self.delta) + return {"expires": datetime_to_header(expires), "cache-control": "public"} + + def warning(self, response: HTTPResponse) -> str | None: + tmpl = "110 - Automatically cached for %s. Response might be stale" + return tmpl % self.delta + + +class LastModified(BaseHeuristic): + """ + If there is no Expires header already, fall back on Last-Modified + using the heuristic from + http://tools.ietf.org/html/rfc7234#section-4.2.2 + to calculate a reasonable value. + + Firefox also does something like this per + https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching_FAQ + http://lxr.mozilla.org/mozilla-release/source/netwerk/protocol/http/nsHttpResponseHead.cpp#397 + Unlike mozilla we limit this to 24-hr. + """ + + cacheable_by_default_statuses = { + 200, + 203, + 204, + 206, + 300, + 301, + 404, + 405, + 410, + 414, + 501, + } + + def update_headers(self, resp: HTTPResponse) -> dict[str, str]: + headers: Mapping[str, str] = resp.headers + + if "expires" in headers: + return {} + + if "cache-control" in headers and headers["cache-control"] != "public": + return {} + + if resp.status not in self.cacheable_by_default_statuses: + return {} + + if "date" not in headers or "last-modified" not in headers: + return {} + + time_tuple = parsedate_tz(headers["date"]) + assert time_tuple is not None + date = calendar.timegm(time_tuple[:6]) + last_modified = parsedate(headers["last-modified"]) + if last_modified is None: + return {} + + now = time.time() + current_age = max(0, now - date) + delta = date - calendar.timegm(last_modified) + freshness_lifetime = max(0, min(delta / 10, 24 * 3600)) + if freshness_lifetime <= current_age: + return {} + + expires = date + freshness_lifetime + return {"expires": time.strftime(TIME_FMT, time.gmtime(expires))} + + def warning(self, resp: HTTPResponse) -> str | None: + return None diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/py.typed b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/serialize.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..a49487a1493f9bbd160645ea4e491b4ac54a19a9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/serialize.py @@ -0,0 +1,146 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +import io +from typing import IO, TYPE_CHECKING, Any, Mapping, cast + +from pip._vendor import msgpack +from pip._vendor.requests.structures import CaseInsensitiveDict +from pip._vendor.urllib3 import HTTPResponse + +if TYPE_CHECKING: + from pip._vendor.requests import PreparedRequest + + +class Serializer: + serde_version = "4" + + def dumps( + self, + request: PreparedRequest, + response: HTTPResponse, + body: bytes | None = None, + ) -> bytes: + response_headers: CaseInsensitiveDict[str] = CaseInsensitiveDict( + response.headers + ) + + if body is None: + # When a body isn't passed in, we'll read the response. We + # also update the response with a new file handler to be + # sure it acts as though it was never read. + body = response.read(decode_content=False) + response._fp = io.BytesIO(body) # type: ignore[assignment] + response.length_remaining = len(body) + + data = { + "response": { + "body": body, # Empty bytestring if body is stored separately + "headers": {str(k): str(v) for k, v in response.headers.items()}, + "status": response.status, + "version": response.version, + "reason": str(response.reason), + "decode_content": response.decode_content, + } + } + + # Construct our vary headers + data["vary"] = {} + if "vary" in response_headers: + varied_headers = response_headers["vary"].split(",") + for header in varied_headers: + header = str(header).strip() + header_value = request.headers.get(header, None) + if header_value is not None: + header_value = str(header_value) + data["vary"][header] = header_value + + return b",".join([f"cc={self.serde_version}".encode(), self.serialize(data)]) + + def serialize(self, data: dict[str, Any]) -> bytes: + return cast(bytes, msgpack.dumps(data, use_bin_type=True)) + + def loads( + self, + request: PreparedRequest, + data: bytes, + body_file: IO[bytes] | None = None, + ) -> HTTPResponse | None: + # Short circuit if we've been given an empty set of data + if not data: + return None + + # Previous versions of this library supported other serialization + # formats, but these have all been removed. + if not data.startswith(f"cc={self.serde_version},".encode()): + return None + + data = data[5:] + return self._loads_v4(request, data, body_file) + + def prepare_response( + self, + request: PreparedRequest, + cached: Mapping[str, Any], + body_file: IO[bytes] | None = None, + ) -> HTTPResponse | None: + """Verify our vary headers match and construct a real urllib3 + HTTPResponse object. + """ + # Special case the '*' Vary value as it means we cannot actually + # determine if the cached response is suitable for this request. + # This case is also handled in the controller code when creating + # a cache entry, but is left here for backwards compatibility. + if "*" in cached.get("vary", {}): + return None + + # Ensure that the Vary headers for the cached response match our + # request + for header, value in cached.get("vary", {}).items(): + if request.headers.get(header, None) != value: + return None + + body_raw = cached["response"].pop("body") + + headers: CaseInsensitiveDict[str] = CaseInsensitiveDict( + data=cached["response"]["headers"] + ) + if headers.get("transfer-encoding", "") == "chunked": + headers.pop("transfer-encoding") + + cached["response"]["headers"] = headers + + try: + body: IO[bytes] + if body_file is None: + body = io.BytesIO(body_raw) + else: + body = body_file + except TypeError: + # This can happen if cachecontrol serialized to v1 format (pickle) + # using Python 2. A Python 2 str(byte string) will be unpickled as + # a Python 3 str (unicode string), which will cause the above to + # fail with: + # + # TypeError: 'str' does not support the buffer interface + body = io.BytesIO(body_raw.encode("utf8")) + + # Discard any `strict` parameter serialized by older version of cachecontrol. + cached["response"].pop("strict", None) + + return HTTPResponse(body=body, preload_content=False, **cached["response"]) + + def _loads_v4( + self, + request: PreparedRequest, + data: bytes, + body_file: IO[bytes] | None = None, + ) -> HTTPResponse | None: + try: + cached = msgpack.loads(data, raw=False) + except ValueError: + return None + + return self.prepare_response(request, cached, body_file) diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/wrapper.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..f618bc363f12fb416b048e2a86cbddb6082874d6 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/cachecontrol/wrapper.py @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: 2015 Eric Larson +# +# SPDX-License-Identifier: Apache-2.0 +from __future__ import annotations + +from typing import TYPE_CHECKING, Collection + +from pip._vendor.cachecontrol.adapter import CacheControlAdapter +from pip._vendor.cachecontrol.cache import DictCache + +if TYPE_CHECKING: + from pip._vendor import requests + + from pip._vendor.cachecontrol.cache import BaseCache + from pip._vendor.cachecontrol.controller import CacheController + from pip._vendor.cachecontrol.heuristics import BaseHeuristic + from pip._vendor.cachecontrol.serialize import Serializer + + +def CacheControl( + sess: requests.Session, + cache: BaseCache | None = None, + cache_etags: bool = True, + serializer: Serializer | None = None, + heuristic: BaseHeuristic | None = None, + controller_class: type[CacheController] | None = None, + adapter_class: type[CacheControlAdapter] | None = None, + cacheable_methods: Collection[str] | None = None, +) -> requests.Session: + cache = DictCache() if cache is None else cache + adapter_class = adapter_class or CacheControlAdapter + adapter = adapter_class( + cache, + cache_etags=cache_etags, + serializer=serializer, + heuristic=heuristic, + controller_class=controller_class, + cacheable_methods=cacheable_methods, + ) + sess.mount("http://", adapter) + sess.mount("https://", adapter) + + return sess diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/distro/__main__.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/distro/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..0c01d5b08b6b44379b931d54d7fcf5221fdc9fde --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/distro/__main__.py @@ -0,0 +1,4 @@ +from .distro import main + +if __name__ == "__main__": + main() diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__init__.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b61510544a97a6a20051c0e0e60cb4c37a8e1bcd --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__init__.py @@ -0,0 +1,55 @@ +# ruff: noqa: F401 +import os + +from .exceptions import * # noqa: F403 +from .ext import ExtType, Timestamp + +version = (1, 1, 0) +__version__ = "1.1.0" + + +if os.environ.get("MSGPACK_PUREPYTHON"): + from .fallback import Packer, Unpacker, unpackb +else: + try: + from ._cmsgpack import Packer, Unpacker, unpackb + except ImportError: + from .fallback import Packer, Unpacker, unpackb + + +def pack(o, stream, **kwargs): + """ + Pack object `o` and write it to `stream` + + See :class:`Packer` for options. + """ + packer = Packer(**kwargs) + stream.write(packer.pack(o)) + + +def packb(o, **kwargs): + """ + Pack object `o` and return packed bytes + + See :class:`Packer` for options. + """ + return Packer(**kwargs).pack(o) + + +def unpack(stream, **kwargs): + """ + Unpack an object from `stream`. + + Raises `ExtraData` when `stream` contains extra bytes. + See :class:`Unpacker` for options. + """ + data = stream.read() + return unpackb(data, **kwargs) + + +# alias for compatibility to simplejson/marshal/pickle. +load = unpack +loads = unpackb + +dump = pack +dumps = packb diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eabd9bca1cb2a507bedc6a48def1eeebb81e359b Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__pycache__/ext.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__pycache__/ext.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fa59081b8ef6b4b28027e98b424b680777ffafd Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/__pycache__/ext.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/exceptions.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d2615cfdd0b914d064cdf7eecd45761e4bcaf6 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/exceptions.py @@ -0,0 +1,48 @@ +class UnpackException(Exception): + """Base class for some exceptions raised while unpacking. + + NOTE: unpack may raise exception other than subclass of + UnpackException. If you want to catch all error, catch + Exception instead. + """ + + +class BufferFull(UnpackException): + pass + + +class OutOfData(UnpackException): + pass + + +class FormatError(ValueError, UnpackException): + """Invalid msgpack format""" + + +class StackError(ValueError, UnpackException): + """Too nested""" + + +# Deprecated. Use ValueError instead +UnpackValueError = ValueError + + +class ExtraData(UnpackValueError): + """ExtraData is raised when there is trailing data. + + This exception is raised while only one-shot (not streaming) + unpack. + """ + + def __init__(self, unpacked, extra): + self.unpacked = unpacked + self.extra = extra + + def __str__(self): + return "unpack(b) received extra data." + + +# Deprecated. Use Exception instead to catch all exception during packing. +PackException = Exception +PackValueError = ValueError +PackOverflowError = OverflowError diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/ext.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/ext.py new file mode 100644 index 0000000000000000000000000000000000000000..9694819a7df1570ccbb41de065cb7052f9af8e79 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/ext.py @@ -0,0 +1,170 @@ +import datetime +import struct +from collections import namedtuple + + +class ExtType(namedtuple("ExtType", "code data")): + """ExtType represents ext type in msgpack.""" + + def __new__(cls, code, data): + if not isinstance(code, int): + raise TypeError("code must be int") + if not isinstance(data, bytes): + raise TypeError("data must be bytes") + if not 0 <= code <= 127: + raise ValueError("code must be 0~127") + return super().__new__(cls, code, data) + + +class Timestamp: + """Timestamp represents the Timestamp extension type in msgpack. + + When built with Cython, msgpack uses C methods to pack and unpack `Timestamp`. + When using pure-Python msgpack, :func:`to_bytes` and :func:`from_bytes` are used to pack and + unpack `Timestamp`. + + This class is immutable: Do not override seconds and nanoseconds. + """ + + __slots__ = ["seconds", "nanoseconds"] + + def __init__(self, seconds, nanoseconds=0): + """Initialize a Timestamp object. + + :param int seconds: + Number of seconds since the UNIX epoch (00:00:00 UTC Jan 1 1970, minus leap seconds). + May be negative. + + :param int nanoseconds: + Number of nanoseconds to add to `seconds` to get fractional time. + Maximum is 999_999_999. Default is 0. + + Note: Negative times (before the UNIX epoch) are represented as neg. seconds + pos. ns. + """ + if not isinstance(seconds, int): + raise TypeError("seconds must be an integer") + if not isinstance(nanoseconds, int): + raise TypeError("nanoseconds must be an integer") + if not (0 <= nanoseconds < 10**9): + raise ValueError("nanoseconds must be a non-negative integer less than 999999999.") + self.seconds = seconds + self.nanoseconds = nanoseconds + + def __repr__(self): + """String representation of Timestamp.""" + return f"Timestamp(seconds={self.seconds}, nanoseconds={self.nanoseconds})" + + def __eq__(self, other): + """Check for equality with another Timestamp object""" + if type(other) is self.__class__: + return self.seconds == other.seconds and self.nanoseconds == other.nanoseconds + return False + + def __ne__(self, other): + """not-equals method (see :func:`__eq__()`)""" + return not self.__eq__(other) + + def __hash__(self): + return hash((self.seconds, self.nanoseconds)) + + @staticmethod + def from_bytes(b): + """Unpack bytes into a `Timestamp` object. + + Used for pure-Python msgpack unpacking. + + :param b: Payload from msgpack ext message with code -1 + :type b: bytes + + :returns: Timestamp object unpacked from msgpack ext payload + :rtype: Timestamp + """ + if len(b) == 4: + seconds = struct.unpack("!L", b)[0] + nanoseconds = 0 + elif len(b) == 8: + data64 = struct.unpack("!Q", b)[0] + seconds = data64 & 0x00000003FFFFFFFF + nanoseconds = data64 >> 34 + elif len(b) == 12: + nanoseconds, seconds = struct.unpack("!Iq", b) + else: + raise ValueError( + "Timestamp type can only be created from 32, 64, or 96-bit byte objects" + ) + return Timestamp(seconds, nanoseconds) + + def to_bytes(self): + """Pack this Timestamp object into bytes. + + Used for pure-Python msgpack packing. + + :returns data: Payload for EXT message with code -1 (timestamp type) + :rtype: bytes + """ + if (self.seconds >> 34) == 0: # seconds is non-negative and fits in 34 bits + data64 = self.nanoseconds << 34 | self.seconds + if data64 & 0xFFFFFFFF00000000 == 0: + # nanoseconds is zero and seconds < 2**32, so timestamp 32 + data = struct.pack("!L", data64) + else: + # timestamp 64 + data = struct.pack("!Q", data64) + else: + # timestamp 96 + data = struct.pack("!Iq", self.nanoseconds, self.seconds) + return data + + @staticmethod + def from_unix(unix_sec): + """Create a Timestamp from posix timestamp in seconds. + + :param unix_float: Posix timestamp in seconds. + :type unix_float: int or float + """ + seconds = int(unix_sec // 1) + nanoseconds = int((unix_sec % 1) * 10**9) + return Timestamp(seconds, nanoseconds) + + def to_unix(self): + """Get the timestamp as a floating-point value. + + :returns: posix timestamp + :rtype: float + """ + return self.seconds + self.nanoseconds / 1e9 + + @staticmethod + def from_unix_nano(unix_ns): + """Create a Timestamp from posix timestamp in nanoseconds. + + :param int unix_ns: Posix timestamp in nanoseconds. + :rtype: Timestamp + """ + return Timestamp(*divmod(unix_ns, 10**9)) + + def to_unix_nano(self): + """Get the timestamp as a unixtime in nanoseconds. + + :returns: posix timestamp in nanoseconds + :rtype: int + """ + return self.seconds * 10**9 + self.nanoseconds + + def to_datetime(self): + """Get the timestamp as a UTC datetime. + + :rtype: `datetime.datetime` + """ + utc = datetime.timezone.utc + return datetime.datetime.fromtimestamp(0, utc) + datetime.timedelta( + seconds=self.seconds, microseconds=self.nanoseconds // 1000 + ) + + @staticmethod + def from_datetime(dt): + """Create a Timestamp from datetime with tzinfo. + + :rtype: Timestamp + """ + return Timestamp(seconds=int(dt.timestamp()), nanoseconds=dt.microsecond * 1000) diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/fallback.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..b02e47cfb91a54a7205881ee87a5db2ea8d049a7 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/msgpack/fallback.py @@ -0,0 +1,929 @@ +"""Fallback pure Python implementation of msgpack""" + +import struct +import sys +from datetime import datetime as _DateTime + +if hasattr(sys, "pypy_version_info"): + from __pypy__ import newlist_hint + from __pypy__.builders import BytesBuilder + + _USING_STRINGBUILDER = True + + class BytesIO: + def __init__(self, s=b""): + if s: + self.builder = BytesBuilder(len(s)) + self.builder.append(s) + else: + self.builder = BytesBuilder() + + def write(self, s): + if isinstance(s, memoryview): + s = s.tobytes() + elif isinstance(s, bytearray): + s = bytes(s) + self.builder.append(s) + + def getvalue(self): + return self.builder.build() + +else: + from io import BytesIO + + _USING_STRINGBUILDER = False + + def newlist_hint(size): + return [] + + +from .exceptions import BufferFull, ExtraData, FormatError, OutOfData, StackError +from .ext import ExtType, Timestamp + +EX_SKIP = 0 +EX_CONSTRUCT = 1 +EX_READ_ARRAY_HEADER = 2 +EX_READ_MAP_HEADER = 3 + +TYPE_IMMEDIATE = 0 +TYPE_ARRAY = 1 +TYPE_MAP = 2 +TYPE_RAW = 3 +TYPE_BIN = 4 +TYPE_EXT = 5 + +DEFAULT_RECURSE_LIMIT = 511 + + +def _check_type_strict(obj, t, type=type, tuple=tuple): + if type(t) is tuple: + return type(obj) in t + else: + return type(obj) is t + + +def _get_data_from_buffer(obj): + view = memoryview(obj) + if view.itemsize != 1: + raise ValueError("cannot unpack from multi-byte object") + return view + + +def unpackb(packed, **kwargs): + """ + Unpack an object from `packed`. + + Raises ``ExtraData`` when *packed* contains extra bytes. + Raises ``ValueError`` when *packed* is incomplete. + Raises ``FormatError`` when *packed* is not valid msgpack. + Raises ``StackError`` when *packed* contains too nested. + Other exceptions can be raised during unpacking. + + See :class:`Unpacker` for options. + """ + unpacker = Unpacker(None, max_buffer_size=len(packed), **kwargs) + unpacker.feed(packed) + try: + ret = unpacker._unpack() + except OutOfData: + raise ValueError("Unpack failed: incomplete input") + except RecursionError: + raise StackError + if unpacker._got_extradata(): + raise ExtraData(ret, unpacker._get_extradata()) + return ret + + +_NO_FORMAT_USED = "" +_MSGPACK_HEADERS = { + 0xC4: (1, _NO_FORMAT_USED, TYPE_BIN), + 0xC5: (2, ">H", TYPE_BIN), + 0xC6: (4, ">I", TYPE_BIN), + 0xC7: (2, "Bb", TYPE_EXT), + 0xC8: (3, ">Hb", TYPE_EXT), + 0xC9: (5, ">Ib", TYPE_EXT), + 0xCA: (4, ">f"), + 0xCB: (8, ">d"), + 0xCC: (1, _NO_FORMAT_USED), + 0xCD: (2, ">H"), + 0xCE: (4, ">I"), + 0xCF: (8, ">Q"), + 0xD0: (1, "b"), + 0xD1: (2, ">h"), + 0xD2: (4, ">i"), + 0xD3: (8, ">q"), + 0xD4: (1, "b1s", TYPE_EXT), + 0xD5: (2, "b2s", TYPE_EXT), + 0xD6: (4, "b4s", TYPE_EXT), + 0xD7: (8, "b8s", TYPE_EXT), + 0xD8: (16, "b16s", TYPE_EXT), + 0xD9: (1, _NO_FORMAT_USED, TYPE_RAW), + 0xDA: (2, ">H", TYPE_RAW), + 0xDB: (4, ">I", TYPE_RAW), + 0xDC: (2, ">H", TYPE_ARRAY), + 0xDD: (4, ">I", TYPE_ARRAY), + 0xDE: (2, ">H", TYPE_MAP), + 0xDF: (4, ">I", TYPE_MAP), +} + + +class Unpacker: + """Streaming unpacker. + + Arguments: + + :param file_like: + File-like object having `.read(n)` method. + If specified, unpacker reads serialized data from it and `.feed()` is not usable. + + :param int read_size: + Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`) + + :param bool use_list: + If true, unpack msgpack array to Python list. + Otherwise, unpack to Python tuple. (default: True) + + :param bool raw: + If true, unpack msgpack raw to Python bytes. + Otherwise, unpack to Python str by decoding with UTF-8 encoding (default). + + :param int timestamp: + Control how timestamp type is unpacked: + + 0 - Timestamp + 1 - float (Seconds from the EPOCH) + 2 - int (Nanoseconds from the EPOCH) + 3 - datetime.datetime (UTC). + + :param bool strict_map_key: + If true (default), only str or bytes are accepted for map (dict) keys. + + :param object_hook: + When specified, it should be callable. + Unpacker calls it with a dict argument after unpacking msgpack map. + (See also simplejson) + + :param object_pairs_hook: + When specified, it should be callable. + Unpacker calls it with a list of key-value pairs after unpacking msgpack map. + (See also simplejson) + + :param str unicode_errors: + The error handler for decoding unicode. (default: 'strict') + This option should be used only when you have msgpack data which + contains invalid UTF-8 string. + + :param int max_buffer_size: + Limits size of data waiting unpacked. 0 means 2**32-1. + The default value is 100*1024*1024 (100MiB). + Raises `BufferFull` exception when it is insufficient. + You should set this parameter when unpacking data from untrusted source. + + :param int max_str_len: + Deprecated, use *max_buffer_size* instead. + Limits max length of str. (default: max_buffer_size) + + :param int max_bin_len: + Deprecated, use *max_buffer_size* instead. + Limits max length of bin. (default: max_buffer_size) + + :param int max_array_len: + Limits max length of array. + (default: max_buffer_size) + + :param int max_map_len: + Limits max length of map. + (default: max_buffer_size//2) + + :param int max_ext_len: + Deprecated, use *max_buffer_size* instead. + Limits max size of ext type. (default: max_buffer_size) + + Example of streaming deserialize from file-like object:: + + unpacker = Unpacker(file_like) + for o in unpacker: + process(o) + + Example of streaming deserialize from socket:: + + unpacker = Unpacker() + while True: + buf = sock.recv(1024**2) + if not buf: + break + unpacker.feed(buf) + for o in unpacker: + process(o) + + Raises ``ExtraData`` when *packed* contains extra bytes. + Raises ``OutOfData`` when *packed* is incomplete. + Raises ``FormatError`` when *packed* is not valid msgpack. + Raises ``StackError`` when *packed* contains too nested. + Other exceptions can be raised during unpacking. + """ + + def __init__( + self, + file_like=None, + *, + read_size=0, + use_list=True, + raw=False, + timestamp=0, + strict_map_key=True, + object_hook=None, + object_pairs_hook=None, + list_hook=None, + unicode_errors=None, + max_buffer_size=100 * 1024 * 1024, + ext_hook=ExtType, + max_str_len=-1, + max_bin_len=-1, + max_array_len=-1, + max_map_len=-1, + max_ext_len=-1, + ): + if unicode_errors is None: + unicode_errors = "strict" + + if file_like is None: + self._feeding = True + else: + if not callable(file_like.read): + raise TypeError("`file_like.read` must be callable") + self.file_like = file_like + self._feeding = False + + #: array of bytes fed. + self._buffer = bytearray() + #: Which position we currently reads + self._buff_i = 0 + + # When Unpacker is used as an iterable, between the calls to next(), + # the buffer is not "consumed" completely, for efficiency sake. + # Instead, it is done sloppily. To make sure we raise BufferFull at + # the correct moments, we have to keep track of how sloppy we were. + # Furthermore, when the buffer is incomplete (that is: in the case + # we raise an OutOfData) we need to rollback the buffer to the correct + # state, which _buf_checkpoint records. + self._buf_checkpoint = 0 + + if not max_buffer_size: + max_buffer_size = 2**31 - 1 + if max_str_len == -1: + max_str_len = max_buffer_size + if max_bin_len == -1: + max_bin_len = max_buffer_size + if max_array_len == -1: + max_array_len = max_buffer_size + if max_map_len == -1: + max_map_len = max_buffer_size // 2 + if max_ext_len == -1: + max_ext_len = max_buffer_size + + self._max_buffer_size = max_buffer_size + if read_size > self._max_buffer_size: + raise ValueError("read_size must be smaller than max_buffer_size") + self._read_size = read_size or min(self._max_buffer_size, 16 * 1024) + self._raw = bool(raw) + self._strict_map_key = bool(strict_map_key) + self._unicode_errors = unicode_errors + self._use_list = use_list + if not (0 <= timestamp <= 3): + raise ValueError("timestamp must be 0..3") + self._timestamp = timestamp + self._list_hook = list_hook + self._object_hook = object_hook + self._object_pairs_hook = object_pairs_hook + self._ext_hook = ext_hook + self._max_str_len = max_str_len + self._max_bin_len = max_bin_len + self._max_array_len = max_array_len + self._max_map_len = max_map_len + self._max_ext_len = max_ext_len + self._stream_offset = 0 + + if list_hook is not None and not callable(list_hook): + raise TypeError("`list_hook` is not callable") + if object_hook is not None and not callable(object_hook): + raise TypeError("`object_hook` is not callable") + if object_pairs_hook is not None and not callable(object_pairs_hook): + raise TypeError("`object_pairs_hook` is not callable") + if object_hook is not None and object_pairs_hook is not None: + raise TypeError("object_pairs_hook and object_hook are mutually exclusive") + if not callable(ext_hook): + raise TypeError("`ext_hook` is not callable") + + def feed(self, next_bytes): + assert self._feeding + view = _get_data_from_buffer(next_bytes) + if len(self._buffer) - self._buff_i + len(view) > self._max_buffer_size: + raise BufferFull + + # Strip buffer before checkpoint before reading file. + if self._buf_checkpoint > 0: + del self._buffer[: self._buf_checkpoint] + self._buff_i -= self._buf_checkpoint + self._buf_checkpoint = 0 + + # Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython + self._buffer.extend(view) + view.release() + + def _consume(self): + """Gets rid of the used parts of the buffer.""" + self._stream_offset += self._buff_i - self._buf_checkpoint + self._buf_checkpoint = self._buff_i + + def _got_extradata(self): + return self._buff_i < len(self._buffer) + + def _get_extradata(self): + return self._buffer[self._buff_i :] + + def read_bytes(self, n): + ret = self._read(n, raise_outofdata=False) + self._consume() + return ret + + def _read(self, n, raise_outofdata=True): + # (int) -> bytearray + self._reserve(n, raise_outofdata=raise_outofdata) + i = self._buff_i + ret = self._buffer[i : i + n] + self._buff_i = i + len(ret) + return ret + + def _reserve(self, n, raise_outofdata=True): + remain_bytes = len(self._buffer) - self._buff_i - n + + # Fast path: buffer has n bytes already + if remain_bytes >= 0: + return + + if self._feeding: + self._buff_i = self._buf_checkpoint + raise OutOfData + + # Strip buffer before checkpoint before reading file. + if self._buf_checkpoint > 0: + del self._buffer[: self._buf_checkpoint] + self._buff_i -= self._buf_checkpoint + self._buf_checkpoint = 0 + + # Read from file + remain_bytes = -remain_bytes + if remain_bytes + len(self._buffer) > self._max_buffer_size: + raise BufferFull + while remain_bytes > 0: + to_read_bytes = max(self._read_size, remain_bytes) + read_data = self.file_like.read(to_read_bytes) + if not read_data: + break + assert isinstance(read_data, bytes) + self._buffer += read_data + remain_bytes -= len(read_data) + + if len(self._buffer) < n + self._buff_i and raise_outofdata: + self._buff_i = 0 # rollback + raise OutOfData + + def _read_header(self): + typ = TYPE_IMMEDIATE + n = 0 + obj = None + self._reserve(1) + b = self._buffer[self._buff_i] + self._buff_i += 1 + if b & 0b10000000 == 0: + obj = b + elif b & 0b11100000 == 0b11100000: + obj = -1 - (b ^ 0xFF) + elif b & 0b11100000 == 0b10100000: + n = b & 0b00011111 + typ = TYPE_RAW + if n > self._max_str_len: + raise ValueError(f"{n} exceeds max_str_len({self._max_str_len})") + obj = self._read(n) + elif b & 0b11110000 == 0b10010000: + n = b & 0b00001111 + typ = TYPE_ARRAY + if n > self._max_array_len: + raise ValueError(f"{n} exceeds max_array_len({self._max_array_len})") + elif b & 0b11110000 == 0b10000000: + n = b & 0b00001111 + typ = TYPE_MAP + if n > self._max_map_len: + raise ValueError(f"{n} exceeds max_map_len({self._max_map_len})") + elif b == 0xC0: + obj = None + elif b == 0xC2: + obj = False + elif b == 0xC3: + obj = True + elif 0xC4 <= b <= 0xC6: + size, fmt, typ = _MSGPACK_HEADERS[b] + self._reserve(size) + if len(fmt) > 0: + n = struct.unpack_from(fmt, self._buffer, self._buff_i)[0] + else: + n = self._buffer[self._buff_i] + self._buff_i += size + if n > self._max_bin_len: + raise ValueError(f"{n} exceeds max_bin_len({self._max_bin_len})") + obj = self._read(n) + elif 0xC7 <= b <= 0xC9: + size, fmt, typ = _MSGPACK_HEADERS[b] + self._reserve(size) + L, n = struct.unpack_from(fmt, self._buffer, self._buff_i) + self._buff_i += size + if L > self._max_ext_len: + raise ValueError(f"{L} exceeds max_ext_len({self._max_ext_len})") + obj = self._read(L) + elif 0xCA <= b <= 0xD3: + size, fmt = _MSGPACK_HEADERS[b] + self._reserve(size) + if len(fmt) > 0: + obj = struct.unpack_from(fmt, self._buffer, self._buff_i)[0] + else: + obj = self._buffer[self._buff_i] + self._buff_i += size + elif 0xD4 <= b <= 0xD8: + size, fmt, typ = _MSGPACK_HEADERS[b] + if self._max_ext_len < size: + raise ValueError(f"{size} exceeds max_ext_len({self._max_ext_len})") + self._reserve(size + 1) + n, obj = struct.unpack_from(fmt, self._buffer, self._buff_i) + self._buff_i += size + 1 + elif 0xD9 <= b <= 0xDB: + size, fmt, typ = _MSGPACK_HEADERS[b] + self._reserve(size) + if len(fmt) > 0: + (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i) + else: + n = self._buffer[self._buff_i] + self._buff_i += size + if n > self._max_str_len: + raise ValueError(f"{n} exceeds max_str_len({self._max_str_len})") + obj = self._read(n) + elif 0xDC <= b <= 0xDD: + size, fmt, typ = _MSGPACK_HEADERS[b] + self._reserve(size) + (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i) + self._buff_i += size + if n > self._max_array_len: + raise ValueError(f"{n} exceeds max_array_len({self._max_array_len})") + elif 0xDE <= b <= 0xDF: + size, fmt, typ = _MSGPACK_HEADERS[b] + self._reserve(size) + (n,) = struct.unpack_from(fmt, self._buffer, self._buff_i) + self._buff_i += size + if n > self._max_map_len: + raise ValueError(f"{n} exceeds max_map_len({self._max_map_len})") + else: + raise FormatError("Unknown header: 0x%x" % b) + return typ, n, obj + + def _unpack(self, execute=EX_CONSTRUCT): + typ, n, obj = self._read_header() + + if execute == EX_READ_ARRAY_HEADER: + if typ != TYPE_ARRAY: + raise ValueError("Expected array") + return n + if execute == EX_READ_MAP_HEADER: + if typ != TYPE_MAP: + raise ValueError("Expected map") + return n + # TODO should we eliminate the recursion? + if typ == TYPE_ARRAY: + if execute == EX_SKIP: + for i in range(n): + # TODO check whether we need to call `list_hook` + self._unpack(EX_SKIP) + return + ret = newlist_hint(n) + for i in range(n): + ret.append(self._unpack(EX_CONSTRUCT)) + if self._list_hook is not None: + ret = self._list_hook(ret) + # TODO is the interaction between `list_hook` and `use_list` ok? + return ret if self._use_list else tuple(ret) + if typ == TYPE_MAP: + if execute == EX_SKIP: + for i in range(n): + # TODO check whether we need to call hooks + self._unpack(EX_SKIP) + self._unpack(EX_SKIP) + return + if self._object_pairs_hook is not None: + ret = self._object_pairs_hook( + (self._unpack(EX_CONSTRUCT), self._unpack(EX_CONSTRUCT)) for _ in range(n) + ) + else: + ret = {} + for _ in range(n): + key = self._unpack(EX_CONSTRUCT) + if self._strict_map_key and type(key) not in (str, bytes): + raise ValueError("%s is not allowed for map key" % str(type(key))) + if isinstance(key, str): + key = sys.intern(key) + ret[key] = self._unpack(EX_CONSTRUCT) + if self._object_hook is not None: + ret = self._object_hook(ret) + return ret + if execute == EX_SKIP: + return + if typ == TYPE_RAW: + if self._raw: + obj = bytes(obj) + else: + obj = obj.decode("utf_8", self._unicode_errors) + return obj + if typ == TYPE_BIN: + return bytes(obj) + if typ == TYPE_EXT: + if n == -1: # timestamp + ts = Timestamp.from_bytes(bytes(obj)) + if self._timestamp == 1: + return ts.to_unix() + elif self._timestamp == 2: + return ts.to_unix_nano() + elif self._timestamp == 3: + return ts.to_datetime() + else: + return ts + else: + return self._ext_hook(n, bytes(obj)) + assert typ == TYPE_IMMEDIATE + return obj + + def __iter__(self): + return self + + def __next__(self): + try: + ret = self._unpack(EX_CONSTRUCT) + self._consume() + return ret + except OutOfData: + self._consume() + raise StopIteration + except RecursionError: + raise StackError + + next = __next__ + + def skip(self): + self._unpack(EX_SKIP) + self._consume() + + def unpack(self): + try: + ret = self._unpack(EX_CONSTRUCT) + except RecursionError: + raise StackError + self._consume() + return ret + + def read_array_header(self): + ret = self._unpack(EX_READ_ARRAY_HEADER) + self._consume() + return ret + + def read_map_header(self): + ret = self._unpack(EX_READ_MAP_HEADER) + self._consume() + return ret + + def tell(self): + return self._stream_offset + + +class Packer: + """ + MessagePack Packer + + Usage:: + + packer = Packer() + astream.write(packer.pack(a)) + astream.write(packer.pack(b)) + + Packer's constructor has some keyword arguments: + + :param default: + When specified, it should be callable. + Convert user type to builtin type that Packer supports. + See also simplejson's document. + + :param bool use_single_float: + Use single precision float type for float. (default: False) + + :param bool autoreset: + Reset buffer after each pack and return its content as `bytes`. (default: True). + If set this to false, use `bytes()` to get content and `.reset()` to clear buffer. + + :param bool use_bin_type: + Use bin type introduced in msgpack spec 2.0 for bytes. + It also enables str8 type for unicode. (default: True) + + :param bool strict_types: + If set to true, types will be checked to be exact. Derived classes + from serializable types will not be serialized and will be + treated as unsupported type and forwarded to default. + Additionally tuples will not be serialized as lists. + This is useful when trying to implement accurate serialization + for python types. + + :param bool datetime: + If set to true, datetime with tzinfo is packed into Timestamp type. + Note that the tzinfo is stripped in the timestamp. + You can get UTC datetime with `timestamp=3` option of the Unpacker. + + :param str unicode_errors: + The error handler for encoding unicode. (default: 'strict') + DO NOT USE THIS!! This option is kept for very specific usage. + + :param int buf_size: + Internal buffer size. This option is used only for C implementation. + """ + + def __init__( + self, + *, + default=None, + use_single_float=False, + autoreset=True, + use_bin_type=True, + strict_types=False, + datetime=False, + unicode_errors=None, + buf_size=None, + ): + self._strict_types = strict_types + self._use_float = use_single_float + self._autoreset = autoreset + self._use_bin_type = use_bin_type + self._buffer = BytesIO() + self._datetime = bool(datetime) + self._unicode_errors = unicode_errors or "strict" + if default is not None and not callable(default): + raise TypeError("default must be callable") + self._default = default + + def _pack( + self, + obj, + nest_limit=DEFAULT_RECURSE_LIMIT, + check=isinstance, + check_type_strict=_check_type_strict, + ): + default_used = False + if self._strict_types: + check = check_type_strict + list_types = list + else: + list_types = (list, tuple) + while True: + if nest_limit < 0: + raise ValueError("recursion limit exceeded") + if obj is None: + return self._buffer.write(b"\xc0") + if check(obj, bool): + if obj: + return self._buffer.write(b"\xc3") + return self._buffer.write(b"\xc2") + if check(obj, int): + if 0 <= obj < 0x80: + return self._buffer.write(struct.pack("B", obj)) + if -0x20 <= obj < 0: + return self._buffer.write(struct.pack("b", obj)) + if 0x80 <= obj <= 0xFF: + return self._buffer.write(struct.pack("BB", 0xCC, obj)) + if -0x80 <= obj < 0: + return self._buffer.write(struct.pack(">Bb", 0xD0, obj)) + if 0xFF < obj <= 0xFFFF: + return self._buffer.write(struct.pack(">BH", 0xCD, obj)) + if -0x8000 <= obj < -0x80: + return self._buffer.write(struct.pack(">Bh", 0xD1, obj)) + if 0xFFFF < obj <= 0xFFFFFFFF: + return self._buffer.write(struct.pack(">BI", 0xCE, obj)) + if -0x80000000 <= obj < -0x8000: + return self._buffer.write(struct.pack(">Bi", 0xD2, obj)) + if 0xFFFFFFFF < obj <= 0xFFFFFFFFFFFFFFFF: + return self._buffer.write(struct.pack(">BQ", 0xCF, obj)) + if -0x8000000000000000 <= obj < -0x80000000: + return self._buffer.write(struct.pack(">Bq", 0xD3, obj)) + if not default_used and self._default is not None: + obj = self._default(obj) + default_used = True + continue + raise OverflowError("Integer value out of range") + if check(obj, (bytes, bytearray)): + n = len(obj) + if n >= 2**32: + raise ValueError("%s is too large" % type(obj).__name__) + self._pack_bin_header(n) + return self._buffer.write(obj) + if check(obj, str): + obj = obj.encode("utf-8", self._unicode_errors) + n = len(obj) + if n >= 2**32: + raise ValueError("String is too large") + self._pack_raw_header(n) + return self._buffer.write(obj) + if check(obj, memoryview): + n = obj.nbytes + if n >= 2**32: + raise ValueError("Memoryview is too large") + self._pack_bin_header(n) + return self._buffer.write(obj) + if check(obj, float): + if self._use_float: + return self._buffer.write(struct.pack(">Bf", 0xCA, obj)) + return self._buffer.write(struct.pack(">Bd", 0xCB, obj)) + if check(obj, (ExtType, Timestamp)): + if check(obj, Timestamp): + code = -1 + data = obj.to_bytes() + else: + code = obj.code + data = obj.data + assert isinstance(code, int) + assert isinstance(data, bytes) + L = len(data) + if L == 1: + self._buffer.write(b"\xd4") + elif L == 2: + self._buffer.write(b"\xd5") + elif L == 4: + self._buffer.write(b"\xd6") + elif L == 8: + self._buffer.write(b"\xd7") + elif L == 16: + self._buffer.write(b"\xd8") + elif L <= 0xFF: + self._buffer.write(struct.pack(">BB", 0xC7, L)) + elif L <= 0xFFFF: + self._buffer.write(struct.pack(">BH", 0xC8, L)) + else: + self._buffer.write(struct.pack(">BI", 0xC9, L)) + self._buffer.write(struct.pack("b", code)) + self._buffer.write(data) + return + if check(obj, list_types): + n = len(obj) + self._pack_array_header(n) + for i in range(n): + self._pack(obj[i], nest_limit - 1) + return + if check(obj, dict): + return self._pack_map_pairs(len(obj), obj.items(), nest_limit - 1) + + if self._datetime and check(obj, _DateTime) and obj.tzinfo is not None: + obj = Timestamp.from_datetime(obj) + default_used = 1 + continue + + if not default_used and self._default is not None: + obj = self._default(obj) + default_used = 1 + continue + + if self._datetime and check(obj, _DateTime): + raise ValueError(f"Cannot serialize {obj!r} where tzinfo=None") + + raise TypeError(f"Cannot serialize {obj!r}") + + def pack(self, obj): + try: + self._pack(obj) + except: + self._buffer = BytesIO() # force reset + raise + if self._autoreset: + ret = self._buffer.getvalue() + self._buffer = BytesIO() + return ret + + def pack_map_pairs(self, pairs): + self._pack_map_pairs(len(pairs), pairs) + if self._autoreset: + ret = self._buffer.getvalue() + self._buffer = BytesIO() + return ret + + def pack_array_header(self, n): + if n >= 2**32: + raise ValueError + self._pack_array_header(n) + if self._autoreset: + ret = self._buffer.getvalue() + self._buffer = BytesIO() + return ret + + def pack_map_header(self, n): + if n >= 2**32: + raise ValueError + self._pack_map_header(n) + if self._autoreset: + ret = self._buffer.getvalue() + self._buffer = BytesIO() + return ret + + def pack_ext_type(self, typecode, data): + if not isinstance(typecode, int): + raise TypeError("typecode must have int type.") + if not 0 <= typecode <= 127: + raise ValueError("typecode should be 0-127") + if not isinstance(data, bytes): + raise TypeError("data must have bytes type") + L = len(data) + if L > 0xFFFFFFFF: + raise ValueError("Too large data") + if L == 1: + self._buffer.write(b"\xd4") + elif L == 2: + self._buffer.write(b"\xd5") + elif L == 4: + self._buffer.write(b"\xd6") + elif L == 8: + self._buffer.write(b"\xd7") + elif L == 16: + self._buffer.write(b"\xd8") + elif L <= 0xFF: + self._buffer.write(b"\xc7" + struct.pack("B", L)) + elif L <= 0xFFFF: + self._buffer.write(b"\xc8" + struct.pack(">H", L)) + else: + self._buffer.write(b"\xc9" + struct.pack(">I", L)) + self._buffer.write(struct.pack("B", typecode)) + self._buffer.write(data) + + def _pack_array_header(self, n): + if n <= 0x0F: + return self._buffer.write(struct.pack("B", 0x90 + n)) + if n <= 0xFFFF: + return self._buffer.write(struct.pack(">BH", 0xDC, n)) + if n <= 0xFFFFFFFF: + return self._buffer.write(struct.pack(">BI", 0xDD, n)) + raise ValueError("Array is too large") + + def _pack_map_header(self, n): + if n <= 0x0F: + return self._buffer.write(struct.pack("B", 0x80 + n)) + if n <= 0xFFFF: + return self._buffer.write(struct.pack(">BH", 0xDE, n)) + if n <= 0xFFFFFFFF: + return self._buffer.write(struct.pack(">BI", 0xDF, n)) + raise ValueError("Dict is too large") + + def _pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT): + self._pack_map_header(n) + for k, v in pairs: + self._pack(k, nest_limit - 1) + self._pack(v, nest_limit - 1) + + def _pack_raw_header(self, n): + if n <= 0x1F: + self._buffer.write(struct.pack("B", 0xA0 + n)) + elif self._use_bin_type and n <= 0xFF: + self._buffer.write(struct.pack(">BB", 0xD9, n)) + elif n <= 0xFFFF: + self._buffer.write(struct.pack(">BH", 0xDA, n)) + elif n <= 0xFFFFFFFF: + self._buffer.write(struct.pack(">BI", 0xDB, n)) + else: + raise ValueError("Raw is too large") + + def _pack_bin_header(self, n): + if not self._use_bin_type: + return self._pack_raw_header(n) + elif n <= 0xFF: + return self._buffer.write(struct.pack(">BB", 0xC4, n)) + elif n <= 0xFFFF: + return self._buffer.write(struct.pack(">BH", 0xC5, n)) + elif n <= 0xFFFFFFFF: + return self._buffer.write(struct.pack(">BI", 0xC6, n)) + else: + raise ValueError("Bin is too large") + + def bytes(self): + """Return internal buffer contents as bytes object""" + return self._buffer.getvalue() + + def reset(self): + """Reset internal buffer. + + This method is useful only when autoreset=False. + """ + self._buffer = BytesIO() + + def getbuffer(self): + """Return view of internal buffer.""" + if _USING_STRINGBUILDER: + return memoryview(self.bytes()) + else: + return self._buffer.getbuffer() diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa34bf95fe991e1987860606709ca1e093f36a1b Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/__init__.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b829c0700d22185160ceb36422f4e2518e147ea2 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37b87709b060b419f80f18e639993d5097f2ae20 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/__pycache__/collections_abc.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/collections_abc.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/collections_abc.py new file mode 100644 index 0000000000000000000000000000000000000000..1becc5093c5ab8e196bb9fee415e2381e7158fc3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/compat/collections_abc.py @@ -0,0 +1,6 @@ +__all__ = ["Mapping", "Sequence"] + +try: + from collections.abc import Mapping, Sequence +except ImportError: + from collections import Mapping, Sequence diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/resolvers.py b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/resolvers.py new file mode 100644 index 0000000000000000000000000000000000000000..2c3d0e306f91f9dfac1843b40babd223766bbf50 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/pip/_vendor/resolvelib/resolvers.py @@ -0,0 +1,547 @@ +import collections +import itertools +import operator + +from .providers import AbstractResolver +from .structs import DirectedGraph, IteratorMapping, build_iter_view + +RequirementInformation = collections.namedtuple( + "RequirementInformation", ["requirement", "parent"] +) + + +class ResolverException(Exception): + """A base class for all exceptions raised by this module. + + Exceptions derived by this class should all be handled in this module. Any + bubbling pass the resolver should be treated as a bug. + """ + + +class RequirementsConflicted(ResolverException): + def __init__(self, criterion): + super(RequirementsConflicted, self).__init__(criterion) + self.criterion = criterion + + def __str__(self): + return "Requirements conflict: {}".format( + ", ".join(repr(r) for r in self.criterion.iter_requirement()), + ) + + +class InconsistentCandidate(ResolverException): + def __init__(self, candidate, criterion): + super(InconsistentCandidate, self).__init__(candidate, criterion) + self.candidate = candidate + self.criterion = criterion + + def __str__(self): + return "Provided candidate {!r} does not satisfy {}".format( + self.candidate, + ", ".join(repr(r) for r in self.criterion.iter_requirement()), + ) + + +class Criterion(object): + """Representation of possible resolution results of a package. + + This holds three attributes: + + * `information` is a collection of `RequirementInformation` pairs. + Each pair is a requirement contributing to this criterion, and the + candidate that provides the requirement. + * `incompatibilities` is a collection of all known not-to-work candidates + to exclude from consideration. + * `candidates` is a collection containing all possible candidates deducted + from the union of contributing requirements and known incompatibilities. + It should never be empty, except when the criterion is an attribute of a + raised `RequirementsConflicted` (in which case it is always empty). + + .. note:: + This class is intended to be externally immutable. **Do not** mutate + any of its attribute containers. + """ + + def __init__(self, candidates, information, incompatibilities): + self.candidates = candidates + self.information = information + self.incompatibilities = incompatibilities + + def __repr__(self): + requirements = ", ".join( + "({!r}, via={!r})".format(req, parent) + for req, parent in self.information + ) + return "Criterion({})".format(requirements) + + def iter_requirement(self): + return (i.requirement for i in self.information) + + def iter_parent(self): + return (i.parent for i in self.information) + + +class ResolutionError(ResolverException): + pass + + +class ResolutionImpossible(ResolutionError): + def __init__(self, causes): + super(ResolutionImpossible, self).__init__(causes) + # causes is a list of RequirementInformation objects + self.causes = causes + + +class ResolutionTooDeep(ResolutionError): + def __init__(self, round_count): + super(ResolutionTooDeep, self).__init__(round_count) + self.round_count = round_count + + +# Resolution state in a round. +State = collections.namedtuple("State", "mapping criteria backtrack_causes") + + +class Resolution(object): + """Stateful resolution object. + + This is designed as a one-off object that holds information to kick start + the resolution process, and holds the results afterwards. + """ + + def __init__(self, provider, reporter): + self._p = provider + self._r = reporter + self._states = [] + + @property + def state(self): + try: + return self._states[-1] + except IndexError: + raise AttributeError("state") + + def _push_new_state(self): + """Push a new state into history. + + This new state will be used to hold resolution results of the next + coming round. + """ + base = self._states[-1] + state = State( + mapping=base.mapping.copy(), + criteria=base.criteria.copy(), + backtrack_causes=base.backtrack_causes[:], + ) + self._states.append(state) + + def _add_to_criteria(self, criteria, requirement, parent): + self._r.adding_requirement(requirement=requirement, parent=parent) + + identifier = self._p.identify(requirement_or_candidate=requirement) + criterion = criteria.get(identifier) + if criterion: + incompatibilities = list(criterion.incompatibilities) + else: + incompatibilities = [] + + matches = self._p.find_matches( + identifier=identifier, + requirements=IteratorMapping( + criteria, + operator.methodcaller("iter_requirement"), + {identifier: [requirement]}, + ), + incompatibilities=IteratorMapping( + criteria, + operator.attrgetter("incompatibilities"), + {identifier: incompatibilities}, + ), + ) + + if criterion: + information = list(criterion.information) + information.append(RequirementInformation(requirement, parent)) + else: + information = [RequirementInformation(requirement, parent)] + + criterion = Criterion( + candidates=build_iter_view(matches), + information=information, + incompatibilities=incompatibilities, + ) + if not criterion.candidates: + raise RequirementsConflicted(criterion) + criteria[identifier] = criterion + + def _remove_information_from_criteria(self, criteria, parents): + """Remove information from parents of criteria. + + Concretely, removes all values from each criterion's ``information`` + field that have one of ``parents`` as provider of the requirement. + + :param criteria: The criteria to update. + :param parents: Identifiers for which to remove information from all criteria. + """ + if not parents: + return + for key, criterion in criteria.items(): + criteria[key] = Criterion( + criterion.candidates, + [ + information + for information in criterion.information + if ( + information.parent is None + or self._p.identify(information.parent) not in parents + ) + ], + criterion.incompatibilities, + ) + + def _get_preference(self, name): + return self._p.get_preference( + identifier=name, + resolutions=self.state.mapping, + candidates=IteratorMapping( + self.state.criteria, + operator.attrgetter("candidates"), + ), + information=IteratorMapping( + self.state.criteria, + operator.attrgetter("information"), + ), + backtrack_causes=self.state.backtrack_causes, + ) + + def _is_current_pin_satisfying(self, name, criterion): + try: + current_pin = self.state.mapping[name] + except KeyError: + return False + return all( + self._p.is_satisfied_by(requirement=r, candidate=current_pin) + for r in criterion.iter_requirement() + ) + + def _get_updated_criteria(self, candidate): + criteria = self.state.criteria.copy() + for requirement in self._p.get_dependencies(candidate=candidate): + self._add_to_criteria(criteria, requirement, parent=candidate) + return criteria + + def _attempt_to_pin_criterion(self, name): + criterion = self.state.criteria[name] + + causes = [] + for candidate in criterion.candidates: + try: + criteria = self._get_updated_criteria(candidate) + except RequirementsConflicted as e: + self._r.rejecting_candidate(e.criterion, candidate) + causes.append(e.criterion) + continue + + # Check the newly-pinned candidate actually works. This should + # always pass under normal circumstances, but in the case of a + # faulty provider, we will raise an error to notify the implementer + # to fix find_matches() and/or is_satisfied_by(). + satisfied = all( + self._p.is_satisfied_by(requirement=r, candidate=candidate) + for r in criterion.iter_requirement() + ) + if not satisfied: + raise InconsistentCandidate(candidate, criterion) + + self._r.pinning(candidate=candidate) + self.state.criteria.update(criteria) + + # Put newly-pinned candidate at the end. This is essential because + # backtracking looks at this mapping to get the last pin. + self.state.mapping.pop(name, None) + self.state.mapping[name] = candidate + + return [] + + # All candidates tried, nothing works. This criterion is a dead + # end, signal for backtracking. + return causes + + def _backjump(self, causes): + """Perform backjumping. + + When we enter here, the stack is like this:: + + [ state Z ] + [ state Y ] + [ state X ] + .... earlier states are irrelevant. + + 1. No pins worked for Z, so it does not have a pin. + 2. We want to reset state Y to unpinned, and pin another candidate. + 3. State X holds what state Y was before the pin, but does not + have the incompatibility information gathered in state Y. + + Each iteration of the loop will: + + 1. Identify Z. The incompatibility is not always caused by the latest + state. For example, given three requirements A, B and C, with + dependencies A1, B1 and C1, where A1 and B1 are incompatible: the + last state might be related to C, so we want to discard the + previous state. + 2. Discard Z. + 3. Discard Y but remember its incompatibility information gathered + previously, and the failure we're dealing with right now. + 4. Push a new state Y' based on X, and apply the incompatibility + information from Y to Y'. + 5a. If this causes Y' to conflict, we need to backtrack again. Make Y' + the new Z and go back to step 2. + 5b. If the incompatibilities apply cleanly, end backtracking. + """ + incompatible_reqs = itertools.chain( + (c.parent for c in causes if c.parent is not None), + (c.requirement for c in causes), + ) + incompatible_deps = {self._p.identify(r) for r in incompatible_reqs} + while len(self._states) >= 3: + # Remove the state that triggered backtracking. + del self._states[-1] + + # Ensure to backtrack to a state that caused the incompatibility + incompatible_state = False + while not incompatible_state: + # Retrieve the last candidate pin and known incompatibilities. + try: + broken_state = self._states.pop() + name, candidate = broken_state.mapping.popitem() + except (IndexError, KeyError): + raise ResolutionImpossible(causes) + current_dependencies = { + self._p.identify(d) + for d in self._p.get_dependencies(candidate) + } + incompatible_state = not current_dependencies.isdisjoint( + incompatible_deps + ) + + incompatibilities_from_broken = [ + (k, list(v.incompatibilities)) + for k, v in broken_state.criteria.items() + ] + + # Also mark the newly known incompatibility. + incompatibilities_from_broken.append((name, [candidate])) + + # Create a new state from the last known-to-work one, and apply + # the previously gathered incompatibility information. + def _patch_criteria(): + for k, incompatibilities in incompatibilities_from_broken: + if not incompatibilities: + continue + try: + criterion = self.state.criteria[k] + except KeyError: + continue + matches = self._p.find_matches( + identifier=k, + requirements=IteratorMapping( + self.state.criteria, + operator.methodcaller("iter_requirement"), + ), + incompatibilities=IteratorMapping( + self.state.criteria, + operator.attrgetter("incompatibilities"), + {k: incompatibilities}, + ), + ) + candidates = build_iter_view(matches) + if not candidates: + return False + incompatibilities.extend(criterion.incompatibilities) + self.state.criteria[k] = Criterion( + candidates=candidates, + information=list(criterion.information), + incompatibilities=incompatibilities, + ) + return True + + self._push_new_state() + success = _patch_criteria() + + # It works! Let's work on this new state. + if success: + return True + + # State does not work after applying known incompatibilities. + # Try the still previous state. + + # No way to backtrack anymore. + return False + + def resolve(self, requirements, max_rounds): + if self._states: + raise RuntimeError("already resolved") + + self._r.starting() + + # Initialize the root state. + self._states = [ + State( + mapping=collections.OrderedDict(), + criteria={}, + backtrack_causes=[], + ) + ] + for r in requirements: + try: + self._add_to_criteria(self.state.criteria, r, parent=None) + except RequirementsConflicted as e: + raise ResolutionImpossible(e.criterion.information) + + # The root state is saved as a sentinel so the first ever pin can have + # something to backtrack to if it fails. The root state is basically + # pinning the virtual "root" package in the graph. + self._push_new_state() + + for round_index in range(max_rounds): + self._r.starting_round(index=round_index) + + unsatisfied_names = [ + key + for key, criterion in self.state.criteria.items() + if not self._is_current_pin_satisfying(key, criterion) + ] + + # All criteria are accounted for. Nothing more to pin, we are done! + if not unsatisfied_names: + self._r.ending(state=self.state) + return self.state + + # keep track of satisfied names to calculate diff after pinning + satisfied_names = set(self.state.criteria.keys()) - set( + unsatisfied_names + ) + + # Choose the most preferred unpinned criterion to try. + name = min(unsatisfied_names, key=self._get_preference) + failure_causes = self._attempt_to_pin_criterion(name) + + if failure_causes: + causes = [i for c in failure_causes for i in c.information] + # Backjump if pinning fails. The backjump process puts us in + # an unpinned state, so we can work on it in the next round. + self._r.resolving_conflicts(causes=causes) + success = self._backjump(causes) + self.state.backtrack_causes[:] = causes + + # Dead ends everywhere. Give up. + if not success: + raise ResolutionImpossible(self.state.backtrack_causes) + else: + # discard as information sources any invalidated names + # (unsatisfied names that were previously satisfied) + newly_unsatisfied_names = { + key + for key, criterion in self.state.criteria.items() + if key in satisfied_names + and not self._is_current_pin_satisfying(key, criterion) + } + self._remove_information_from_criteria( + self.state.criteria, newly_unsatisfied_names + ) + # Pinning was successful. Push a new state to do another pin. + self._push_new_state() + + self._r.ending_round(index=round_index, state=self.state) + + raise ResolutionTooDeep(max_rounds) + + +def _has_route_to_root(criteria, key, all_keys, connected): + if key in connected: + return True + if key not in criteria: + return False + for p in criteria[key].iter_parent(): + try: + pkey = all_keys[id(p)] + except KeyError: + continue + if pkey in connected: + connected.add(key) + return True + if _has_route_to_root(criteria, pkey, all_keys, connected): + connected.add(key) + return True + return False + + +Result = collections.namedtuple("Result", "mapping graph criteria") + + +def _build_result(state): + mapping = state.mapping + all_keys = {id(v): k for k, v in mapping.items()} + all_keys[id(None)] = None + + graph = DirectedGraph() + graph.add(None) # Sentinel as root dependencies' parent. + + connected = {None} + for key, criterion in state.criteria.items(): + if not _has_route_to_root(state.criteria, key, all_keys, connected): + continue + if key not in graph: + graph.add(key) + for p in criterion.iter_parent(): + try: + pkey = all_keys[id(p)] + except KeyError: + continue + if pkey not in graph: + graph.add(pkey) + graph.connect(pkey, key) + + return Result( + mapping={k: v for k, v in mapping.items() if k in connected}, + graph=graph, + criteria=state.criteria, + ) + + +class Resolver(AbstractResolver): + """The thing that performs the actual resolution work.""" + + base_exception = ResolverException + + def resolve(self, requirements, max_rounds=100): + """Take a collection of constraints, spit out the resolution result. + + The return value is a representation to the final resolution result. It + is a tuple subclass with three public members: + + * `mapping`: A dict of resolved candidates. Each key is an identifier + of a requirement (as returned by the provider's `identify` method), + and the value is the resolved candidate. + * `graph`: A `DirectedGraph` instance representing the dependency tree. + The vertices are keys of `mapping`, and each edge represents *why* + a particular package is included. A special vertex `None` is + included to represent parents of user-supplied requirements. + * `criteria`: A dict of "criteria" that hold detailed information on + how edges in the graph are derived. Each key is an identifier of a + requirement, and the value is a `Criterion` instance. + + The following exceptions may be raised if a resolution cannot be found: + + * `ResolutionImpossible`: A resolution cannot be found for the given + combination of requirements. The `causes` attribute of the + exception is a list of (requirement, parent), giving the + requirements that could not be satisfied. + * `ResolutionTooDeep`: The dependency tree is too deeply nested and + the resolver gave up. This is usually caused by a circular + dependency, but you can try to resolve this by increasing the + `max_rounds` argument. + """ + resolution = Resolution(self.provider, self.reporter) + state = resolution.resolve(requirements, max_rounds=max_rounds) + return _build_result(state) diff --git a/videollama2/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/rule.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/rule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc64bc20968261d92f91ba9e31e12bb1a4f6b493 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/rule.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_geointerface.cpython-310.pyc b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_geointerface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4d852ae6b2aed4bf81f127c9f6e1a0e7119fa9a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_geointerface.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_locale.cpython-310.pyc b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_locale.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35f97e4d19e8ec2d596b115ddcfe53a196d53f2f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_locale.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_nearest.cpython-310.pyc b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_nearest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..022733dd22286f86774ff6a9333d7b988e590766 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_nearest.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_orient.cpython-310.pyc b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_orient.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b51d156310e155d38c0ed1221a1a756afeffe280 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_orient.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_parallel_offset.cpython-310.pyc b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_parallel_offset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c353c1b8c44e6067c13a0feab80012f92044ccf Binary files /dev/null and b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_parallel_offset.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_products_z.cpython-310.pyc b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_products_z.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb0e13572e1dd95476931dfaf968986148ac248a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_products_z.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_svg.cpython-310.pyc b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_svg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..764041fcd4bfc92c9751cc8e56fbf4139958ea15 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_svg.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_transform.cpython-310.pyc b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_transform.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3940576b2d3f254fc4c99188a3c82bbd6d9a00c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/__pycache__/test_transform.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/conftest.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..374958ee8a72afb44e773b10d8ded06f8a04f6d2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/conftest.py @@ -0,0 +1,21 @@ +import numpy +import pytest + +from shapely.geos import geos_version + +requires_geos_38 = pytest.mark.skipif( + geos_version < (3, 8, 0), reason="GEOS >= 3.8.0 is required." +) +requires_geos_342 = pytest.mark.skipif( + geos_version < (3, 4, 2), reason="GEOS > 3.4.2 is required." +) + +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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_affinity.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_affinity.py new file mode 100644 index 0000000000000000000000000000000000000000..1004fa34e2017965c53edc7e4598f23f9a662edd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_affinity.py @@ -0,0 +1,311 @@ +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) + return + + 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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_box.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_box.py new file mode 100644 index 0000000000000000000000000000000000000000..40d5a536323587d83fefd6d4e1798ee9736eff25 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_clip_by_rect.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_clip_by_rect.py new file mode 100644 index 0000000000000000000000000000000000000000..dab3e9e7855b1de7b4777f395f098b41bc9245c7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_clip_by_rect.py @@ -0,0 +1,120 @@ +""" +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 +from shapely.wkt import 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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_create_inconsistent_dimensionality.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_create_inconsistent_dimensionality.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e346aa6ef16902f308602030ca049ff3e312b1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_create_inconsistent_dimensionality.py @@ -0,0 +1,214 @@ +""" +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 + +from shapely import wkt +from shapely.errors import GEOSException +from shapely.geometry import LineString, Polygon, shape +from shapely.geos import geos_version + +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 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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_delaunay.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_delaunay.py new file mode 100644 index 0000000000000000000000000000000000000000..2f21b2211821c65e75c93b1e4f3d65707bb73f24 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_empty_polygons.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_empty_polygons.py new file mode 100644 index 0000000000000000000000000000000000000000..a2caff758951be30b5d42ba7be7592ecfebec950 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_equality.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_equality.py new file mode 100644 index 0000000000000000000000000000000000000000..18ce322f7a47a09a6b3ce3cfe152ca56356ec24b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_equality.py @@ -0,0 +1,32 @@ +import pytest + +from shapely import Point +from shapely.errors import ShapelyDeprecationWarning + + +def test_equals_exact(): + p1 = Point(1.0, 1.0) + p2 = Point(2.0, 2.0) + assert not p1.equals(p2) + assert not p1.equals_exact(p2, 0.001) + assert p1.equals_exact(p2, 1.42) + + +def test_almost_equals_default(): + p1 = Point(1.0, 1.0) + p2 = Point(1.0 + 1e-7, 1.0 + 1e-7) # almost equal to 6 places + p3 = Point(1.0 + 1e-6, 1.0 + 1e-6) # not almost equal + with pytest.warns(ShapelyDeprecationWarning): + assert p1.almost_equals(p2) + with pytest.warns(ShapelyDeprecationWarning): + assert not p1.almost_equals(p3) + + +def test_almost_equals(): + p1 = Point(1.0, 1.0) + p2 = Point(1.1, 1.1) + assert not p1.equals(p2) + with pytest.warns(ShapelyDeprecationWarning): + assert p1.almost_equals(p2, 0) + with pytest.warns(ShapelyDeprecationWarning): + assert not p1.almost_equals(p2, 1) diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_geointerface.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_geointerface.py new file mode 100644 index 0000000000000000000000000000000000000000..326a8d694cf22eca7b873df17f85e1843f1ababf --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_linear_referencing.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_linear_referencing.py new file mode 100644 index 0000000000000000000000000000000000000000..47e5c015b9aa6de91b71d942316adc16a4e7e86b --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_locale.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_locale.py new file mode 100644 index 0000000000000000000000000000000000000000..020f70b1df6d8ea4f53df6ca7a94869155785c9c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_locale.py @@ -0,0 +1,56 @@ +"""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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_make_valid.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_make_valid.py new file mode 100644 index 0000000000000000000000000000000000000000..d65e421c32529e833f9fcfabf500f5d211665a02 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_make_valid.py @@ -0,0 +1,18 @@ +from shapely.geometry import Polygon +from shapely.tests.legacy.conftest import requires_geos_38 +from shapely.validation import make_valid + + +@requires_geos_38 +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) + + +@requires_geos_38 +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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_mapping.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..454e7015251df3aa2a52ca4ce56fd1a7d99ea179 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_mapping.py @@ -0,0 +1,14 @@ +import unittest + +from shapely.geometry import mapping, Point, Polygon + + +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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_ndarrays.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_ndarrays.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b9a4aa762cced22edf5a682253ee053826c09c --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_nearest.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_nearest.py new file mode 100644 index 0000000000000000000000000000000000000000..48f058d871d9c26aac99e25388afb06394592ea5 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_operations.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3cab1be80de65190c1c8a68cf9e39b649b4c5763 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_operations.py @@ -0,0 +1,122 @@ +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, 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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_orient.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_orient.py new file mode 100644 index 0000000000000000000000000000000000000000..71dce26582689772c824e75fc1df97d5dcb65817 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_orient.py @@ -0,0 +1,64 @@ +import unittest + +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_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]) diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_pickle.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..4d65bc4ea9654c9f68190899214634fa7099b672 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_pickle.py @@ -0,0 +1,84 @@ +import pathlib +import pickle +import warnings +from pickle import dumps, HIGHEST_PROTOCOL, loads + +import pytest + +import shapely +from shapely import wkt +from shapely.geometry import ( + box, + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) + +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): + 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.geos_version) + + for name, geom in TEST_DATA.items(): + if name == "emptypoint" and shapely.geos.geos_version < (3, 9, 0): + # Empty Points cannot be represented in WKB + continue + with open(datadir / f"{name}_{shapely_version}.pickle", "wb") as f: + pickle.dump(geom, f) diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_polylabel.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_polylabel.py new file mode 100644 index 0000000000000000000000000000000000000000..347db38b606b2a65c51a1a922204ab413aed63d5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_polylabel.py @@ -0,0 +1,97 @@ +import unittest + +import pytest + +from shapely.algorithms.polylabel import Cell, polylabel +from shapely.errors import TopologicalError +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=10) + expected = Point(59.35615556364569, 121.8391962974644) + assert expected.equals_exact(label, 1e-6) + + def test_invalid_polygon(self): + """ + Makes sure that the polylabel function throws an exception when provided + an invalid polygon. + + """ + bowtie_polygon = Polygon( + [(0, 0), (0, 20), (10, 10), (20, 20), (20, 0), (10, 10), (0, 0)] + ) + with pytest.raises(TopologicalError): + polylabel(bowtie_polygon) + + def test_cell_sorting(self): + """ + Tests rich comparison operators of Cells for use in the polylabel + minimum priority queue. + + """ + polygon = Point(0, 0).buffer(100) + cell1 = Cell(0, 0, 50, polygon) # closest + cell2 = Cell(50, 50, 50, polygon) # furthest + assert cell1 < cell2 + assert cell1 <= cell2 + assert (cell2 <= cell1) is False + assert cell1 == cell1 + assert (cell1 == cell2) is False + assert cell1 != cell2 + assert (cell1 != cell1) is False + assert cell2 > cell1 + assert (cell1 > cell2) is False + assert cell2 >= cell1 + assert (cell1 >= cell2) is False + + 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) + assert label.coords[:] == [(32.722025, -117.201875)] + + 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) diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_predicates.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_predicates.py new file mode 100644 index 0000000000000000000000000000000000000000..ea3551ccc7b0352fd645c106cdcc31035b139356 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_predicates.py @@ -0,0 +1,99 @@ +"""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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_prepared.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_prepared.py new file mode 100644 index 0000000000000000000000000000000000000000..b30b923ae9d741f0baf08cf2d76b64ea610d4d6d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_prepared.py @@ -0,0 +1,62 @@ +import numpy as np +import pytest + +from shapely.geometry import Point, Polygon +from shapely.prepared import prep, PreparedGeometry + + +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.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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_shape.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..8e0aa7ab7c6437c20fa427a948f664eda7f1dc68 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_shape.py @@ -0,0 +1,48 @@ +import pytest + +from shapely.geometry import MultiLineString, 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) diff --git a/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_singularity.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_singularity.py new file mode 100644 index 0000000000000000000000000000000000000000..a9f74b494db8bdae37aca3b0c7997aa9d6cbfa75 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_snap.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_snap.py new file mode 100644 index 0000000000000000000000000000000000000000..67a950d9e823ee1a4be3cb768fb370b4b44d5b3b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_snap.py @@ -0,0 +1,25 @@ +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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_split.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..129e7473322b5aa4e7ce82ef5213456ed27d712b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_split.py @@ -0,0 +1,249 @@ +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 segments + splitter = LineString([(1, 3), (1, -3)]) + self.helper(self.poly_simple, splitter, 2) + self.helper(self.poly_hole, splitter, 2) + + # 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_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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_svg.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_svg.py new file mode 100644 index 0000000000000000000000000000000000000000..c1c6e7f44aee757305e35e4293f4d192d8c20fd3 --- /dev/null +++ b/vllm/lib/python3.10/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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_voronoi_diagram.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_voronoi_diagram.py new file mode 100644 index 0000000000000000000000000000000000000000..4b48c89d978ff6930e02061c374a8d654f2d61a3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/test_voronoi_diagram.py @@ -0,0 +1,146 @@ +""" +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.geos import geos_version +from shapely.ops import voronoi_diagram +from shapely.wkt import loads as load_wkt + +requires_geos_35 = pytest.mark.skipif( + geos_version < (3, 5, 0), reason="GEOS >= 3.5.0 is required." +) + + +@requires_geos_35 +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 + + +@requires_geos_35 +def test_two_regions(): + mp = MultiPoint(points=[(0.5, 0.5), (1.0, 1.0)]) + regions = voronoi_diagram(mp) + + assert len(regions.geoms) == 2 + + +@requires_geos_35 +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) + + +@requires_geos_35 +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 + + +@requires_geos_35 +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 + + +@requires_geos_35 +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 + + +@requires_geos_35 +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 + + +@requires_geos_35 +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) + + +@requires_geos_35 +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) + + +@requires_geos_35 +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) + + +@requires_geos_35 +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) + + +@requires_geos_35 +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/vllm/lib/python3.10/site-packages/shapely/tests/legacy/threading_test.py b/vllm/lib/python3.10/site-packages/shapely/tests/legacy/threading_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6d73382d86c4f055334f5f147162629cd6c6d048 --- /dev/null +++ b/vllm/lib/python3.10/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("%s: Running shapely tests on wkb" % num) + import shapely.geos + + print("%s GEOS Handle: %s" % (num, shapely.geos.lgeos.geos_handle)) + import shapely.wkb + import shapely.wkt + + p = shapely.wkt.loads("POINT (0 0)") + print("%s WKT: %s" % (num, shapely.wkt.dumps(p))) + wkb = shapely.wkb.dumps(p) + print("%s WKB: %s" % (num, b2a_hex(wkb))) + + for i in range(10): + shapely.wkb.loads(wkb) + + print("%s GEOS Handle: %s" % (num, shapely.geos.lgeos.geos_handle)) + print("Done %s" % num) + + +if __name__ == "__main__": + main()