diff --git a/data/miniconda3/lib/python3.13/site-packages/_distutils_hack/__init__.py b/data/miniconda3/lib/python3.13/site-packages/_distutils_hack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94f71b99ecefd27e6cf3fd06fc3c0eef5fd73910 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/_distutils_hack/__init__.py @@ -0,0 +1,239 @@ +# don't import any costly modules +import os +import sys + +report_url = ( + "https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml" +) + + +def warn_distutils_present(): + if 'distutils' not in sys.modules: + return + import warnings + + warnings.warn( + "Distutils was imported before Setuptools, but importing Setuptools " + "also replaces the `distutils` module in `sys.modules`. This may lead " + "to undesirable behaviors or errors. To avoid these issues, avoid " + "using distutils directly, ensure that setuptools is installed in the " + "traditional way (e.g. not an editable install), and/or make sure " + "that setuptools is always imported before distutils." + ) + + +def clear_distutils(): + if 'distutils' not in sys.modules: + return + import warnings + + warnings.warn( + "Setuptools is replacing distutils. Support for replacing " + "an already imported distutils is deprecated. In the future, " + "this condition will fail. " + f"Register concerns at {report_url}" + ) + mods = [ + name + for name in sys.modules + if name == "distutils" or name.startswith("distutils.") + ] + for name in mods: + del sys.modules[name] + + +def enabled(): + """ + Allow selection of distutils by environment variable. + """ + which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local') + if which == 'stdlib': + import warnings + + warnings.warn( + "Reliance on distutils from stdlib is deprecated. Users " + "must rely on setuptools to provide the distutils module. " + "Avoid importing distutils or import setuptools first, " + "and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. " + f"Register concerns at {report_url}" + ) + return which == 'local' + + +def ensure_local_distutils(): + import importlib + + clear_distutils() + + # With the DistutilsMetaFinder in place, + # perform an import to cause distutils to be + # loaded from setuptools._distutils. Ref #2906. + with shim(): + importlib.import_module('distutils') + + # check that submodules load as expected + core = importlib.import_module('distutils.core') + assert '_distutils' in core.__file__, core.__file__ + assert 'setuptools._distutils.log' not in sys.modules + + +def do_override(): + """ + Ensure that the local copy of distutils is preferred over stdlib. + + See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 + for more motivation. + """ + if enabled(): + warn_distutils_present() + ensure_local_distutils() + + +class _TrivialRe: + def __init__(self, *patterns) -> None: + self._patterns = patterns + + def match(self, string): + return all(pat in string for pat in self._patterns) + + +class DistutilsMetaFinder: + def find_spec(self, fullname, path, target=None): + # optimization: only consider top level modules and those + # found in the CPython test suite. + if path is not None and not fullname.startswith('test.'): + return None + + method_name = 'spec_for_{fullname}'.format(**locals()) + method = getattr(self, method_name, lambda: None) + return method() + + def spec_for_distutils(self): + if self.is_cpython(): + return None + + import importlib + import importlib.abc + import importlib.util + + try: + mod = importlib.import_module('setuptools._distutils') + except Exception: + # There are a couple of cases where setuptools._distutils + # may not be present: + # - An older Setuptools without a local distutils is + # taking precedence. Ref #2957. + # - Path manipulation during sitecustomize removes + # setuptools from the path but only after the hook + # has been loaded. Ref #2980. + # In either case, fall back to stdlib behavior. + return None + + class DistutilsLoader(importlib.abc.Loader): + def create_module(self, spec): + mod.__name__ = 'distutils' + return mod + + def exec_module(self, module): + pass + + return importlib.util.spec_from_loader( + 'distutils', DistutilsLoader(), origin=mod.__file__ + ) + + @staticmethod + def is_cpython(): + """ + Suppress supplying distutils for CPython (build and tests). + Ref #2965 and #3007. + """ + return os.path.isfile('pybuilddir.txt') + + def spec_for_pip(self): + """ + Ensure stdlib distutils when running under pip. + See pypa/pip#8761 for rationale. + """ + if sys.version_info >= (3, 12) or self.pip_imported_during_build(): + return + clear_distutils() + self.spec_for_distutils = lambda: None + + @classmethod + def pip_imported_during_build(cls): + """ + Detect if pip is being imported in a build script. Ref #2355. + """ + import traceback + + return any( + cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None) + ) + + @staticmethod + def frame_file_is_setup(frame): + """ + Return True if the indicated frame suggests a setup.py file. + """ + # some frames may not have __file__ (#2940) + return frame.f_globals.get('__file__', '').endswith('setup.py') + + def spec_for_sensitive_tests(self): + """ + Ensure stdlib distutils when running select tests under CPython. + + python/cpython#91169 + """ + clear_distutils() + self.spec_for_distutils = lambda: None + + sensitive_tests = ( + [ + 'test.test_distutils', + 'test.test_peg_generator', + 'test.test_importlib', + ] + if sys.version_info < (3, 10) + else [ + 'test.test_distutils', + ] + ) + + +for name in DistutilsMetaFinder.sensitive_tests: + setattr( + DistutilsMetaFinder, + f'spec_for_{name}', + DistutilsMetaFinder.spec_for_sensitive_tests, + ) + + +DISTUTILS_FINDER = DistutilsMetaFinder() + + +def add_shim(): + DISTUTILS_FINDER in sys.meta_path or insert_shim() + + +class shim: + def __enter__(self) -> None: + insert_shim() + + def __exit__(self, exc: object, value: object, tb: object) -> None: + _remove_shim() + + +def insert_shim(): + sys.meta_path.insert(0, DISTUTILS_FINDER) + + +def _remove_shim(): + try: + sys.meta_path.remove(DISTUTILS_FINDER) + except ValueError: + pass + + +if sys.version_info < (3, 12): + # DistutilsMetaFinder can only be disabled in Python < 3.12 (PEP 632) + remove_shim = _remove_shim diff --git a/data/miniconda3/lib/python3.13/site-packages/_distutils_hack/override.py b/data/miniconda3/lib/python3.13/site-packages/_distutils_hack/override.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc433a4a55e3b41fa31089918fb62096092f89f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/_distutils_hack/override.py @@ -0,0 +1 @@ +__import__('_distutils_hack').do_override() diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/__init__.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..70a9e4f2e1350de535bf79ce6dd8f912d791e1b6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/__init__.py @@ -0,0 +1,121 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import typing as _t + +from . import types +from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes, omit, not_given +from ._utils import file_from_path +from ._client import ( + Client, + Stream, + Timeout, + Anthropic, + Transport, + AsyncClient, + AsyncStream, + AsyncAnthropic, + RequestOptions, +) +from ._models import BaseModel +from ._version import __title__, __version__ +from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse +from ._constants import ( + AI_PROMPT as AI_PROMPT, + HUMAN_PROMPT as HUMAN_PROMPT, + DEFAULT_TIMEOUT, + DEFAULT_MAX_RETRIES, + DEFAULT_CONNECTION_LIMITS, +) +from ._exceptions import ( + APIError, + ConflictError, + NotFoundError, + AnthropicError, + APIStatusError, + RateLimitError, + APITimeoutError, + BadRequestError, + APIConnectionError, + AuthenticationError, + InternalServerError, + PermissionDeniedError, + UnprocessableEntityError, + APIResponseValidationError, +) +from ._base_client import DefaultHttpxClient, DefaultAioHttpClient, DefaultAsyncHttpxClient +from ._utils._logs import setup_logging as _setup_logging +from .lib._parse._transform import transform_schema + +__all__ = [ + "types", + "__version__", + "__title__", + "NoneType", + "Transport", + "ProxiesTypes", + "NotGiven", + "NOT_GIVEN", + "not_given", + "Omit", + "omit", + "AnthropicError", + "APIError", + "APIStatusError", + "APITimeoutError", + "APIConnectionError", + "APIResponseValidationError", + "BadRequestError", + "AuthenticationError", + "PermissionDeniedError", + "NotFoundError", + "ConflictError", + "UnprocessableEntityError", + "RateLimitError", + "InternalServerError", + "Timeout", + "RequestOptions", + "Client", + "AsyncClient", + "Stream", + "AsyncStream", + "Anthropic", + "AsyncAnthropic", + "file_from_path", + "BaseModel", + "DEFAULT_TIMEOUT", + "DEFAULT_MAX_RETRIES", + "DEFAULT_CONNECTION_LIMITS", + "DefaultHttpxClient", + "DefaultAsyncHttpxClient", + "DefaultAioHttpClient", + "HUMAN_PROMPT", + "AI_PROMPT", + "beta_tool", + "beta_async_tool", + "transform_schema", +] + +if not _t.TYPE_CHECKING: + from ._utils._resources_proxy import resources as resources + +from .lib.aws import AnthropicAWS as AnthropicAWS, AsyncAnthropicAWS as AsyncAnthropicAWS +from .lib.tools import beta_tool, beta_async_tool +from .lib.vertex import * +from .lib.bedrock import * +from .lib.foundry import AnthropicFoundry as AnthropicFoundry, AsyncAnthropicFoundry as AsyncAnthropicFoundry +from .lib.streaming import * + +_setup_logging() + +# Update the __module__ attribute for exported symbols so that +# error messages point to this module instead of the module +# it was originally defined in, e.g. +# anthropic._exceptions.NotFoundError -> anthropic.NotFoundError +__locals = locals() +for __name in __all__: + if not __name.startswith("__"): + try: + __locals[__name].__module__ = "anthropic" + except (TypeError, AttributeError): + # Some of our exported symbols are builtins which we can't set attributes for. + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_base_client.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_base_client.py new file mode 100644 index 0000000000000000000000000000000000000000..02122c538197b0f68d190705d3478e4a5d6e2a9a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_base_client.py @@ -0,0 +1,2271 @@ +from __future__ import annotations + +import sys +import json +import time +import uuid +import email +import socket +import asyncio +import inspect +import logging +import platform +import warnings +import email.utils +from types import TracebackType +from random import random +from typing import ( + TYPE_CHECKING, + Any, + Dict, + List, + Type, + Tuple, + Union, + Generic, + Mapping, + TypeVar, + Iterable, + Iterator, + Optional, + Generator, + AsyncIterator, + cast, + overload, +) +from typing_extensions import Literal, override, get_origin + +import anyio +import httpx +import distro +import pydantic +from httpx import URL, Proxy, HTTPTransport, AsyncHTTPTransport +from pydantic import PrivateAttr + +from . import _exceptions +from ._qs import Querystring +from ._files import to_httpx_files, async_to_httpx_files +from ._types import ( + Body, + Omit, + Query, + Headers, + Timeout, + NotGiven, + ResponseT, + AnyMapping, + PostParser, + BinaryTypes, + RequestFiles, + HttpxSendArgs, + RequestOptions, + AsyncBinaryTypes, + HttpxRequestFiles, + ModelBuilderProtocol, + not_given, +) +from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping +from ._compat import PYDANTIC_V1, model_copy, model_dump +from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type +from ._response import ( + APIResponse, + BaseAPIResponse, + AsyncAPIResponse, + extract_response_type, +) +from ._constants import ( + DEFAULT_TIMEOUT, + MAX_RETRY_DELAY, + DEFAULT_MAX_RETRIES, + INITIAL_RETRY_DELAY, + RAW_RESPONSE_HEADER, + OVERRIDE_CAST_TO_HEADER, + DEFAULT_CONNECTION_LIMITS, +) +from ._streaming import Stream, SSEDecoder, AsyncStream, SSEBytesDecoder +from ._exceptions import ( + APIStatusError, + APITimeoutError, + APIConnectionError, + APIResponseValidationError, +) +from ._utils._json import openapi_dumps +from ._utils._httpx import get_environment_proxies +from ._legacy_response import LegacyAPIResponse + +log: logging.Logger = logging.getLogger(__name__) + +# TODO: make base page type vars covariant +SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]") +AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]") + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +_StreamT = TypeVar("_StreamT", bound=Stream[Any]) +_AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any]) + +if TYPE_CHECKING: + from httpx._config import ( + DEFAULT_TIMEOUT_CONFIG, # pyright: ignore[reportPrivateImportUsage] + ) + + HTTPX_DEFAULT_TIMEOUT = DEFAULT_TIMEOUT_CONFIG +else: + try: + from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT + except ImportError: + # taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366 + HTTPX_DEFAULT_TIMEOUT = Timeout(5.0) + + +class PageInfo: + """Stores the necessary information to build the request to retrieve the next page. + + Either `url` or `params` must be set. + """ + + url: URL | NotGiven + params: Query | NotGiven + json: Body | NotGiven + + @overload + def __init__( + self, + *, + url: URL, + ) -> None: ... + + @overload + def __init__( + self, + *, + params: Query, + ) -> None: ... + + @overload + def __init__( + self, + *, + json: Body, + ) -> None: ... + + def __init__( + self, + *, + url: URL | NotGiven = not_given, + json: Body | NotGiven = not_given, + params: Query | NotGiven = not_given, + ) -> None: + self.url = url + self.json = json + self.params = params + + @override + def __repr__(self) -> str: + if self.url: + return f"{self.__class__.__name__}(url={self.url})" + if self.json: + return f"{self.__class__.__name__}(json={self.json})" + return f"{self.__class__.__name__}(params={self.params})" + + +class BasePage(GenericModel, Generic[_T]): + """ + Defines the core interface for pagination. + + Type Args: + ModelT: The pydantic model that represents an item in the response. + + Methods: + has_next_page(): Check if there is another page available + next_page_info(): Get the necessary information to make a request for the next page + """ + + _options: FinalRequestOptions = PrivateAttr() + _model: Type[_T] = PrivateAttr() + + def has_next_page(self) -> bool: + items = self._get_page_items() + if not items: + return False + return self.next_page_info() is not None + + def next_page_info(self) -> Optional[PageInfo]: ... + + def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body] + ... + + def _params_from_url(self, url: URL) -> httpx.QueryParams: + # TODO: do we have to preprocess params here? + return httpx.QueryParams(cast(Any, self._options.params)).merge(url.params) + + def _info_to_options(self, info: PageInfo) -> FinalRequestOptions: + options = model_copy(self._options) + options._strip_raw_response_header() + + if not isinstance(info.params, NotGiven): + options.params = {**options.params, **info.params} + return options + + if not isinstance(info.url, NotGiven): + params = self._params_from_url(info.url) + url = info.url.copy_with(params=params) + options.params = dict(url.params) + options.url = str(url) + return options + + if not isinstance(info.json, NotGiven): + if not is_mapping(info.json): + raise TypeError("Pagination is only supported with mappings") + + if not options.json_data: + options.json_data = {**info.json} + else: + if not is_mapping(options.json_data): + raise TypeError("Pagination is only supported with mappings") + + options.json_data = {**options.json_data, **info.json} + return options + + raise ValueError("Unexpected PageInfo state") + + +class BaseSyncPage(BasePage[_T], Generic[_T]): + _client: SyncAPIClient = pydantic.PrivateAttr() + + def _set_private_attributes( + self, + client: SyncAPIClient, + model: Type[_T], + options: FinalRequestOptions, + ) -> None: + if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None: + self.__pydantic_private__ = {} + + self._model = model + self._client = client + self._options = options + + # Pydantic uses a custom `__iter__` method to support casting BaseModels + # to dictionaries. e.g. dict(model). + # As we want to support `for item in page`, this is inherently incompatible + # with the default pydantic behaviour. It is not possible to support both + # use cases at once. Fortunately, this is not a big deal as all other pydantic + # methods should continue to work as expected as there is an alternative method + # to cast a model to a dictionary, model.dict(), which is used internally + # by pydantic. + def __iter__(self) -> Iterator[_T]: # type: ignore + for page in self.iter_pages(): + for item in page._get_page_items(): + yield item + + def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]: + page = self + while True: + yield page + if page.has_next_page(): + page = page.get_next_page() + else: + return + + def get_next_page(self: SyncPageT) -> SyncPageT: + info = self.next_page_info() + if not info: + raise RuntimeError( + "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`." + ) + + options = self._info_to_options(info) + return self._client._request_api_list(self._model, page=self.__class__, options=options) + + +class AsyncPaginator(Generic[_T, AsyncPageT]): + def __init__( + self, + client: AsyncAPIClient, + options: FinalRequestOptions, + page_cls: Type[AsyncPageT], + model: Type[_T], + ) -> None: + self._model = model + self._client = client + self._options = options + self._page_cls = page_cls + + def __await__(self) -> Generator[Any, None, AsyncPageT]: + return self._get_page().__await__() + + async def _get_page(self) -> AsyncPageT: + def _parser(resp: AsyncPageT) -> AsyncPageT: + resp._set_private_attributes( + model=self._model, + options=self._options, + client=self._client, + ) + return resp + + self._options.post_parser = _parser + + return await self._client.request(self._page_cls, self._options) + + async def __aiter__(self) -> AsyncIterator[_T]: + # https://github.com/microsoft/pyright/issues/3464 + page = cast( + AsyncPageT, + await self, # type: ignore + ) + async for item in page: + yield item + + +class BaseAsyncPage(BasePage[_T], Generic[_T]): + _client: AsyncAPIClient = pydantic.PrivateAttr() + + def _set_private_attributes( + self, + model: Type[_T], + client: AsyncAPIClient, + options: FinalRequestOptions, + ) -> None: + if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None: + self.__pydantic_private__ = {} + + self._model = model + self._client = client + self._options = options + + async def __aiter__(self) -> AsyncIterator[_T]: + async for page in self.iter_pages(): + for item in page._get_page_items(): + yield item + + async def iter_pages(self: AsyncPageT) -> AsyncIterator[AsyncPageT]: + page = self + while True: + yield page + if page.has_next_page(): + page = await page.get_next_page() + else: + return + + async def get_next_page(self: AsyncPageT) -> AsyncPageT: + info = self.next_page_info() + if not info: + raise RuntimeError( + "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`." + ) + + options = self._info_to_options(info) + return await self._client._request_api_list(self._model, page=self.__class__, options=options) + + +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]): + _client: _HttpxClientT + _version: str + _base_url: URL + max_retries: int + timeout: Union[float, Timeout, None] + _strict_response_validation: bool + _idempotency_header: str | None + _default_stream_cls: type[_DefaultStreamT] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + _strict_response_validation: bool, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None = DEFAULT_TIMEOUT, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + ) -> None: + self._version = version + self._base_url = self._enforce_trailing_slash(URL(base_url)) + self.max_retries = max_retries + self.timeout = timeout + self._custom_headers = custom_headers or {} + self._custom_query = custom_query or {} + self._strict_response_validation = _strict_response_validation + self._idempotency_header = None + self._platform: Platform | None = None + + if max_retries is None: # pyright: ignore[reportUnnecessaryComparison] + raise TypeError( + "max_retries cannot be None. If you want to disable retries, pass `0`; if you want unlimited retries, pass `math.inf` or a very high number; if you want the default behavior, pass `anthropic.DEFAULT_MAX_RETRIES`" + ) + + def _enforce_trailing_slash(self, url: URL) -> URL: + if url.raw_path.endswith(b"/"): + return url + return url.copy_with(raw_path=url.raw_path + b"/") + + def _make_status_error_from_response( + self, + response: httpx.Response, + ) -> APIStatusError: + if response.is_closed and not response.is_stream_consumed: + # We can't read the response body as it has been closed + # before it was read. This can happen if an event hook + # raises a status error. + body = None + err_msg = f"Error code: {response.status_code}" + else: + err_text = response.text.strip() + body = err_text + + try: + body = json.loads(err_text) + err_msg = f"Error code: {response.status_code} - {body}" + except Exception: + err_msg = err_text or f"Error code: {response.status_code}" + + return self._make_status_error(err_msg, body=body, response=response) + + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> _exceptions.APIStatusError: + raise NotImplementedError() + + def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0) -> httpx.Headers: + custom_headers = options.headers or {} + headers_dict = _merge_mappings( + { + "x-stainless-timeout": str(options.timeout.read) + if isinstance(options.timeout, Timeout) + else str(options.timeout), + **self.default_headers, + }, + custom_headers, + ) + self._validate_headers(headers_dict, custom_headers) + + # headers are case-insensitive while dictionaries are not. + headers = httpx.Headers(headers_dict) + + idempotency_header = self._idempotency_header + if idempotency_header and options.idempotency_key and idempotency_header not in headers: + headers[idempotency_header] = options.idempotency_key + + # Don't set these headers if they were already set or removed by the caller. We check + # `custom_headers`, which can contain `Omit()`, instead of `headers` to account for the removal case. + lower_custom_headers = [header.lower() for header in custom_headers] + if "x-stainless-retry-count" not in lower_custom_headers: + headers["x-stainless-retry-count"] = str(retries_taken) + if "x-stainless-read-timeout" not in lower_custom_headers: + timeout = self.timeout if isinstance(options.timeout, NotGiven) else options.timeout + if isinstance(timeout, Timeout): + timeout = timeout.read + if timeout is not None: + headers["x-stainless-read-timeout"] = str(timeout) + + return headers + + def _prepare_url(self, url: str) -> URL: + """ + Merge a URL argument together with any 'base_url' on the client, + to create the URL used for the outgoing request. + """ + # Copied from httpx's `_merge_url` method. + merge_url = URL(url) + if merge_url.is_relative_url: + merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") + return self.base_url.copy_with(raw_path=merge_raw_path) + + return merge_url + + def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder: + return SSEDecoder() + + def _build_request( + self, + options: FinalRequestOptions, + *, + retries_taken: int = 0, + ) -> httpx.Request: + if log.isEnabledFor(logging.DEBUG): + log.debug( + "Request options: %s", + model_dump( + options, + exclude_unset=True, + # Pydantic v1 can't dump every type we support in content, so we exclude it for now. + exclude={ + "content", + } + if PYDANTIC_V1 + else {}, + ), + ) + kwargs: dict[str, Any] = {} + + json_data = options.json_data + if options.extra_json is not None: + if json_data is None: + json_data = cast(Body, options.extra_json) + elif is_mapping(json_data): + json_data = _merge_mappings(json_data, options.extra_json) + else: + raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`") + + headers = self._build_headers(options, retries_taken=retries_taken) + params = _merge_mappings(self.default_query, options.params) + content_type = headers.get("Content-Type") + files = options.files + + # If the given Content-Type header is multipart/form-data then it + # has to be removed so that httpx can generate the header with + # additional information for us as it has to be in this form + # for the server to be able to correctly parse the request: + # multipart/form-data; boundary=---abc-- + if content_type is not None and content_type.startswith("multipart/form-data"): + if "boundary" not in content_type: + # only remove the header if the boundary hasn't been explicitly set + # as the caller doesn't want httpx to come up with their own boundary + headers.pop("Content-Type") + + # As we are now sending multipart/form-data instead of application/json + # we need to tell httpx to use it, https://www.python-httpx.org/advanced/clients/#multipart-file-encoding + if json_data: + if not is_dict(json_data): + raise TypeError( + f"Expected query input to be a dictionary for multipart requests but got {type(json_data)} instead." + ) + kwargs["data"] = self._serialize_multipartform(json_data) + + # httpx determines whether or not to send a "multipart/form-data" + # request based on the truthiness of the "files" argument. + # This gets around that issue by generating a dict value that + # evaluates to true. + # + # https://github.com/encode/httpx/discussions/2399#discussioncomment-3814186 + if not files: + files = cast(HttpxRequestFiles, ForceMultipartDict()) + + prepared_url = self._prepare_url(options.url) + # preserve hard-coded query params from the url + if params and prepared_url.query: + params = {**dict(prepared_url.params.items()), **params} + prepared_url = prepared_url.copy_with(raw_path=prepared_url.raw_path.split(b"?", 1)[0]) + if "_" in prepared_url.host: + # work around https://github.com/encode/httpx/discussions/2880 + kwargs["extensions"] = {"sni_hostname": prepared_url.host.replace("_", "-")} + + is_body_allowed = options.method.lower() != "get" + + if is_body_allowed: + if options.content is not None and json_data is not None: + raise TypeError("Passing both `content` and `json_data` is not supported") + if options.content is not None and files is not None: + raise TypeError("Passing both `content` and `files` is not supported") + if options.content is not None: + kwargs["content"] = options.content + elif isinstance(json_data, bytes): + kwargs["content"] = json_data + elif not files: + # Don't set content when JSON is sent as multipart/form-data, + # since httpx's content param overrides other body arguments + kwargs["content"] = openapi_dumps(json_data) if is_given(json_data) and json_data is not None else None + kwargs["files"] = files + else: + headers.pop("Content-Type", None) + kwargs.pop("data", None) + + # TODO: report this error to httpx + return self._client.build_request( # pyright: ignore[reportUnknownMemberType] + headers=headers, + timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout, + method=options.method, + url=prepared_url, + # the `Query` type that we use is incompatible with qs' + # `Params` type as it needs to be typed as `Mapping[str, object]` + # so that passing a `TypedDict` doesn't cause an error. + # https://github.com/microsoft/pyright/issues/3526#event-6715453066 + params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None, + **kwargs, + ) + + def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]: + items = self.qs.stringify_items( + # TODO: type ignore is required as stringify_items is well typed but we can't be + # well typed without heavy validation. + data, # type: ignore + array_format="brackets", + ) + serialized: dict[str, object] = {} + for key, value in items: + existing = serialized.get(key) + + if not existing: + serialized[key] = value + continue + + # If a value has already been set for this key then that + # means we're sending data like `array[]=[1, 2, 3]` and we + # need to tell httpx that we want to send multiple values with + # the same key which is done by using a list or a tuple. + # + # Note: 2d arrays should never result in the same key at both + # levels so it's safe to assume that if the value is a list, + # it was because we changed it to be a list. + if is_list(existing): + existing.append(value) + else: + serialized[key] = [existing, value] + + return serialized + + def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalRequestOptions) -> type[ResponseT]: + if not is_given(options.headers): + return cast_to + + # make a copy of the headers so we don't mutate user-input + headers = dict(options.headers) + + # we internally support defining a temporary header to override the + # default `cast_to` type for use with `.with_raw_response` and `.with_streaming_response` + # see _response.py for implementation details + override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, not_given) + if is_given(override_cast_to): + options.headers = headers + return cast(Type[ResponseT], override_cast_to) + + return cast_to + + def _should_stream_response_body(self, request: httpx.Request) -> bool: + return request.headers.get(RAW_RESPONSE_HEADER) == "stream" # type: ignore[no-any-return] + + def _process_response_data( + self, + *, + data: object, + cast_to: type[ResponseT], + response: httpx.Response, + ) -> ResponseT: + if data is None: + return cast(ResponseT, None) + + if cast_to is object: + return cast(ResponseT, data) + + try: + if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol): + return cast(ResponseT, cast_to.build(response=response, data=data)) + + if self._strict_response_validation: + return cast(ResponseT, validate_type(type_=cast_to, value=data)) + + return cast(ResponseT, construct_type(type_=cast_to, value=data)) + except pydantic.ValidationError as err: + raise APIResponseValidationError(response=response, body=data) from err + + @property + def qs(self) -> Querystring: + return Querystring() + + @property + def custom_auth(self) -> httpx.Auth | None: + return None + + @property + def auth_headers(self) -> dict[str, str]: + return {} + + @property + def default_headers(self) -> dict[str, str | Omit]: + return { + "Accept": "application/json", + "Content-Type": "application/json", + "User-Agent": self.user_agent, + **self.platform_headers(), + **self.auth_headers, + **self._custom_headers, + } + + @property + def default_query(self) -> dict[str, object]: + return { + **self._custom_query, + } + + def _validate_headers( + self, + headers: Headers, # noqa: ARG002 + custom_headers: Headers, # noqa: ARG002 + ) -> None: + """Validate the given default headers and custom headers. + + Does nothing by default. + """ + return + + @property + def user_agent(self) -> str: + return f"{self.__class__.__name__}/Python {self._version}" + + @property + def base_url(self) -> URL: + return self._base_url + + @base_url.setter + def base_url(self, url: URL | str) -> None: + self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url)) + + def platform_headers(self) -> Dict[str, str]: + # the actual implementation is in a separate `lru_cache` decorated + # function because adding `lru_cache` to methods will leak memory + # https://github.com/python/cpython/issues/88476 + return platform_headers(self._version, platform=self._platform) + + def _calculate_nonstreaming_timeout(self, max_tokens: int, max_nonstreaming_tokens: int | None) -> Timeout: + maximum_time = 60 * 60 + default_time = 60 * 10 + + expected_time = maximum_time * max_tokens / 128_000 + if expected_time > default_time or (max_nonstreaming_tokens and max_tokens > max_nonstreaming_tokens): + raise ValueError( + "Streaming is required for operations that may take longer than 10 minutes. " + + "See https://github.com/anthropics/anthropic-sdk-python#long-requests for more details", + ) + return Timeout( + default_time, + connect=5.0, + ) + + def _parse_retry_after_header(self, response_headers: Optional[httpx.Headers] = None) -> float | None: + """Returns a float of the number of seconds (not milliseconds) to wait after retrying, or None if unspecified. + + About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax + """ + if response_headers is None: + return None + + # First, try the non-standard `retry-after-ms` header for milliseconds, + # which is more precise than integer-seconds `retry-after` + try: + retry_ms_header = response_headers.get("retry-after-ms", None) + return float(retry_ms_header) / 1000 + except (TypeError, ValueError): + pass + + # Next, try parsing `retry-after` header as seconds (allowing nonstandard floats). + retry_header = response_headers.get("retry-after") + try: + # note: the spec indicates that this should only ever be an integer + # but if someone sends a float there's no reason for us to not respect it + return float(retry_header) + except (TypeError, ValueError): + pass + + # Last, try parsing `retry-after` as a date. + retry_date_tuple = email.utils.parsedate_tz(retry_header) + if retry_date_tuple is None: + return None + + retry_date = email.utils.mktime_tz(retry_date_tuple) + return float(retry_date - time.time()) + + def _calculate_retry_timeout( + self, + remaining_retries: int, + options: FinalRequestOptions, + response_headers: Optional[httpx.Headers] = None, + ) -> float: + max_retries = options.get_max_retries(self.max_retries) + + # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says. + retry_after = self._parse_retry_after_header(response_headers) + if retry_after is not None and 0 < retry_after <= 60: + return retry_after + + # Also cap retry count to 1000 to avoid any potential overflows with `pow` + nb_retries = min(max_retries - remaining_retries, 1000) + + # Apply exponential backoff, but not more than the max. + sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY) + + # Apply some jitter, plus-or-minus half a second. + jitter = 1 - 0.25 * random() + timeout = sleep_seconds * jitter + return timeout if timeout >= 0 else 0 + + def _should_retry(self, response: httpx.Response) -> bool: + # Note: this is not a standard header + should_retry_header = response.headers.get("x-should-retry") + + # If the server explicitly says whether or not to retry, obey. + if should_retry_header == "true": + log.debug("Retrying as header `x-should-retry` is set to `true`") + return True + if should_retry_header == "false": + log.debug("Not retrying as header `x-should-retry` is set to `false`") + return False + + # Retry on request timeouts. + if response.status_code == 408: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry on lock timeouts. + if response.status_code == 409: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry on rate limits. + if response.status_code == 429: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry internal errors. + if response.status_code >= 500: + log.debug("Retrying due to status code %i", response.status_code) + return True + + log.debug("Not retrying") + return False + + def _idempotency_key(self) -> str: + return f"stainless-python-retry-{uuid.uuid4()}" + + +class _DefaultHttpxClient(httpx.Client): + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + + if "transport" not in kwargs: + socket_options: List[Tuple[int, int, Union[int, bool]]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)] + + TCP_KEEPINTVL = getattr(socket, "TCP_KEEPINTVL", None) + + if TCP_KEEPINTVL is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPINTVL, 60)) + elif sys.platform == "darwin": + TCP_KEEPALIVE = getattr(socket, "TCP_KEEPALIVE", 0x10) + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPALIVE, 60)) + + TCP_KEEPCNT = getattr(socket, "TCP_KEEPCNT", None) + if TCP_KEEPCNT is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPCNT, 5)) + + TCP_KEEPIDLE = getattr(socket, "TCP_KEEPIDLE", None) + if TCP_KEEPIDLE is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPIDLE, 60)) + + proxy_map = {key: None if url is None else Proxy(url=url) for key, url in get_environment_proxies().items()} + + transport_kwargs = { + arg: kwargs[arg] for arg in ("verify", "cert", "trust_env", "http1", "http2", "limits") if arg in kwargs + } + + transport_kwargs["socket_options"] = socket_options + + proxy_mounts = { + key: None if proxy is None else HTTPTransport(proxy=proxy, **transport_kwargs) + for key, proxy in proxy_map.items() + } + default_transport = HTTPTransport(**transport_kwargs) + + # Prioritize the mounts set by the user over the environment variables. + proxy_mounts.update(kwargs.get("mounts", {})) + kwargs["mounts"] = proxy_mounts + + # Sets the default transport so that HTTPX won't automatically configure proxies. + kwargs["transport"] = default_transport + + super().__init__(**kwargs) + + +if TYPE_CHECKING: + DefaultHttpxClient = httpx.Client + """An alias to `httpx.Client` that provides the same defaults that this SDK + uses internally. + + This is useful because overriding the `http_client` with your own instance of + `httpx.Client` will result in httpx's defaults being used, not ours. + """ +else: + DefaultHttpxClient = _DefaultHttpxClient + + +class SyncHttpxClientWrapper(DefaultHttpxClient): + def __del__(self) -> None: + if self.is_closed: + return + + try: + self.close() + except Exception: + pass + + +class SyncAPIClient(BaseClient[httpx.Client, Stream[Any]]): + _client: httpx.Client + _default_stream_cls: type[Stream[Any]] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.Client | None = None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + _strict_response_validation: bool, + ) -> None: + if not is_given(timeout): + # if the user passed in a custom http client with a non-default + # timeout set then we use that timeout. + # + # note: there is an edge case here where the user passes in a client + # where they've explicitly set the timeout to match the default timeout + # as this check is structural, meaning that we'll think they didn't + # pass in a timeout and will ignore it + if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT: + timeout = http_client.timeout + else: + timeout = DEFAULT_TIMEOUT + + if http_client is not None and not isinstance(http_client, httpx.Client): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError( + f"Invalid `http_client` argument; Expected an instance of `httpx.Client` but got {type(http_client)}" + ) + + super().__init__( + version=version, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + base_url=base_url, + max_retries=max_retries, + custom_query=custom_query, + custom_headers=custom_headers, + _strict_response_validation=_strict_response_validation, + ) + self._client = http_client or SyncHttpxClientWrapper( + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + ) + + def is_closed(self) -> bool: + return self._client.is_closed + + def close(self) -> None: + """Close the underlying HTTPX client. + + The client will *not* be usable after this. + """ + # If an error is thrown while constructing a client, self._client + # may not be present + if hasattr(self, "_client"): + self._client.close() + + def __enter__(self: _T) -> _T: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def _prepare_options( + self, + options: FinalRequestOptions, # noqa: ARG002 + ) -> FinalRequestOptions: + """Hook for mutating the given options""" + return options + + def _prepare_request( + self, + request: httpx.Request, # noqa: ARG002 + ) -> None: + """This method is used as a callback for mutating the `Request` object + after it has been constructed. + This is useful for cases where you want to add certain headers based off of + the request properties, e.g. `url`, `method` etc. + """ + return None + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[True], + stream_cls: Type[_StreamT], + ) -> _StreamT: ... + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: Type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + cast_to = self._maybe_override_cast_to(cast_to, options) + + # create a copy of the options we were given so that if the + # options are mutated later & we then retry, the retries are + # given the original options + input_options = model_copy(options) + if input_options.idempotency_key is None and input_options.method.lower() != "get": + # ensure the idempotency key is reused between requests + input_options.idempotency_key = self._idempotency_key() + + response: httpx.Response | None = None + max_retries = input_options.get_max_retries(self.max_retries) + + retries_taken = 0 + for retries_taken in range(max_retries + 1): + options = model_copy(input_options) + options = self._prepare_options(options) + + remaining_retries = max_retries - retries_taken + request = self._build_request(options, retries_taken=retries_taken) + self._prepare_request(request) + + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + + if options.follow_redirects is not None: + kwargs["follow_redirects"] = options.follow_redirects + + log.debug("Sending HTTP Request: %s %s", request.method, request.url) + + response = None + try: + response = self._client.send( + request, + stream=stream or self._should_stream_response_body(request=request), + **kwargs, + ) + except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + + if remaining_retries > 0: + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising timeout error") + raise APITimeoutError(request=request) from err + except Exception as err: + log.debug("Encountered Exception", exc_info=True) + + if remaining_retries > 0: + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising connection error") + raise APIConnectionError(request=request) from err + + log.debug( + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, + ) + log.debug("request_id: %s", response.headers.get("request-id")) + + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + + if remaining_retries > 0 and self._should_retry(err.response): + err.response.close() + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=response, + ) + continue + + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + err.response.read() + + log.debug("Re-raising status error") + raise self._make_status_error_from_response(err.response) from None + + break + + assert response is not None, "could not resolve response (should never happen)" + return self._process_response( + cast_to=cast_to, + options=options, + response=response, + stream=stream, + stream_cls=stream_cls, + retries_taken=retries_taken, + ) + + def _sleep_for_retry( + self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None + ) -> None: + remaining_retries = max_retries - retries_taken + if remaining_retries == 1: + log.debug("1 retry left") + else: + log.debug("%i retries left", remaining_retries) + + timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None) + log.info("Retrying request to %s in %f seconds", options.url, timeout) + + time.sleep(timeout) + + def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + retries_taken: int = 0, + ) -> ResponseT: + if response.request.headers.get(RAW_RESPONSE_HEADER) == "true": + return cast( + ResponseT, + LegacyAPIResponse( + raw=response, + client=self, + cast_to=cast_to, + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ), + ) + + origin = get_origin(cast_to) or cast_to + + if ( + inspect.isclass(origin) + and issubclass(origin, BaseAPIResponse) + # we only want to actually return the custom BaseAPIResponse class if we're + # returning the raw response, or if we're not streaming SSE, as if we're streaming + # SSE then `cast_to` doesn't actively reflect the type we need to parse into + and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER))) + ): + if not issubclass(origin, APIResponse): + raise TypeError(f"API Response types must subclass {APIResponse}; Received {origin}") + + response_cls = cast("type[BaseAPIResponse[Any]]", cast_to) + return cast( + ResponseT, + response_cls( + raw=response, + client=self, + cast_to=extract_response_type(response_cls), + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ), + ) + + if cast_to == httpx.Response: + return cast(ResponseT, response) + + api_response = APIResponse( + raw=response, + client=self, + cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast] + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ) + if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): + return cast(ResponseT, api_response) + + return api_response.parse() + + def _request_api_list( + self, + model: Type[object], + page: Type[SyncPageT], + options: FinalRequestOptions, + ) -> SyncPageT: + def _parser(resp: SyncPageT) -> SyncPageT: + resp._set_private_attributes( + client=self, + model=model, + options=options, + ) + return resp + + options.post_parser = _parser + + return self.request(page, options, stream=False) + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_StreamT], + ) -> _StreamT: ... + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + opts = FinalRequestOptions.construct(method="get", url=path, **options) + # cast is required because mypy complains about returning Any even though + # it understands the type variables + return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: Literal[True], + stream_cls: type[_StreamT], + ) -> _StreamT: ... + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: bool, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="post", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) + + def patch( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="patch", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return self.request(cast_to, opts) + + def put( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="put", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return self.request(cast_to, opts) + + def delete( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options) + return self.request(cast_to, opts) + + def get_api_list( + self, + path: str, + *, + model: Type[object], + page: Type[SyncPageT], + body: Body | None = None, + options: RequestOptions = {}, + method: str = "get", + ) -> SyncPageT: + opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) + return self._request_api_list(model, page, opts) + + +class _DefaultAsyncHttpxClient(httpx.AsyncClient): + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + + if "transport" not in kwargs: + socket_options: List[Tuple[int, int, Union[int, bool]]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)] + + TCP_KEEPINTVL = getattr(socket, "TCP_KEEPINTVL", None) + + if TCP_KEEPINTVL is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPINTVL, 60)) + elif sys.platform == "darwin": + TCP_KEEPALIVE = getattr(socket, "TCP_KEEPALIVE", 0x10) + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPALIVE, 60)) + + TCP_KEEPCNT = getattr(socket, "TCP_KEEPCNT", None) + if TCP_KEEPCNT is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPCNT, 5)) + + TCP_KEEPIDLE = getattr(socket, "TCP_KEEPIDLE", None) + if TCP_KEEPIDLE is not None: + socket_options.append((socket.IPPROTO_TCP, TCP_KEEPIDLE, 60)) + + proxy_map = {key: None if url is None else Proxy(url=url) for key, url in get_environment_proxies().items()} + + transport_kwargs = { + arg: kwargs[arg] for arg in ("verify", "cert", "trust_env", "http1", "http2", "limits") if arg in kwargs + } + + transport_kwargs["socket_options"] = socket_options + + proxy_mounts = { + key: None if proxy is None else AsyncHTTPTransport(proxy=proxy, **transport_kwargs) + for key, proxy in proxy_map.items() + } + default_transport = AsyncHTTPTransport(**transport_kwargs) + + # Prioritize the mounts set by the user over the environment variables. + proxy_mounts.update(kwargs.get("mounts", {})) + kwargs["mounts"] = proxy_mounts + + # Sets the default transport so that HTTPX won't automatically configure proxies. + kwargs["transport"] = default_transport + + super().__init__(**kwargs) + + +try: + import httpx_aiohttp +except ImportError: + + class _DefaultAioHttpClient(httpx.AsyncClient): + def __init__(self, **_kwargs: Any) -> None: + raise RuntimeError("To use the aiohttp client you must have installed the package with the `aiohttp` extra") +else: + + class _DefaultAioHttpClient(httpx_aiohttp.HttpxAiohttpClient): # type: ignore + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + + super().__init__(**kwargs) + + +if TYPE_CHECKING: + DefaultAsyncHttpxClient = httpx.AsyncClient + """An alias to `httpx.AsyncClient` that provides the same defaults that this SDK + uses internally. + + This is useful because overriding the `http_client` with your own instance of + `httpx.AsyncClient` will result in httpx's defaults being used, not ours. + """ + + DefaultAioHttpClient = httpx.AsyncClient + """An alias to `httpx.AsyncClient` that changes the default HTTP transport to `aiohttp`.""" +else: + DefaultAsyncHttpxClient = _DefaultAsyncHttpxClient + DefaultAioHttpClient = _DefaultAioHttpClient + + +class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient): + def __del__(self) -> None: + if self.is_closed: + return + + try: + # TODO(someday): support non asyncio runtimes here + asyncio.get_running_loop().create_task(self.aclose()) + except Exception: + pass + + +class AsyncAPIClient(BaseClient[httpx.AsyncClient, AsyncStream[Any]]): + _client: httpx.AsyncClient + _default_stream_cls: type[AsyncStream[Any]] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + _strict_response_validation: bool, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.AsyncClient | None = None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + ) -> None: + if not is_given(timeout): + # if the user passed in a custom http client with a non-default + # timeout set then we use that timeout. + # + # note: there is an edge case here where the user passes in a client + # where they've explicitly set the timeout to match the default timeout + # as this check is structural, meaning that we'll think they didn't + # pass in a timeout and will ignore it + if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT: + timeout = http_client.timeout + else: + timeout = DEFAULT_TIMEOUT + + if http_client is not None and not isinstance(http_client, httpx.AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError( + f"Invalid `http_client` argument; Expected an instance of `httpx.AsyncClient` but got {type(http_client)}" + ) + + super().__init__( + version=version, + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + max_retries=max_retries, + custom_query=custom_query, + custom_headers=custom_headers, + _strict_response_validation=_strict_response_validation, + ) + self._client = http_client or AsyncHttpxClientWrapper( + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + ) + + def is_closed(self) -> bool: + return self._client.is_closed + + async def close(self) -> None: + """Close the underlying HTTPX client. + + The client will *not* be usable after this. + """ + await self._client.aclose() + + async def __aenter__(self: _T) -> _T: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def _prepare_options( + self, + options: FinalRequestOptions, # noqa: ARG002 + ) -> FinalRequestOptions: + """Hook for mutating the given options""" + return options + + async def _prepare_request( + self, + request: httpx.Request, # noqa: ARG002 + ) -> None: + """This method is used as a callback for mutating the `Request` object + after it has been constructed. + This is useful for cases where you want to add certain headers based off of + the request properties, e.g. `url`, `method` etc. + """ + return None + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + if self._platform is None: + # `get_platform` can make blocking IO calls so we + # execute it earlier while we are in an async context + self._platform = await asyncify(get_platform)() + + cast_to = self._maybe_override_cast_to(cast_to, options) + + # create a copy of the options we were given so that if the + # options are mutated later & we then retry, the retries are + # given the original options + input_options = model_copy(options) + if input_options.idempotency_key is None and input_options.method.lower() != "get": + # ensure the idempotency key is reused between requests + input_options.idempotency_key = self._idempotency_key() + + response: httpx.Response | None = None + max_retries = input_options.get_max_retries(self.max_retries) + + retries_taken = 0 + for retries_taken in range(max_retries + 1): + options = model_copy(input_options) + options = await self._prepare_options(options) + + remaining_retries = max_retries - retries_taken + request = self._build_request(options, retries_taken=retries_taken) + await self._prepare_request(request) + + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + + if options.follow_redirects is not None: + kwargs["follow_redirects"] = options.follow_redirects + + log.debug("Sending HTTP Request: %s %s", request.method, request.url) + + response = None + try: + response = await self._client.send( + request, + stream=stream or self._should_stream_response_body(request=request), + **kwargs, + ) + except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + + if remaining_retries > 0: + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising timeout error") + raise APITimeoutError(request=request) from err + except Exception as err: + log.debug("Encountered Exception", exc_info=True) + + if remaining_retries > 0: + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising connection error") + raise APIConnectionError(request=request) from err + + log.debug( + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, + ) + log.debug("request_id: %s", response.headers.get("request-id")) + + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + + if remaining_retries > 0 and self._should_retry(err.response): + await err.response.aclose() + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=response, + ) + continue + + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + await err.response.aread() + + log.debug("Re-raising status error") + raise self._make_status_error_from_response(err.response) from None + + break + + assert response is not None, "could not resolve response (should never happen)" + return await self._process_response( + cast_to=cast_to, + options=options, + response=response, + stream=stream, + stream_cls=stream_cls, + retries_taken=retries_taken, + ) + + async def _sleep_for_retry( + self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None + ) -> None: + remaining_retries = max_retries - retries_taken + if remaining_retries == 1: + log.debug("1 retry left") + else: + log.debug("%i retries left", remaining_retries) + + timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None) + log.info("Retrying request to %s in %f seconds", options.url, timeout) + + await anyio.sleep(timeout) + + async def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + retries_taken: int = 0, + ) -> ResponseT: + if response.request.headers.get(RAW_RESPONSE_HEADER) == "true": + return cast( + ResponseT, + LegacyAPIResponse( + raw=response, + client=self, + cast_to=cast_to, + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ), + ) + + origin = get_origin(cast_to) or cast_to + + if ( + inspect.isclass(origin) + and issubclass(origin, BaseAPIResponse) + # we only want to actually return the custom BaseAPIResponse class if we're + # returning the raw response, or if we're not streaming SSE, as if we're streaming + # SSE then `cast_to` doesn't actively reflect the type we need to parse into + and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER))) + ): + if not issubclass(origin, AsyncAPIResponse): + raise TypeError(f"API Response types must subclass {AsyncAPIResponse}; Received {origin}") + + response_cls = cast("type[BaseAPIResponse[Any]]", cast_to) + return cast( + "ResponseT", + response_cls( + raw=response, + client=self, + cast_to=extract_response_type(response_cls), + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ), + ) + + if cast_to == httpx.Response: + return cast(ResponseT, response) + + api_response = AsyncAPIResponse( + raw=response, + client=self, + cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast] + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ) + if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): + return cast(ResponseT, api_response) + + return await api_response.parse() + + def _request_api_list( + self, + model: Type[_T], + page: Type[AsyncPageT], + options: FinalRequestOptions, + ) -> AsyncPaginator[_T, AsyncPageT]: + return AsyncPaginator(client=self, options=options, page_cls=page, model=model) + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + opts = FinalRequestOptions.construct(method="get", url=path, **options) + return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls) + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="post", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options + ) + return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls) + + async def patch( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="patch", + url=path, + json_data=body, + content=content, + files=await async_to_httpx_files(files), + **options, + ) + return await self.request(cast_to, opts) + + async def put( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="put", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options + ) + return await self.request(cast_to, opts) + + async def delete( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options) + return await self.request(cast_to, opts) + + def get_api_list( + self, + path: str, + *, + model: Type[_T], + page: Type[AsyncPageT], + body: Body | None = None, + options: RequestOptions = {}, + method: str = "get", + ) -> AsyncPaginator[_T, AsyncPageT]: + opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) + return self._request_api_list(model, page, opts) + + +def make_request_options( + *, + query: Query | None = None, + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + idempotency_key: str | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + post_parser: PostParser | NotGiven = not_given, +) -> RequestOptions: + """Create a dict of type RequestOptions without keys of NotGiven values.""" + options: RequestOptions = {} + if extra_headers is not None: + options["headers"] = extra_headers + + if extra_body is not None: + options["extra_json"] = cast(AnyMapping, extra_body) + + if query is not None: + options["params"] = query + + if extra_query is not None: + options["params"] = {**options.get("params", {}), **extra_query} + + if not isinstance(timeout, NotGiven): + options["timeout"] = timeout + + if idempotency_key is not None: + options["idempotency_key"] = idempotency_key + + if is_given(post_parser): + # internal + options["post_parser"] = post_parser # type: ignore + + return options + + +class ForceMultipartDict(Dict[str, None]): + def __bool__(self) -> bool: + return True + + +class OtherPlatform: + def __init__(self, name: str) -> None: + self.name = name + + @override + def __str__(self) -> str: + return f"Other:{self.name}" + + +Platform = Union[ + OtherPlatform, + Literal[ + "MacOS", + "Linux", + "Windows", + "FreeBSD", + "OpenBSD", + "iOS", + "Android", + "Unknown", + ], +] + + +def get_platform() -> Platform: + try: + system = platform.system().lower() + platform_name = platform.platform().lower() + except Exception: + return "Unknown" + + if "iphone" in platform_name or "ipad" in platform_name: + # Tested using Python3IDE on an iPhone 11 and Pythonista on an iPad 7 + # system is Darwin and platform_name is a string like: + # - Darwin-21.6.0-iPhone12,1-64bit + # - Darwin-21.6.0-iPad7,11-64bit + return "iOS" + + if system == "darwin": + return "MacOS" + + if system == "windows": + return "Windows" + + if "android" in platform_name: + # Tested using Pydroid 3 + # system is Linux and platform_name is a string like 'Linux-5.10.81-android12-9-00001-geba40aecb3b7-ab8534902-aarch64-with-libc' + return "Android" + + if system == "linux": + # https://distro.readthedocs.io/en/latest/#distro.id + distro_id = distro.id() + if distro_id == "freebsd": + return "FreeBSD" + + if distro_id == "openbsd": + return "OpenBSD" + + return "Linux" + + if platform_name: + return OtherPlatform(platform_name) + + return "Unknown" + + +@lru_cache(maxsize=None) +def platform_headers(version: str, *, platform: Platform | None) -> Dict[str, str]: + return { + "X-Stainless-Lang": "python", + "X-Stainless-Package-Version": version, + "X-Stainless-OS": str(platform or get_platform()), + "X-Stainless-Arch": str(get_architecture()), + "X-Stainless-Runtime": get_python_runtime(), + "X-Stainless-Runtime-Version": get_python_version(), + } + + +class OtherArch: + def __init__(self, name: str) -> None: + self.name = name + + @override + def __str__(self) -> str: + return f"other:{self.name}" + + +Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]] + + +def get_python_runtime() -> str: + try: + return platform.python_implementation() + except Exception: + return "unknown" + + +def get_python_version() -> str: + try: + return platform.python_version() + except Exception: + return "unknown" + + +def get_architecture() -> Arch: + try: + machine = platform.machine().lower() + except Exception: + return "unknown" + + if machine in ("arm64", "aarch64"): + return "arm64" + + # TODO: untested + if machine == "arm": + return "arm" + + if machine == "x86_64": + return "x64" + + # TODO: untested + if sys.maxsize <= 2**32: + return "x32" + + if machine: + return OtherArch(machine) + + return "unknown" + + +def _merge_mappings( + obj1: Mapping[_T_co, Union[_T, Omit]], + obj2: Mapping[_T_co, Union[_T, Omit]], +) -> Dict[_T_co, _T]: + """Merge two mappings of the same type, removing any values that are instances of `Omit`. + + In cases with duplicate keys the second mapping takes precedence. + """ + merged = {**obj1, **obj2} + return {key: value for key, value in merged.items() if not isinstance(value, Omit)} diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_client.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..accf652dca612cc26bcafb07f91814cbf2567d38 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_client.py @@ -0,0 +1,659 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING, Any, Mapping +from typing_extensions import Self, override + +import httpx + +from . import _constants, _exceptions +from ._qs import Querystring +from ._types import ( + Omit, + Headers, + Timeout, + NotGiven, + Transport, + ProxiesTypes, + RequestOptions, + not_given, +) +from ._utils import is_given, get_async_library +from ._compat import cached_property +from ._version import __version__ +from ._streaming import Stream as Stream, AsyncStream as AsyncStream +from ._exceptions import APIStatusError +from ._base_client import ( + DEFAULT_MAX_RETRIES, + SyncAPIClient, + AsyncAPIClient, +) + +if TYPE_CHECKING: + from .resources import beta, models, messages, completions + from .resources.models import Models, AsyncModels + from .resources.beta.beta import Beta, AsyncBeta + from .resources.completions import Completions, AsyncCompletions + from .resources.messages.messages import Messages, AsyncMessages + +__all__ = [ + "Timeout", + "Transport", + "ProxiesTypes", + "RequestOptions", + "Anthropic", + "AsyncAnthropic", + "Client", + "AsyncClient", +] + + +class Anthropic(SyncAPIClient): + # client options + api_key: str | None + auth_token: str | None + + # constants + HUMAN_PROMPT = _constants.HUMAN_PROMPT + AI_PROMPT = _constants.AI_PROMPT + + def __init__( + self, + *, + api_key: str | None = None, + auth_token: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. + # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`. + # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: httpx.Client | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + """Construct a new synchronous Anthropic client instance. + + This automatically infers the following arguments from their corresponding environment variables if they are not provided: + - `api_key` from `ANTHROPIC_API_KEY` + - `auth_token` from `ANTHROPIC_AUTH_TOKEN` + """ + if api_key is None: + api_key = os.environ.get("ANTHROPIC_API_KEY") + self.api_key = api_key + + if auth_token is None: + auth_token = os.environ.get("ANTHROPIC_AUTH_TOKEN") + self.auth_token = auth_token + + if base_url is None: + base_url = os.environ.get("ANTHROPIC_BASE_URL") + if base_url is None: + base_url = f"https://api.anthropic.com" + + super().__init__( + version=__version__, + base_url=base_url, + max_retries=max_retries, + timeout=timeout, + http_client=http_client, + custom_headers=default_headers, + custom_query=default_query, + _strict_response_validation=_strict_response_validation, + ) + + self._default_stream_cls = Stream + + @cached_property + def completions(self) -> Completions: + from .resources.completions import Completions + + return Completions(self) + + @cached_property + def messages(self) -> Messages: + from .resources.messages import Messages + + return Messages(self) + + @cached_property + def models(self) -> Models: + from .resources.models import Models + + return Models(self) + + @cached_property + def beta(self) -> Beta: + from .resources.beta import Beta + + return Beta(self) + + @cached_property + def with_raw_response(self) -> AnthropicWithRawResponse: + return AnthropicWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AnthropicWithStreamedResponse: + return AnthropicWithStreamedResponse(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + return {**self._api_key_auth, **self._bearer_auth} + + @property + def _api_key_auth(self) -> dict[str, str]: + api_key = self.api_key + if api_key is None: + return {} + return {"X-Api-Key": api_key} + + @property + def _bearer_auth(self) -> dict[str, str]: + auth_token = self.auth_token + if auth_token is None: + return {} + return {"Authorization": f"Bearer {auth_token}"} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + "X-Stainless-Async": "false", + "anthropic-version": "2023-06-01", + **self._custom_headers, + } + + @override + def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None: + if headers.get("Authorization") or headers.get("X-Api-Key"): + # valid + return + + if headers.get("X-Api-Key") or isinstance(custom_headers.get("X-Api-Key"), Omit): + return + + if headers.get("Authorization") or isinstance(custom_headers.get("Authorization"), Omit): + return + + raise TypeError( + '"Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted"' + ) + + def copy( + self, + *, + api_key: str | None = None, + auth_token: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = not_given, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + return self.__class__( + api_key=api_key or self.api_key, + auth_token=auth_token or self.auth_token, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 413: + return _exceptions.RequestTooLargeError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code == 529: + return _exceptions.OverloadedError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class AsyncAnthropic(AsyncAPIClient): + # client options + api_key: str | None + auth_token: str | None + + # constants + HUMAN_PROMPT = _constants.HUMAN_PROMPT + AI_PROMPT = _constants.AI_PROMPT + + def __init__( + self, + *, + api_key: str | None = None, + auth_token: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. + # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`. + # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details. + http_client: httpx.AsyncClient | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + """Construct a new async AsyncAnthropic client instance. + + This automatically infers the following arguments from their corresponding environment variables if they are not provided: + - `api_key` from `ANTHROPIC_API_KEY` + - `auth_token` from `ANTHROPIC_AUTH_TOKEN` + """ + if api_key is None: + api_key = os.environ.get("ANTHROPIC_API_KEY") + self.api_key = api_key + + if auth_token is None: + auth_token = os.environ.get("ANTHROPIC_AUTH_TOKEN") + self.auth_token = auth_token + + if base_url is None: + base_url = os.environ.get("ANTHROPIC_BASE_URL") + if base_url is None: + base_url = f"https://api.anthropic.com" + + super().__init__( + version=__version__, + base_url=base_url, + max_retries=max_retries, + timeout=timeout, + http_client=http_client, + custom_headers=default_headers, + custom_query=default_query, + _strict_response_validation=_strict_response_validation, + ) + + self._default_stream_cls = AsyncStream + + @cached_property + def completions(self) -> AsyncCompletions: + from .resources.completions import AsyncCompletions + + return AsyncCompletions(self) + + @cached_property + def messages(self) -> AsyncMessages: + from .resources.messages import AsyncMessages + + return AsyncMessages(self) + + @cached_property + def models(self) -> AsyncModels: + from .resources.models import AsyncModels + + return AsyncModels(self) + + @cached_property + def beta(self) -> AsyncBeta: + from .resources.beta import AsyncBeta + + return AsyncBeta(self) + + @cached_property + def with_raw_response(self) -> AsyncAnthropicWithRawResponse: + return AsyncAnthropicWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncAnthropicWithStreamedResponse: + return AsyncAnthropicWithStreamedResponse(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + return {**self._api_key_auth, **self._bearer_auth} + + @property + def _api_key_auth(self) -> dict[str, str]: + api_key = self.api_key + if api_key is None: + return {} + return {"X-Api-Key": api_key} + + @property + def _bearer_auth(self) -> dict[str, str]: + auth_token = self.auth_token + if auth_token is None: + return {} + return {"Authorization": f"Bearer {auth_token}"} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + "X-Stainless-Async": f"async:{get_async_library()}", + "anthropic-version": "2023-06-01", + **self._custom_headers, + } + + @override + def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None: + if headers.get("Authorization") or headers.get("X-Api-Key"): + # valid + return + + if headers.get("X-Api-Key") or isinstance(custom_headers.get("X-Api-Key"), Omit): + return + + if headers.get("Authorization") or isinstance(custom_headers.get("Authorization"), Omit): + return + + raise TypeError( + '"Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted"' + ) + + def copy( + self, + *, + api_key: str | None = None, + auth_token: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = not_given, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + return self.__class__( + api_key=api_key or self.api_key, + auth_token=auth_token or self.auth_token, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 413: + return _exceptions.RequestTooLargeError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code == 529: + return _exceptions.OverloadedError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class AnthropicWithRawResponse: + _client: Anthropic + + def __init__(self, client: Anthropic) -> None: + self._client = client + + @cached_property + def completions(self) -> completions.CompletionsWithRawResponse: + from .resources.completions import CompletionsWithRawResponse + + return CompletionsWithRawResponse(self._client.completions) + + @cached_property + def messages(self) -> messages.MessagesWithRawResponse: + from .resources.messages import MessagesWithRawResponse + + return MessagesWithRawResponse(self._client.messages) + + @cached_property + def models(self) -> models.ModelsWithRawResponse: + from .resources.models import ModelsWithRawResponse + + return ModelsWithRawResponse(self._client.models) + + @cached_property + def beta(self) -> beta.BetaWithRawResponse: + from .resources.beta import BetaWithRawResponse + + return BetaWithRawResponse(self._client.beta) + + +class AsyncAnthropicWithRawResponse: + _client: AsyncAnthropic + + def __init__(self, client: AsyncAnthropic) -> None: + self._client = client + + @cached_property + def completions(self) -> completions.AsyncCompletionsWithRawResponse: + from .resources.completions import AsyncCompletionsWithRawResponse + + return AsyncCompletionsWithRawResponse(self._client.completions) + + @cached_property + def messages(self) -> messages.AsyncMessagesWithRawResponse: + from .resources.messages import AsyncMessagesWithRawResponse + + return AsyncMessagesWithRawResponse(self._client.messages) + + @cached_property + def models(self) -> models.AsyncModelsWithRawResponse: + from .resources.models import AsyncModelsWithRawResponse + + return AsyncModelsWithRawResponse(self._client.models) + + @cached_property + def beta(self) -> beta.AsyncBetaWithRawResponse: + from .resources.beta import AsyncBetaWithRawResponse + + return AsyncBetaWithRawResponse(self._client.beta) + + +class AnthropicWithStreamedResponse: + _client: Anthropic + + def __init__(self, client: Anthropic) -> None: + self._client = client + + @cached_property + def completions(self) -> completions.CompletionsWithStreamingResponse: + from .resources.completions import CompletionsWithStreamingResponse + + return CompletionsWithStreamingResponse(self._client.completions) + + @cached_property + def messages(self) -> messages.MessagesWithStreamingResponse: + from .resources.messages import MessagesWithStreamingResponse + + return MessagesWithStreamingResponse(self._client.messages) + + @cached_property + def models(self) -> models.ModelsWithStreamingResponse: + from .resources.models import ModelsWithStreamingResponse + + return ModelsWithStreamingResponse(self._client.models) + + @cached_property + def beta(self) -> beta.BetaWithStreamingResponse: + from .resources.beta import BetaWithStreamingResponse + + return BetaWithStreamingResponse(self._client.beta) + + +class AsyncAnthropicWithStreamedResponse: + _client: AsyncAnthropic + + def __init__(self, client: AsyncAnthropic) -> None: + self._client = client + + @cached_property + def completions(self) -> completions.AsyncCompletionsWithStreamingResponse: + from .resources.completions import AsyncCompletionsWithStreamingResponse + + return AsyncCompletionsWithStreamingResponse(self._client.completions) + + @cached_property + def messages(self) -> messages.AsyncMessagesWithStreamingResponse: + from .resources.messages import AsyncMessagesWithStreamingResponse + + return AsyncMessagesWithStreamingResponse(self._client.messages) + + @cached_property + def models(self) -> models.AsyncModelsWithStreamingResponse: + from .resources.models import AsyncModelsWithStreamingResponse + + return AsyncModelsWithStreamingResponse(self._client.models) + + @cached_property + def beta(self) -> beta.AsyncBetaWithStreamingResponse: + from .resources.beta import AsyncBetaWithStreamingResponse + + return AsyncBetaWithStreamingResponse(self._client.beta) + + +Client = Anthropic + +AsyncClient = AsyncAnthropic diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_compat.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..4d7e4b030f64bc8174258fa5abb318c5f3e28ebc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_compat.py @@ -0,0 +1,232 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload +from datetime import date, datetime +from typing_extensions import Self, Literal, TypedDict + +import pydantic +from pydantic.fields import FieldInfo + +from ._types import IncEx, StrBytesIntFloat + +_T = TypeVar("_T") +_ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel) + +# --------------- Pydantic v2, v3 compatibility --------------- + +# Pyright incorrectly reports some of our functions as overriding a method when they don't +# pyright: reportIncompatibleMethodOverride=false + +PYDANTIC_V1 = pydantic.VERSION.startswith("1.") + +if TYPE_CHECKING: + + def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001 + ... + + def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001 + ... + + def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001 + ... + + def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001 + ... + + def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001 + ... + + def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001 + ... + + def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 + ... + +else: + # v1 re-exports + if PYDANTIC_V1: + from pydantic.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime + else: + from ._utils import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + parse_date as parse_date, + is_typeddict as is_typeddict, + parse_datetime as parse_datetime, + is_literal_type as is_literal_type, + ) + + +# refactored config +if TYPE_CHECKING: + from pydantic import ConfigDict as ConfigDict +else: + if PYDANTIC_V1: + # TODO: provide an error message here? + ConfigDict = None + else: + from pydantic import ConfigDict as ConfigDict + + +# renamed methods / properties +def parse_obj(model: type[_ModelT], value: object) -> _ModelT: + if PYDANTIC_V1: + return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + else: + return model.model_validate(value) + + +def field_is_required(field: FieldInfo) -> bool: + if PYDANTIC_V1: + return field.required # type: ignore + return field.is_required() + + +def field_get_default(field: FieldInfo) -> Any: + value = field.get_default() + if PYDANTIC_V1: + return value + from pydantic_core import PydanticUndefined + + if value == PydanticUndefined: + return None + return value + + +def field_outer_type(field: FieldInfo) -> Any: + if PYDANTIC_V1: + return field.outer_type_ # type: ignore + return field.annotation + + +def get_model_config(model: type[pydantic.BaseModel]) -> Any: + if PYDANTIC_V1: + return model.__config__ # type: ignore + return model.model_config + + +def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]: + if PYDANTIC_V1: + return model.__fields__ # type: ignore + return model.model_fields + + +def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT: + if PYDANTIC_V1: + return model.copy(deep=deep) # type: ignore + return model.model_copy(deep=deep) + + +def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: + if PYDANTIC_V1: + return model.json(indent=indent) # type: ignore + return model.model_dump_json(indent=indent) + + +def model_parse_json(model: type[_ModelT], data: str | bytes) -> _ModelT: + if PYDANTIC_V1: + return model.parse_raw(data) # pyright: ignore[reportDeprecated] + return model.model_validate_json(data) + + +class _ModelDumpKwargs(TypedDict, total=False): + by_alias: bool + + +def model_dump( + model: pydantic.BaseModel, + *, + exclude: IncEx | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + warnings: bool = True, + mode: Literal["json", "python"] = "python", + by_alias: bool | None = None, +) -> dict[str, Any]: + if (not PYDANTIC_V1) or hasattr(model, "model_dump"): + kwargs: _ModelDumpKwargs = {} + if by_alias is not None: + kwargs["by_alias"] = by_alias + return model.model_dump( + mode=mode, + exclude=exclude, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + # warnings are not supported in Pydantic v1 + warnings=True if PYDANTIC_V1 else warnings, + **kwargs, + ) + return cast( + "dict[str, Any]", + model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias) + ), + ) + + +def model_parse(model: type[_ModelT], data: Any) -> _ModelT: + if PYDANTIC_V1: + return model.parse_obj(data) # pyright: ignore[reportDeprecated] + return model.model_validate(data) + + +# generic models +if TYPE_CHECKING: + + class GenericModel(pydantic.BaseModel): ... + +else: + if PYDANTIC_V1: + import pydantic.generics + + class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ... + else: + # there no longer needs to be a distinction in v2 but + # we still have to create our own subclass to avoid + # inconsistent MRO ordering errors + class GenericModel(pydantic.BaseModel): ... + + +# cached properties +if TYPE_CHECKING: + cached_property = property + + # we define a separate type (copied from typeshed) + # that represents that `cached_property` is `set`able + # at runtime, which differs from `@property`. + # + # this is a separate type as editors likely special case + # `@property` and we don't want to cause issues just to have + # more helpful internal types. + + class typed_cached_property(Generic[_T]): + func: Callable[[Any], _T] + attrname: str | None + + def __init__(self, func: Callable[[Any], _T]) -> None: ... + + @overload + def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... + + @overload + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ... + + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self: + raise NotImplementedError() + + def __set_name__(self, owner: type[Any], name: str) -> None: ... + + # __set__ is not defined at runtime, but @cached_property is designed to be settable + def __set__(self, instance: object, value: _T) -> None: ... +else: + from functools import cached_property as cached_property + + typed_cached_property = cached_property diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_constants.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..58929cb89c5473107c37709da54b258d1ef56f54 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_constants.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import httpx + +RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response" +OVERRIDE_CAST_TO_HEADER = "____stainless_override_cast_to" + +# default timeout is 10 minutes +DEFAULT_TIMEOUT = httpx.Timeout(timeout=10 * 60, connect=5.0) +DEFAULT_MAX_RETRIES = 2 +DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=1000, max_keepalive_connections=100) + +INITIAL_RETRY_DELAY = 0.5 +MAX_RETRY_DELAY = 8.0 + +HUMAN_PROMPT = "\n\nHuman:" + +AI_PROMPT = "\n\nAssistant:" + +MODEL_NONSTREAMING_TOKENS = { + "claude-opus-4-20250514": 8_192, + "claude-opus-4-0": 8_192, + "claude-4-opus-20250514": 8_192, + "anthropic.claude-opus-4-20250514-v1:0": 8_192, + "claude-opus-4@20250514": 8_192, + "claude-opus-4-1-20250805": 8192, + "anthropic.claude-opus-4-1-20250805-v1:0": 8192, + "claude-opus-4-1@20250805": 8192, +} diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_exceptions.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..c5b74870223a84b6075b8eee5d7c7286f2f3b491 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_exceptions.py @@ -0,0 +1,140 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, cast +from typing_extensions import Literal + +import httpx + +from ._utils import is_dict +from .types.shared.error_type import ErrorType + +__all__ = [ + "BadRequestError", + "AuthenticationError", + "PermissionDeniedError", + "NotFoundError", + "ConflictError", + "UnprocessableEntityError", + "RateLimitError", + "InternalServerError", +] + + +class AnthropicError(Exception): + pass + + +class APIError(AnthropicError): + message: str + request: httpx.Request + + body: object | None + """The API response body. + + If the API responded with a valid JSON structure then this property will be the + decoded result. + + If it isn't a valid JSON structure then this will be the raw response. + + If there was no response associated with this error then it will be `None`. + """ + + def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: # noqa: ARG002 + super().__init__(message) + self.request = request + self.message = message + self.body = body + + +class APIResponseValidationError(APIError): + response: httpx.Response + status_code: int + + def __init__(self, response: httpx.Response, body: object | None, *, message: str | None = None) -> None: + super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body) + self.response = response + self.status_code = response.status_code + + +class APIStatusError(APIError): + """Raised when an API response has a status code of 4xx or 5xx.""" + + response: httpx.Response + status_code: int + request_id: str | None + type: ErrorType | None + + def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None: + super().__init__(message, response.request, body=body) + self.response = response + self.status_code = response.status_code + self.request_id = response.headers.get("request-id") + + self.type = None + if is_dict(body): + error = body.get("error") + if is_dict(error): + self.type = cast(Union[ErrorType, None], error.get("type")) + + +class APIConnectionError(APIError): + def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None: + super().__init__(message, request, body=None) + + +class APITimeoutError(APIConnectionError): + def __init__(self, request: httpx.Request) -> None: + super().__init__( + message="Request timed out or interrupted. This could be due to a network timeout, dropped connection, or request cancellation. See https://docs.anthropic.com/en/api/errors#long-requests for more details.", + request=request, + ) + + +class BadRequestError(APIStatusError): + status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride] + + +class AuthenticationError(APIStatusError): + status_code: Literal[401] = 401 # pyright: ignore[reportIncompatibleVariableOverride] + + +class PermissionDeniedError(APIStatusError): + status_code: Literal[403] = 403 # pyright: ignore[reportIncompatibleVariableOverride] + + +class NotFoundError(APIStatusError): + status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride] + + +class ConflictError(APIStatusError): + status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride] + + +class RequestTooLargeError(APIStatusError): + status_code: Literal[413] = 413 # pyright: ignore[reportIncompatibleVariableOverride] + + +class UnprocessableEntityError(APIStatusError): + status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride] + + +class RateLimitError(APIStatusError): + status_code: Literal[429] = 429 # pyright: ignore[reportIncompatibleVariableOverride] + + +class ServiceUnavailableError(APIStatusError): + status_code: Literal[503] = 503 # pyright: ignore[reportIncompatibleVariableOverride] + + +class OverloadedError(APIStatusError): + status_code: Literal[529] = 529 # pyright: ignore[reportIncompatibleVariableOverride] + + +class DeadlineExceededError(APIStatusError): + status_code: Literal[504] = 504 # pyright: ignore[reportIncompatibleVariableOverride] + + +class InternalServerError(APIStatusError): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_files.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_files.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a6f94e76626bfbd0c2715f4b2035bcd4a5d9d8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_files.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import io +import os +import pathlib +from typing import overload +from typing_extensions import TypeGuard + +import anyio + +from ._types import ( + FileTypes, + FileContent, + RequestFiles, + HttpxFileTypes, + Base64FileInput, + HttpxFileContent, + HttpxRequestFiles, +) +from ._utils import is_tuple_t, is_mapping_t, is_sequence_t + + +def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]: + return isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) + + +def is_file_content(obj: object) -> TypeGuard[FileContent]: + return ( + isinstance(obj, bytes) or isinstance(obj, tuple) or isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) + ) + + +def assert_is_file_content(obj: object, *, key: str | None = None) -> None: + if not is_file_content(obj): + prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`" + raise RuntimeError( + f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/anthropics/anthropic-sdk-python/tree/main#file-uploads" + ) from None + + +@overload +def to_httpx_files(files: None) -> None: ... + + +@overload +def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... + + +def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: + if files is None: + return None + + if is_mapping_t(files): + files = {key: _transform_file(file) for key, file in files.items()} + elif is_sequence_t(files): + files = [(key, _transform_file(file)) for key, file in files] + else: + raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence") + + return files + + +def _transform_file(file: FileTypes) -> HttpxFileTypes: + if is_file_content(file): + if isinstance(file, os.PathLike): + path = pathlib.Path(file) + return (path.name, path.read_bytes()) + + return file + + if is_tuple_t(file): + return (file[0], read_file_content(file[1]), *file[2:]) + + raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") + + +def read_file_content(file: FileContent) -> HttpxFileContent: + if isinstance(file, os.PathLike): + return pathlib.Path(file).read_bytes() + return file + + +@overload +async def async_to_httpx_files(files: None) -> None: ... + + +@overload +async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... + + +async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: + if files is None: + return None + + if is_mapping_t(files): + files = {key: await _async_transform_file(file) for key, file in files.items()} + elif is_sequence_t(files): + files = [(key, await _async_transform_file(file)) for key, file in files] + else: + raise TypeError("Unexpected file type input {type(files)}, expected mapping or sequence") + + return files + + +async def _async_transform_file(file: FileTypes) -> HttpxFileTypes: + if is_file_content(file): + if isinstance(file, os.PathLike): + path = anyio.Path(file) + return (path.name, await path.read_bytes()) + + return file + + if is_tuple_t(file): + return (file[0], await async_read_file_content(file[1]), *file[2:]) + + raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") + + +async def async_read_file_content(file: FileContent) -> HttpxFileContent: + if isinstance(file, os.PathLike): + return await anyio.Path(file).read_bytes() + + return file diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_legacy_response.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_legacy_response.py new file mode 100644 index 0000000000000000000000000000000000000000..9f93da7c233150607aa3ba94aa9c24c8233e9505 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_legacy_response.py @@ -0,0 +1,514 @@ +from __future__ import annotations + +import os +import inspect +import logging +import datetime +import functools +from typing import ( + TYPE_CHECKING, + Any, + Union, + Generic, + TypeVar, + Callable, + Iterator, + AsyncIterator, + cast, + overload, +) +from typing_extensions import Awaitable, ParamSpec, override, deprecated, get_origin + +import anyio +import httpx +import pydantic + +from ._types import NoneType +from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type +from ._models import BaseModel, is_basemodel, add_request_id +from ._constants import RAW_RESPONSE_HEADER +from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type +from ._exceptions import APIResponseValidationError +from ._decoders.jsonl import JSONLDecoder, AsyncJSONLDecoder + +if TYPE_CHECKING: + from ._models import FinalRequestOptions + from ._base_client import BaseClient + + +P = ParamSpec("P") +R = TypeVar("R") +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +log: logging.Logger = logging.getLogger(__name__) + + +class LegacyAPIResponse(Generic[R]): + """This is a legacy class as it will be replaced by `APIResponse` + and `AsyncAPIResponse` in the `_response.py` file in the next major + release. + + For the sync client this will mostly be the same with the exception + of `content` & `text` will be methods instead of properties. In the + async client, all methods will be async. + + A migration script will be provided & the migration in general should + be smooth. + """ + + _cast_to: type[R] + _client: BaseClient[Any, Any] + _parsed_by_type: dict[type[Any], Any] + _stream: bool + _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None + _options: FinalRequestOptions + + http_response: httpx.Response + + retries_taken: int + """The number of retries made. If no retries happened this will be `0`""" + + def __init__( + self, + *, + raw: httpx.Response, + cast_to: type[R], + client: BaseClient[Any, Any], + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + options: FinalRequestOptions, + retries_taken: int = 0, + ) -> None: + self._cast_to = cast_to + self._client = client + self._parsed_by_type = {} + self._stream = stream + self._stream_cls = stream_cls + self._options = options + self.http_response = raw + self.retries_taken = retries_taken + + @property + def request_id(self) -> str | None: + return self.http_response.headers.get("request-id") # type: ignore[no-any-return] + + @overload + def parse(self, *, to: type[_T]) -> _T: ... + + @overload + def parse(self) -> R: ... + + def parse(self, *, to: type[_T] | None = None) -> R | _T: + """Returns the rich python representation of this response's data. + + NOTE: For the async client: this will become a coroutine in the next major version. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from anthropic import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `int` + - `float` + - `httpx.Response` + """ + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] + + parsed = self._parse(to=to) + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + if isinstance(parsed, BaseModel): + add_request_id(parsed, self.request_id) + + self._parsed_by_type[cache_key] = parsed + return cast(R, parsed) + + @property + def headers(self) -> httpx.Headers: + return self.http_response.headers + + @property + def http_request(self) -> httpx.Request: + return self.http_response.request + + @property + def status_code(self) -> int: + return self.http_response.status_code + + @property + def url(self) -> httpx.URL: + return self.http_response.url + + @property + def method(self) -> str: + return self.http_request.method + + @property + def content(self) -> bytes: + """Return the binary response content. + + NOTE: this will be removed in favour of `.read()` in the + next major version. + """ + return self.http_response.content + + @property + def text(self) -> str: + """Return the decoded response content. + + NOTE: this will be turned into a method in the next major version. + """ + return self.http_response.text + + @property + def http_version(self) -> str: + return self.http_response.http_version + + @property + def is_closed(self) -> bool: + return self.http_response.is_closed + + @property + def elapsed(self) -> datetime.timedelta: + """The time taken for the complete request/response cycle to complete.""" + return self.http_response.elapsed + + def _parse(self, *, to: type[_T] | None = None) -> R | _T: + cast_to = to if to is not None else self._cast_to + + # unwrap `TypeAlias('Name', T)` -> `T` + if is_type_alias_type(cast_to): + cast_to = cast_to.__value__ # type: ignore[unreachable] + + # unwrap `Annotated[T, ...]` -> `T` + if cast_to and is_annotated_type(cast_to): + cast_to = extract_type_arg(cast_to, 0) + + origin = get_origin(cast_to) or cast_to + + if inspect.isclass(origin): + if issubclass(cast(Any, origin), JSONLDecoder): + return cast( + R, + cast("type[JSONLDecoder[Any]]", cast_to)( + raw_iterator=self.http_response.iter_bytes(chunk_size=64), + line_type=extract_type_arg(cast_to, 0), + http_response=self.http_response, + ), + ) + + if issubclass(cast(Any, origin), AsyncJSONLDecoder): + return cast( + R, + cast("type[AsyncJSONLDecoder[Any]]", cast_to)( + raw_iterator=self.http_response.aiter_bytes(chunk_size=64), + line_type=extract_type_arg(cast_to, 0), + http_response=self.http_response, + ), + ) + + if self._stream: + if to: + if not is_stream_class_type(to): + raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}") + + return cast( + _T, + to( + cast_to=extract_stream_chunk_type( + to, + failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]", + ), + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + if self._stream_cls: + return cast( + R, + self._stream_cls( + cast_to=extract_stream_chunk_type(self._stream_cls), + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls) + if stream_cls is None: + raise MissingStreamClassError() + + return cast( + R, + stream_cls( + cast_to=cast_to, + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + if cast_to is NoneType: + return cast(R, None) + + response = self.http_response + if cast_to == str: + return cast(R, response.text) + + if cast_to == int: + return cast(R, int(response.text)) + + if cast_to == float: + return cast(R, float(response.text)) + + if cast_to == bool: + return cast(R, response.text.lower() == "true") + + if inspect.isclass(origin) and issubclass(origin, HttpxBinaryResponseContent): + return cast(R, cast_to(response)) # type: ignore + + if origin == LegacyAPIResponse: + raise RuntimeError("Unexpected state - cast_to is `APIResponse`") + + if inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) and issubclass(origin, httpx.Response): + # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response + # and pass that class to our request functions. We cannot change the variance to be either + # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct + # the response class ourselves but that is something that should be supported directly in httpx + # as it would be easy to incorrectly construct the Response object due to the multitude of arguments. + if cast_to != httpx.Response: + raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") + return cast(R, response) + + if ( + inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) + and not issubclass(origin, BaseModel) + and issubclass(origin, pydantic.BaseModel) + ): + raise TypeError("Pydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`") + + if ( + cast_to is not object + and not origin is list + and not origin is dict + and not origin is Union + and not issubclass(origin, BaseModel) + ): + raise RuntimeError( + f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}." + ) + + # split is required to handle cases where additional information is included + # in the response, e.g. application/json; charset=utf-8 + content_type, *_ = response.headers.get("content-type", "*").split(";") + if not content_type.endswith("json"): + if is_basemodel(cast_to): + try: + data = response.json() + except Exception as exc: + log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc) + else: + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + if self._client._strict_response_validation: + raise APIResponseValidationError( + response=response, + message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.", + body=response.text, + ) + + # If the API responds with content that isn't JSON then we just return + # the (decoded) text without performing any parsing so that you can still + # handle the response however you need to. + return response.text # type: ignore + + data = response.json() + + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + @override + def __repr__(self) -> str: + return f"" + + +class MissingStreamClassError(TypeError): + def __init__(self) -> None: + super().__init__( + "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `anthropic._streaming` for reference", + ) + + +def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, LegacyAPIResponse[R]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "true" + + kwargs["extra_headers"] = extra_headers + + return cast(LegacyAPIResponse[R], func(*args, **kwargs)) + + return wrapped + + +def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[LegacyAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + async def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "true" + + kwargs["extra_headers"] = extra_headers + + return cast(LegacyAPIResponse[R], await func(*args, **kwargs)) + + return wrapped + + +class HttpxBinaryResponseContent: + response: httpx.Response + + def __init__(self, response: httpx.Response) -> None: + self.response = response + + @property + def content(self) -> bytes: + return self.response.content + + @property + def text(self) -> str: + return self.response.text + + @property + def encoding(self) -> str | None: + return self.response.encoding + + @property + def charset_encoding(self) -> str | None: + return self.response.charset_encoding + + def json(self, **kwargs: Any) -> Any: + return self.response.json(**kwargs) + + def read(self) -> bytes: + return self.response.read() + + def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]: + return self.response.iter_bytes(chunk_size) + + def iter_text(self, chunk_size: int | None = None) -> Iterator[str]: + return self.response.iter_text(chunk_size) + + def iter_lines(self) -> Iterator[str]: + return self.response.iter_lines() + + def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]: + return self.response.iter_raw(chunk_size) + + def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `client.with_streaming_response.foo().stream_to_file('my_filename.txt')` + """ + with open(file, mode="wb") as f: + for data in self.response.iter_bytes(): + f.write(data) + + @deprecated( + "Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead" + ) + def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + with open(file, mode="wb") as f: + for data in self.response.iter_bytes(chunk_size): + f.write(data) + + def close(self) -> None: + return self.response.close() + + async def aread(self) -> bytes: + return await self.response.aread() + + async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: + return self.response.aiter_bytes(chunk_size) + + async def aiter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]: + return self.response.aiter_text(chunk_size) + + async def aiter_lines(self) -> AsyncIterator[str]: + return self.response.aiter_lines() + + async def aiter_raw(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: + return self.response.aiter_raw(chunk_size) + + @deprecated( + "Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead" + ) + async def astream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.response.aiter_bytes(chunk_size): + await f.write(data) + + async def aclose(self) -> None: + return await self.response.aclose() diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_models.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..2d979355a3116b52ab3465a68f57219e2b30b665 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_models.py @@ -0,0 +1,918 @@ +from __future__ import annotations + +import os +import inspect +import weakref +from typing import ( + IO, + TYPE_CHECKING, + Any, + Type, + Union, + Generic, + TypeVar, + Callable, + Iterable, + Optional, + AsyncIterable, + cast, +) +from datetime import date, datetime +from typing_extensions import ( + List, + Unpack, + Literal, + ClassVar, + Protocol, + Required, + ParamSpec, + TypedDict, + TypeGuard, + final, + override, + runtime_checkable, +) + +import pydantic +from pydantic.fields import FieldInfo + +from ._types import ( + Body, + IncEx, + Query, + ModelT, + Headers, + Timeout, + NotGiven, + AnyMapping, + HttpxRequestFiles, +) +from ._utils import ( + PropertyInfo, + is_list, + is_given, + json_safe, + lru_cache, + is_mapping, + parse_date, + coerce_boolean, + parse_datetime, + strip_not_given, + extract_type_arg, + is_annotated_type, + is_type_alias_type, + strip_annotated_type, +) +from ._compat import ( + PYDANTIC_V1, + ConfigDict, + GenericModel as BaseGenericModel, + get_args, + is_union, + parse_obj, + get_origin, + is_literal_type, + get_model_config, + get_model_fields, + field_get_default, +) +from ._constants import RAW_RESPONSE_HEADER + +if TYPE_CHECKING: + from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema + +__all__ = ["BaseModel", "GenericModel"] + +_T = TypeVar("_T") +_BaseModelT = TypeVar("_BaseModelT", bound="BaseModel") + +P = ParamSpec("P") + + +@runtime_checkable +class _ConfigProtocol(Protocol): + allow_population_by_field_name: bool + + +class BaseModel(pydantic.BaseModel): + if PYDANTIC_V1: + + @property + @override + def model_fields_set(self) -> set[str]: + # a forwards-compat shim for pydantic v2 + return self.__fields_set__ # type: ignore + + class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] + extra: Any = pydantic.Extra.allow # type: ignore + else: + model_config: ClassVar[ConfigDict] = ConfigDict( + extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true")) + ) + + if TYPE_CHECKING: + _request_id: Optional[str] = None + """The ID of the request, returned via the `request-id` header. Useful for debugging requests and reporting issues to Anthropic. + This will **only** be set for the top-level response object, it will not be defined for nested objects. For example: + + ```py + message = await client.messages.create(...) + message._request_id # req_xxx + message.usage._request_id # raises `AttributeError` + ``` + + Note: unlike other properties that use an `_` prefix, this property + *is* public. Unless documented otherwise, all other `_` prefix properties, + methods and modules are *private*. + """ + + def to_dict( + self, + *, + mode: Literal["json", "python"] = "python", + use_api_names: bool = True, + exclude_unset: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, + warnings: bool = True, + ) -> dict[str, object]: + """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + By default, fields that were not set by the API will not be included, + and keys will match the API response, *not* the property names from the model. + + For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, + the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). + + Args: + mode: + If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`. + If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)` + + use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value from the output. + exclude_none: Whether to exclude fields that have a value of `None` from the output. + warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2. + """ + return self.model_dump( + mode=mode, + by_alias=use_api_names, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + warnings=warnings, + ) + + def to_json( + self, + *, + indent: int | None = 2, + use_api_names: bool = True, + exclude_unset: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, + warnings: bool = True, + ) -> str: + """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation). + + By default, fields that were not set by the API will not be included, + and keys will match the API response, *not* the property names from the model. + + For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, + the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). + + Args: + indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2` + use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that have the default value. + exclude_none: Whether to exclude fields that have a value of `None`. + warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2. + """ + return self.model_dump_json( + indent=indent, + by_alias=use_api_names, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + warnings=warnings, + ) + + @override + def __str__(self) -> str: + # mypy complains about an invalid self arg + return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc] + + # Override the 'construct' method in a way that supports recursive parsing without validation. + # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836. + @classmethod + @override + def construct( # pyright: ignore[reportIncompatibleMethodOverride] + __cls: Type[ModelT], + _fields_set: set[str] | None = None, + **values: object, + ) -> ModelT: + m = __cls.__new__(__cls) + fields_values: dict[str, object] = {} + + config = get_model_config(__cls) + populate_by_name = ( + config.allow_population_by_field_name + if isinstance(config, _ConfigProtocol) + else config.get("populate_by_name") + ) + + if _fields_set is None: + _fields_set = set() + + model_fields = get_model_fields(__cls) + for name, field in model_fields.items(): + key = field.alias + if key is None or (key not in values and populate_by_name): + key = name + + if key in values: + fields_values[name] = _construct_field(value=values[key], field=field, key=key) + _fields_set.add(name) + else: + fields_values[name] = field_get_default(field) + + extra_field_type = _get_extra_fields_type(__cls) + + _extra = {} + for key, value in values.items(): + if key not in model_fields: + parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value + + if PYDANTIC_V1: + _fields_set.add(key) + fields_values[key] = parsed + else: + _extra[key] = parsed + + object.__setattr__(m, "__dict__", fields_values) + + if PYDANTIC_V1: + # init_private_attributes() does not exist in v2 + m._init_private_attributes() # type: ignore + + # copied from Pydantic v1's `construct()` method + object.__setattr__(m, "__fields_set__", _fields_set) + else: + # these properties are copied from Pydantic's `model_construct()` method + object.__setattr__(m, "__pydantic_private__", None) + object.__setattr__(m, "__pydantic_extra__", _extra) + object.__setattr__(m, "__pydantic_fields_set__", _fields_set) + + return m + + if not TYPE_CHECKING: + # type checkers incorrectly complain about this assignment + # because the type signatures are technically different + # although not in practice + model_construct = construct + + if PYDANTIC_V1: + # we define aliases for some of the new pydantic v2 methods so + # that we can just document these methods without having to specify + # a specific pydantic version as some users may not know which + # pydantic version they are currently using + + @override + def model_dump( + self, + *, + mode: Literal["json", "python"] | str = "python", + include: IncEx | None = None, + exclude: IncEx | None = None, + context: Any | None = None, + by_alias: bool | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + exclude_computed_fields: bool = False, + round_trip: bool = False, + warnings: bool | Literal["none", "warn", "error"] = True, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + ) -> dict[str, Any]: + """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump + + Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + Args: + mode: The mode in which `to_python` should run. + If mode is 'json', the output will only contain JSON serializable types. + If mode is 'python', the output may contain non-JSON-serializable Python objects. + include: A set of fields to include in the output. + exclude: A set of fields to exclude from the output. + context: Additional context to pass to the serializer. + by_alias: Whether to use the field's alias in the dictionary key if defined. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value. + exclude_none: Whether to exclude fields that have a value of `None`. + exclude_computed_fields: Whether to exclude computed fields. + While this can be useful for round-tripping, it is usually recommended to use the dedicated + `round_trip` parameter instead. + round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. + warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + fallback: A function to call when an unknown value is encountered. If not provided, + a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + + Returns: + A dictionary representation of the model. + """ + if mode not in {"json", "python"}: + raise ValueError("mode must be either 'json' or 'python'") + if round_trip != False: + raise ValueError("round_trip is only supported in Pydantic v2") + if warnings != True: + raise ValueError("warnings is only supported in Pydantic v2") + if context is not None: + raise ValueError("context is only supported in Pydantic v2") + if serialize_as_any != False: + raise ValueError("serialize_as_any is only supported in Pydantic v2") + if fallback is not None: + raise ValueError("fallback is only supported in Pydantic v2") + if exclude_computed_fields != False: + raise ValueError("exclude_computed_fields is only supported in Pydantic v2") + dumped = super().dict( # pyright: ignore[reportDeprecated] + include=include, + exclude=exclude, + by_alias=by_alias if by_alias is not None else False, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + return cast("dict[str, Any]", json_safe(dumped)) if mode == "json" else dumped + + @override + def model_dump_json( + self, + *, + indent: int | None = None, + ensure_ascii: bool = False, + include: IncEx | None = None, + exclude: IncEx | None = None, + context: Any | None = None, + by_alias: bool | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + exclude_computed_fields: bool = False, + round_trip: bool = False, + warnings: bool | Literal["none", "warn", "error"] = True, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + ) -> str: + """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json + + Generates a JSON representation of the model using Pydantic's `to_json` method. + + Args: + indent: Indentation to use in the JSON output. If None is passed, the output will be compact. + include: Field(s) to include in the JSON output. Can take either a string or set of strings. + exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings. + by_alias: Whether to serialize using field aliases. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that have the default value. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: Whether to use serialization/deserialization between JSON and class instance. + warnings: Whether to show any warnings that occurred during serialization. + + Returns: + A JSON string representation of the model. + """ + if round_trip != False: + raise ValueError("round_trip is only supported in Pydantic v2") + if warnings != True: + raise ValueError("warnings is only supported in Pydantic v2") + if context is not None: + raise ValueError("context is only supported in Pydantic v2") + if serialize_as_any != False: + raise ValueError("serialize_as_any is only supported in Pydantic v2") + if fallback is not None: + raise ValueError("fallback is only supported in Pydantic v2") + if ensure_ascii != False: + raise ValueError("ensure_ascii is only supported in Pydantic v2") + if exclude_computed_fields != False: + raise ValueError("exclude_computed_fields is only supported in Pydantic v2") + return super().json( # type: ignore[reportDeprecated] + indent=indent, + include=include, + exclude=exclude, + by_alias=by_alias if by_alias is not None else False, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + +def _construct_field(value: object, field: FieldInfo, key: str) -> object: + if value is None: + return field_get_default(field) + + if PYDANTIC_V1: + type_ = cast(type, field.outer_type_) # type: ignore + else: + type_ = field.annotation # type: ignore + + if type_ is None: + raise RuntimeError(f"Unexpected field type is None for {key}") + + return construct_type(value=value, type_=type_, metadata=getattr(field, "metadata", None)) + + +def _get_extra_fields_type(cls: type[pydantic.BaseModel]) -> type | None: + if PYDANTIC_V1: + # TODO + return None + + schema = cls.__pydantic_core_schema__ + if schema["type"] == "model": + fields = schema["schema"] + if fields["type"] == "model-fields": + extras = fields.get("extras_schema") + if extras and "cls" in extras: + # mypy can't narrow the type + return extras["cls"] # type: ignore[no-any-return] + + return None + + +def is_basemodel(type_: type) -> bool: + """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`""" + if is_union(type_): + for variant in get_args(type_): + if is_basemodel(variant): + return True + + return False + + return is_basemodel_type(type_) + + +def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]: + origin = get_origin(type_) or type_ + if not inspect.isclass(origin): + return False + return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) + + +def build( + base_model_cls: Callable[P, _BaseModelT], + *args: P.args, + **kwargs: P.kwargs, +) -> _BaseModelT: + """Construct a BaseModel class without validation. + + This is useful for cases where you need to instantiate a `BaseModel` + from an API response as this provides type-safe params which isn't supported + by helpers like `construct_type()`. + + ```py + build(MyModel, my_field_a="foo", my_field_b=123) + ``` + """ + if args: + raise TypeError( + "Received positional arguments which are not supported; Keyword arguments must be used instead", + ) + + return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs)) + + +def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T: + """Loose coercion to the expected type with construction of nested values. + + Note: the returned value from this function is not guaranteed to match the + given type. + """ + return cast(_T, construct_type(value=value, type_=type_)) + + +def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]] = None) -> object: + """Loose coercion to the expected type with construction of nested values. + + If the given value does not match the expected type then it is returned as-is. + """ + + # store a reference to the original type we were given before we extract any inner + # types so that we can properly resolve forward references in `TypeAliasType` annotations + original_type = None + + # we allow `object` as the input type because otherwise, passing things like + # `Literal['value']` will be reported as a type error by type checkers + type_ = cast("type[object]", type_) + if is_type_alias_type(type_): + original_type = type_ # type: ignore[unreachable] + type_ = type_.__value__ # type: ignore[unreachable] + + # unwrap `Annotated[T, ...]` -> `T` + if metadata is not None and len(metadata) > 0: + meta: tuple[Any, ...] = tuple(metadata) + elif is_annotated_type(type_): + meta = get_args(type_)[1:] + type_ = extract_type_arg(type_, 0) + else: + meta = tuple() + + # we need to use the origin class for any types that are subscripted generics + # e.g. Dict[str, object] + origin = get_origin(type_) or type_ + args = get_args(type_) + + if is_union(origin): + try: + return validate_type(type_=cast("type[object]", original_type or type_), value=value) + except Exception: + pass + + # if the type is a discriminated union then we want to construct the right variant + # in the union, even if the data doesn't match exactly, otherwise we'd break code + # that relies on the constructed class types, e.g. + # + # class FooType: + # kind: Literal['foo'] + # value: str + # + # class BarType: + # kind: Literal['bar'] + # value: int + # + # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then + # we'd end up constructing `FooType` when it should be `BarType`. + discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta) + if discriminator and is_mapping(value): + variant_value = value.get(discriminator.field_alias_from or discriminator.field_name) + if variant_value and isinstance(variant_value, str): + variant_type = discriminator.mapping.get(variant_value) + if variant_type: + return construct_type(type_=variant_type, value=value) + + # if the data is not valid, use the first variant that doesn't fail while deserializing + for variant in args: + try: + return construct_type(value=value, type_=variant) + except Exception: + continue + + raise RuntimeError(f"Could not convert data into a valid instance of {type_}") + + if origin == dict: + if not is_mapping(value): + return value + + _, items_type = get_args(type_) # Dict[_, items_type] + return {key: construct_type(value=item, type_=items_type) for key, item in value.items()} + + if ( + not is_literal_type(type_) + and inspect.isclass(origin) + and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)) + ): + if is_list(value): + return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value] + + if is_mapping(value): + if issubclass(type_, BaseModel): + return type_.construct(**value) # type: ignore[arg-type] + + return cast(Any, type_).construct(**value) + + if origin == list: + if not is_list(value): + return value + + inner_type = args[0] # List[inner_type] + return [construct_type(value=entry, type_=inner_type) for entry in value] + + if origin == float: + if isinstance(value, int): + coerced = float(value) + if coerced != value: + return value + return coerced + + return value + + if type_ == datetime: + try: + return parse_datetime(value) # type: ignore + except Exception: + return value + + if type_ == date: + try: + return parse_date(value) # type: ignore + except Exception: + return value + + return value + + +@runtime_checkable +class CachedDiscriminatorType(Protocol): + __discriminator__: DiscriminatorDetails + + +DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary() + + +class DiscriminatorDetails: + field_name: str + """The name of the discriminator field in the variant class, e.g. + + ```py + class Foo(BaseModel): + type: Literal['foo'] + ``` + + Will result in field_name='type' + """ + + field_alias_from: str | None + """The name of the discriminator field in the API response, e.g. + + ```py + class Foo(BaseModel): + type: Literal['foo'] = Field(alias='type_from_api') + ``` + + Will result in field_alias_from='type_from_api' + """ + + mapping: dict[str, type] + """Mapping of discriminator value to variant type, e.g. + + {'foo': FooVariant, 'bar': BarVariant} + """ + + def __init__( + self, + *, + mapping: dict[str, type], + discriminator_field: str, + discriminator_alias: str | None, + ) -> None: + self.mapping = mapping + self.field_name = discriminator_field + self.field_alias_from = discriminator_alias + + +def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None: + cached = DISCRIMINATOR_CACHE.get(union) + if cached is not None: + return cached + + discriminator_field_name: str | None = None + + for annotation in meta_annotations: + if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None: + discriminator_field_name = annotation.discriminator + break + + if not discriminator_field_name: + return None + + mapping: dict[str, type] = {} + discriminator_alias: str | None = None + + for variant in get_args(union): + variant = strip_annotated_type(variant) + if is_basemodel_type(variant): + if PYDANTIC_V1: + field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + if not field_info: + continue + + # Note: if one variant defines an alias then they all should + discriminator_alias = field_info.alias + + if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation): + for entry in get_args(annotation): + if isinstance(entry, str): + mapping[entry] = variant + else: + field = _extract_field_schema_pv2(variant, discriminator_field_name) + if not field: + continue + + # Note: if one variant defines an alias then they all should + discriminator_alias = field.get("serialization_alias") + + field_schema = field["schema"] + + if field_schema["type"] == "literal": + for entry in cast("LiteralSchema", field_schema)["expected"]: + if isinstance(entry, str): + mapping[entry] = variant + + if not mapping: + return None + + details = DiscriminatorDetails( + mapping=mapping, + discriminator_field=discriminator_field_name, + discriminator_alias=discriminator_alias, + ) + DISCRIMINATOR_CACHE.setdefault(union, details) + return details + + +def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None: + schema = model.__pydantic_core_schema__ + if schema["type"] == "definitions": + schema = schema["schema"] + + if schema["type"] != "model": + return None + + schema = cast("ModelSchema", schema) + fields_schema = schema["schema"] + if fields_schema["type"] != "model-fields": + return None + + fields_schema = cast("ModelFieldsSchema", fields_schema) + field = fields_schema["fields"].get(field_name) + if not field: + return None + + return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast] + + +def validate_type(*, type_: type[_T], value: object) -> _T: + """Strict validation that the given value matches the expected type""" + if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel): + return cast(_T, parse_obj(type_, value)) + + return cast(_T, _validate_non_model_type(type_=type_, value=value)) + + +def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None: + """Add a pydantic config for the given type. + + Note: this is a no-op on Pydantic v1. + """ + setattr(typ, "__pydantic_config__", config) # noqa: B010 + + +def add_request_id(obj: BaseModel, request_id: str | None) -> None: + obj._request_id = request_id + + # in Pydantic v1, using setattr like we do above causes the attribute + # to be included when serializing the model which we don't want in this + # case so we need to explicitly exclude it + if PYDANTIC_V1: + try: + exclude_fields = obj.__exclude_fields__ # type: ignore + except AttributeError: + cast(Any, obj).__exclude_fields__ = {"_request_id", "__exclude_fields__"} + else: + cast(Any, obj).__exclude_fields__ = {*(exclude_fields or {}), "_request_id", "__exclude_fields__"} + + +# our use of subclassing here causes weirdness for type checkers, +# so we just pretend that we don't subclass +if TYPE_CHECKING: + GenericModel = BaseModel +else: + + class GenericModel(BaseGenericModel, BaseModel): + pass + + +if not PYDANTIC_V1: + from pydantic import TypeAdapter as _TypeAdapter, computed_field as computed_field + + _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter)) + + if TYPE_CHECKING: + from pydantic import TypeAdapter + else: + TypeAdapter = _CachedTypeAdapter + + def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: + return TypeAdapter(type_).validate_python(value) + +elif not TYPE_CHECKING: # TODO: condition is weird + + class RootModel(GenericModel, Generic[_T]): + """Used as a placeholder to easily convert runtime types to a Pydantic format + to provide validation. + + For example: + ```py + validated = RootModel[int](__root__="5").__root__ + # validated: 5 + ``` + """ + + __root__: _T + + def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: + model = _create_pydantic_model(type_).validate(value) + return cast(_T, model.__root__) + + def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]: + return RootModel[type_] # type: ignore + + def TypeAdapter(*_args: Any, **_kwargs: Any) -> Any: + raise RuntimeError("attempted to use TypeAdapter in pydantic v1") + + def computed_field(func: Any | None = None, /, **__: Any) -> Any: + def _exc_func(*_: Any, **__: Any) -> Any: + raise RuntimeError("attempted to use computed_field in pydantic v1") + + def _dec(*_: Any, **__: Any) -> Any: + return _exc_func + + if func is not None: + return _dec(func) + else: + return _dec + + +class FinalRequestOptionsInput(TypedDict, total=False): + method: Required[str] + url: Required[str] + params: Query + headers: Headers + max_retries: int + timeout: float | Timeout | None + files: HttpxRequestFiles | None + idempotency_key: str + content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] + json_data: Body + extra_json: AnyMapping + follow_redirects: bool + + +@final +class FinalRequestOptions(pydantic.BaseModel): + method: str + url: str + params: Query = {} + headers: Union[Headers, NotGiven] = NotGiven() + max_retries: Union[int, NotGiven] = NotGiven() + timeout: Union[float, Timeout, None, NotGiven] = NotGiven() + files: Union[HttpxRequestFiles, None] = None + idempotency_key: Union[str, None] = None + post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven() + follow_redirects: Union[bool, None] = None + + content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] = None + # It should be noted that we cannot use `json` here as that would override + # a BaseModel method in an incompatible fashion. + json_data: Union[Body, None] = None + extra_json: Union[AnyMapping, None] = None + + if PYDANTIC_V1: + + class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] + arbitrary_types_allowed: bool = True + else: + model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True) + + def get_max_retries(self, max_retries: int) -> int: + if isinstance(self.max_retries, NotGiven): + return max_retries + return self.max_retries + + def _strip_raw_response_header(self) -> None: + if not is_given(self.headers): + return + + if self.headers.get(RAW_RESPONSE_HEADER): + self.headers = {**self.headers} + self.headers.pop(RAW_RESPONSE_HEADER) + + # override the `construct` method so that we can run custom transformations. + # this is necessary as we don't want to do any actual runtime type checking + # (which means we can't use validators) but we do want to ensure that `NotGiven` + # values are not present + # + # type ignore required because we're adding explicit types to `**values` + @classmethod + def construct( # type: ignore + cls, + _fields_set: set[str] | None = None, + **values: Unpack[FinalRequestOptionsInput], + ) -> FinalRequestOptions: + kwargs: dict[str, Any] = { + # we unconditionally call `strip_not_given` on any value + # as it will just ignore any non-mapping types + key: strip_not_given(value) + for key, value in values.items() + } + if PYDANTIC_V1: + return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated] + return super().model_construct(_fields_set, **kwargs) + + if not TYPE_CHECKING: + # type checkers incorrectly complain about this assignment + model_construct = construct diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_qs.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_qs.py new file mode 100644 index 0000000000000000000000000000000000000000..de8c99bc63a67980987a8de83d2331b50070fcfa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_qs.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +from typing import Any, List, Tuple, Union, Mapping, TypeVar +from urllib.parse import parse_qs, urlencode +from typing_extensions import Literal, get_args + +from ._types import NotGiven, not_given +from ._utils import flatten + +_T = TypeVar("_T") + + +ArrayFormat = Literal["comma", "repeat", "indices", "brackets"] +NestedFormat = Literal["dots", "brackets"] + +PrimitiveData = Union[str, int, float, bool, None] +# this should be Data = Union[PrimitiveData, "List[Data]", "Tuple[Data]", "Mapping[str, Data]"] +# https://github.com/microsoft/pyright/issues/3555 +Data = Union[PrimitiveData, List[Any], Tuple[Any], "Mapping[str, Any]"] +Params = Mapping[str, Data] + + +class Querystring: + array_format: ArrayFormat + nested_format: NestedFormat + + def __init__( + self, + *, + array_format: ArrayFormat = "repeat", + nested_format: NestedFormat = "brackets", + ) -> None: + self.array_format = array_format + self.nested_format = nested_format + + def parse(self, query: str) -> Mapping[str, object]: + # Note: custom format syntax is not supported yet + return parse_qs(query) + + def stringify( + self, + params: Params, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> str: + return urlencode( + self.stringify_items( + params, + array_format=array_format, + nested_format=nested_format, + ) + ) + + def stringify_items( + self, + params: Params, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> list[tuple[str, str]]: + opts = Options( + qs=self, + array_format=array_format, + nested_format=nested_format, + ) + return flatten([self._stringify_item(key, value, opts) for key, value in params.items()]) + + def _stringify_item( + self, + key: str, + value: Data, + opts: Options, + ) -> list[tuple[str, str]]: + if isinstance(value, Mapping): + items: list[tuple[str, str]] = [] + nested_format = opts.nested_format + for subkey, subvalue in value.items(): + items.extend( + self._stringify_item( + # TODO: error if unknown format + f"{key}.{subkey}" if nested_format == "dots" else f"{key}[{subkey}]", + subvalue, + opts, + ) + ) + return items + + if isinstance(value, (list, tuple)): + array_format = opts.array_format + if array_format == "comma": + return [ + ( + key, + ",".join(self._primitive_value_to_str(item) for item in value if item is not None), + ), + ] + elif array_format == "repeat": + items = [] + for item in value: + items.extend(self._stringify_item(key, item, opts)) + return items + elif array_format == "indices": + items = [] + for i, item in enumerate(value): + items.extend(self._stringify_item(f"{key}[{i}]", item, opts)) + return items + elif array_format == "brackets": + items = [] + key = key + "[]" + for item in value: + items.extend(self._stringify_item(key, item, opts)) + return items + else: + raise NotImplementedError( + f"Unknown array_format value: {array_format}, choose from {', '.join(get_args(ArrayFormat))}" + ) + + serialised = self._primitive_value_to_str(value) + if not serialised: + return [] + return [(key, serialised)] + + def _primitive_value_to_str(self, value: PrimitiveData) -> str: + # copied from httpx + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + +_qs = Querystring() +parse = _qs.parse +stringify = _qs.stringify +stringify_items = _qs.stringify_items + + +class Options: + array_format: ArrayFormat + nested_format: NestedFormat + + def __init__( + self, + qs: Querystring = _qs, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> None: + self.array_format = qs.array_format if isinstance(array_format, NotGiven) else array_format + self.nested_format = qs.nested_format if isinstance(nested_format, NotGiven) else nested_format diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_resource.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..f62cc2ba48787443f9127890da6eec2804a57b97 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_resource.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import time + +import anyio + +from ._base_client import SyncAPIClient, AsyncAPIClient + + +class SyncAPIResource: + _client: SyncAPIClient + + def __init__(self, client: SyncAPIClient) -> None: + self._client = client + self._get = client.get + self._post = client.post + self._patch = client.patch + self._put = client.put + self._delete = client.delete + self._get_api_list = client.get_api_list + + def _sleep(self, seconds: float) -> None: + time.sleep(seconds) + + +class AsyncAPIResource: + _client: AsyncAPIClient + + def __init__(self, client: AsyncAPIClient) -> None: + self._client = client + self._get = client.get + self._post = client.post + self._patch = client.patch + self._put = client.put + self._delete = client.delete + self._get_api_list = client.get_api_list + + async def _sleep(self, seconds: float) -> None: + await anyio.sleep(seconds) diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_response.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_response.py new file mode 100644 index 0000000000000000000000000000000000000000..1e0257ee424f5dbcefa120e3f008de38c5dc5948 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_response.py @@ -0,0 +1,875 @@ +from __future__ import annotations + +import os +import inspect +import logging +import datetime +import functools +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Union, + Generic, + TypeVar, + Callable, + Iterator, + AsyncIterator, + cast, + overload, +) +from typing_extensions import Awaitable, ParamSpec, override, get_origin + +import anyio +import httpx +import pydantic + +from ._types import NoneType +from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type, extract_type_var_from_base +from ._models import BaseModel, is_basemodel, add_request_id +from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER +from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type +from ._exceptions import AnthropicError, APIResponseValidationError +from ._decoders.jsonl import JSONLDecoder, AsyncJSONLDecoder + +if TYPE_CHECKING: + from ._models import FinalRequestOptions + from ._base_client import BaseClient + + +P = ParamSpec("P") +R = TypeVar("R") +_T = TypeVar("_T") +_APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]") +_AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]") + +log: logging.Logger = logging.getLogger(__name__) + + +class BaseAPIResponse(Generic[R]): + _cast_to: type[R] + _client: BaseClient[Any, Any] + _parsed_by_type: dict[type[Any], Any] + _is_sse_stream: bool + _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None + _options: FinalRequestOptions + + http_response: httpx.Response + + retries_taken: int + """The number of retries made. If no retries happened this will be `0`""" + + def __init__( + self, + *, + raw: httpx.Response, + cast_to: type[R], + client: BaseClient[Any, Any], + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + options: FinalRequestOptions, + retries_taken: int = 0, + ) -> None: + self._cast_to = cast_to + self._client = client + self._parsed_by_type = {} + self._is_sse_stream = stream + self._stream_cls = stream_cls + self._options = options + self.http_response = raw + self.retries_taken = retries_taken + + @property + def headers(self) -> httpx.Headers: + return self.http_response.headers + + @property + def http_request(self) -> httpx.Request: + """Returns the httpx Request instance associated with the current response.""" + return self.http_response.request + + @property + def status_code(self) -> int: + return self.http_response.status_code + + @property + def url(self) -> httpx.URL: + """Returns the URL for which the request was made.""" + return self.http_response.url + + @property + def method(self) -> str: + return self.http_request.method + + @property + def http_version(self) -> str: + return self.http_response.http_version + + @property + def elapsed(self) -> datetime.timedelta: + """The time taken for the complete request/response cycle to complete.""" + return self.http_response.elapsed + + @property + def is_closed(self) -> bool: + """Whether or not the response body has been closed. + + If this is False then there is response data that has not been read yet. + You must either fully consume the response body or call `.close()` + before discarding the response to prevent resource leaks. + """ + return self.http_response.is_closed + + @override + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>" + ) + + def _parse(self, *, to: type[_T] | None = None) -> R | _T: + cast_to = to if to is not None else self._cast_to + + # unwrap `TypeAlias('Name', T)` -> `T` + if is_type_alias_type(cast_to): + cast_to = cast_to.__value__ # type: ignore[unreachable] + + # unwrap `Annotated[T, ...]` -> `T` + if cast_to and is_annotated_type(cast_to): + cast_to = extract_type_arg(cast_to, 0) + + origin = get_origin(cast_to) or cast_to + + if inspect.isclass(origin): + if issubclass(cast(Any, origin), JSONLDecoder): + return cast( + R, + cast("type[JSONLDecoder[Any]]", cast_to)( + raw_iterator=self.http_response.iter_bytes(chunk_size=64), + line_type=extract_type_arg(cast_to, 0), + http_response=self.http_response, + ), + ) + + if issubclass(cast(Any, origin), AsyncJSONLDecoder): + return cast( + R, + cast("type[AsyncJSONLDecoder[Any]]", cast_to)( + raw_iterator=self.http_response.aiter_bytes(chunk_size=64), + line_type=extract_type_arg(cast_to, 0), + http_response=self.http_response, + ), + ) + + if self._is_sse_stream: + if to: + if not is_stream_class_type(to): + raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}") + + return cast( + _T, + to( + cast_to=extract_stream_chunk_type( + to, + failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]", + ), + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + if self._stream_cls: + return cast( + R, + self._stream_cls( + cast_to=extract_stream_chunk_type(self._stream_cls), + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls) + if stream_cls is None: + raise MissingStreamClassError() + + return cast( + R, + stream_cls( + cast_to=cast_to, + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + if cast_to is NoneType: + return cast(R, None) + + response = self.http_response + if cast_to == str: + return cast(R, response.text) + + if cast_to == bytes: + return cast(R, response.content) + + if cast_to == int: + return cast(R, int(response.text)) + + if cast_to == float: + return cast(R, float(response.text)) + + if cast_to == bool: + return cast(R, response.text.lower() == "true") + + # handle the legacy binary response case + if inspect.isclass(cast_to) and cast_to.__name__ == "HttpxBinaryResponseContent": + return cast(R, cast_to(response)) # type: ignore + + if origin == APIResponse: + raise RuntimeError("Unexpected state - cast_to is `APIResponse`") + + if inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) and issubclass(origin, httpx.Response): + # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response + # and pass that class to our request functions. We cannot change the variance to be either + # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct + # the response class ourselves but that is something that should be supported directly in httpx + # as it would be easy to incorrectly construct the Response object due to the multitude of arguments. + if cast_to != httpx.Response: + raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") + return cast(R, response) + + if ( + inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) + and not issubclass(origin, BaseModel) + and issubclass(origin, pydantic.BaseModel) + ): + raise TypeError("Pydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`") + + if ( + cast_to is not object + and not origin is list + and not origin is dict + and not origin is Union + and not issubclass(origin, BaseModel) + ): + raise RuntimeError( + f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}." + ) + + # split is required to handle cases where additional information is included + # in the response, e.g. application/json; charset=utf-8 + content_type, *_ = response.headers.get("content-type", "*").split(";") + if not content_type.endswith("json"): + if is_basemodel(cast_to): + try: + data = response.json() + except Exception as exc: + log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc) + else: + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + if self._client._strict_response_validation: + raise APIResponseValidationError( + response=response, + message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.", + body=response.text, + ) + + # If the API responds with content that isn't JSON then we just return + # the (decoded) text without performing any parsing so that you can still + # handle the response however you need to. + return response.text # type: ignore + + data = response.json() + + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + +class APIResponse(BaseAPIResponse[R]): + @property + def request_id(self) -> str | None: + return self.http_response.headers.get("request-id") # type: ignore[no-any-return] + + @overload + def parse(self, *, to: type[_T]) -> _T: ... + + @overload + def parse(self) -> R: ... + + def parse(self, *, to: type[_T] | None = None) -> R | _T: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from anthropic import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `int` + - `float` + - `httpx.Response` + """ + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] + + if not self._is_sse_stream: + self.read() + + parsed = self._parse(to=to) + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + if isinstance(parsed, BaseModel): + add_request_id(parsed, self.request_id) + + self._parsed_by_type[cache_key] = parsed + return cast(R, parsed) + + def read(self) -> bytes: + """Read and return the binary response content.""" + try: + return self.http_response.read() + except httpx.StreamConsumed as exc: + # The default error raised by httpx isn't very + # helpful in our case so we re-raise it with + # a different error message. + raise StreamAlreadyConsumed() from exc + + def text(self) -> str: + """Read and decode the response content into a string.""" + self.read() + return self.http_response.text + + def json(self) -> object: + """Read and decode the JSON response content.""" + self.read() + return self.http_response.json() + + def close(self) -> None: + """Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self.http_response.close() + + def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + + This automatically handles gzip, deflate and brotli encoded responses. + """ + for chunk in self.http_response.iter_bytes(chunk_size): + yield chunk + + def iter_text(self, chunk_size: int | None = None) -> Iterator[str]: + """A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + for chunk in self.http_response.iter_text(chunk_size): + yield chunk + + def iter_lines(self) -> Iterator[str]: + """Like `iter_text()` but will only yield chunks for each line""" + for chunk in self.http_response.iter_lines(): + yield chunk + + +class AsyncAPIResponse(BaseAPIResponse[R]): + @property + def request_id(self) -> str | None: + return self.http_response.headers.get("request-id") # type: ignore[no-any-return] + + @overload + async def parse(self, *, to: type[_T]) -> _T: ... + + @overload + async def parse(self) -> R: ... + + async def parse(self, *, to: type[_T] | None = None) -> R | _T: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from anthropic import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `httpx.Response` + """ + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] + + if not self._is_sse_stream: + await self.read() + + parsed = self._parse(to=to) + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + if isinstance(parsed, BaseModel): + add_request_id(parsed, self.request_id) + + self._parsed_by_type[cache_key] = parsed + return cast(R, parsed) + + async def read(self) -> bytes: + """Read and return the binary response content.""" + try: + return await self.http_response.aread() + except httpx.StreamConsumed as exc: + # the default error raised by httpx isn't very + # helpful in our case so we re-raise it with + # a different error message + raise StreamAlreadyConsumed() from exc + + async def text(self) -> str: + """Read and decode the response content into a string.""" + await self.read() + return self.http_response.text + + async def json(self) -> object: + """Read and decode the JSON response content.""" + await self.read() + return self.http_response.json() + + async def close(self) -> None: + """Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self.http_response.aclose() + + async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + + This automatically handles gzip, deflate and brotli encoded responses. + """ + async for chunk in self.http_response.aiter_bytes(chunk_size): + yield chunk + + async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]: + """A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + async for chunk in self.http_response.aiter_text(chunk_size): + yield chunk + + async def iter_lines(self) -> AsyncIterator[str]: + """Like `iter_text()` but will only yield chunks for each line""" + async for chunk in self.http_response.aiter_lines(): + yield chunk + + +class BinaryAPIResponse(APIResponse[bytes]): + """Subclass of APIResponse providing helpers for dealing with binary data. + + Note: If you want to stream the response data instead of eagerly reading it + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + + def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + with open(file, mode="wb") as f: + for data in self.iter_bytes(): + f.write(data) + + +class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]): + """Subclass of APIResponse providing helpers for dealing with binary data. + + Note: If you want to stream the response data instead of eagerly reading it + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + + async def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.iter_bytes(): + await f.write(data) + + +class StreamedBinaryAPIResponse(APIResponse[bytes]): + def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + """Streams the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + """ + with open(file, mode="wb") as f: + for data in self.iter_bytes(chunk_size): + f.write(data) + + +class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]): + async def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + """Streams the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + """ + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.iter_bytes(chunk_size): + await f.write(data) + + +class MissingStreamClassError(TypeError): + def __init__(self) -> None: + super().__init__( + "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `anthropic._streaming` for reference", + ) + + +class StreamAlreadyConsumed(AnthropicError): + """ + Attempted to read or stream content, but the content has already + been streamed. + + This can happen if you use a method like `.iter_lines()` and then attempt + to read th entire response body afterwards, e.g. + + ```py + response = await client.post(...) + async for line in response.iter_lines(): + ... # do something with `line` + + content = await response.read() + # ^ error + ``` + + If you want this behaviour you'll need to either manually accumulate the response + content or call `await response.read()` before iterating over the stream. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream some content, but the content has " + "already been streamed. " + "This could be due to attempting to stream the response " + "content more than once." + "\n\n" + "You can fix this by manually accumulating the response content while streaming " + "or by calling `.read()` before starting to stream." + ) + super().__init__(message) + + +class ResponseContextManager(Generic[_APIResponseT]): + """Context manager for ensuring that a request is not made + until it is entered and that the response will always be closed + when the context manager exits + """ + + def __init__(self, request_func: Callable[[], _APIResponseT]) -> None: + self._request_func = request_func + self.__response: _APIResponseT | None = None + + def __enter__(self) -> _APIResponseT: + self.__response = self._request_func() + return self.__response + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__response is not None: + self.__response.close() + + +class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]): + """Context manager for ensuring that a request is not made + until it is entered and that the response will always be closed + when the context manager exits + """ + + def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None: + self._api_request = api_request + self.__response: _AsyncAPIResponseT | None = None + + async def __aenter__(self) -> _AsyncAPIResponseT: + self.__response = await self._api_request + return self.__response + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__response is not None: + await self.__response.close() + + +def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support streaming and returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + + kwargs["extra_headers"] = extra_headers + + make_request = functools.partial(func, *args, **kwargs) + + return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request)) + + return wrapped + + +def async_to_streamed_response_wrapper( + func: Callable[P, Awaitable[R]], +) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support streaming and returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + + kwargs["extra_headers"] = extra_headers + + make_request = func(*args, **kwargs) + + return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request)) + + return wrapped + + +def to_custom_streamed_response_wrapper( + func: Callable[P, object], + response_cls: type[_APIResponseT], +) -> Callable[P, ResponseContextManager[_APIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support streaming and returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + make_request = functools.partial(func, *args, **kwargs) + + return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request)) + + return wrapped + + +def async_to_custom_streamed_response_wrapper( + func: Callable[P, Awaitable[object]], + response_cls: type[_AsyncAPIResponseT], +) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support streaming and returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + make_request = func(*args, **kwargs) + + return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request)) + + return wrapped + + +def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + + kwargs["extra_headers"] = extra_headers + + return cast(APIResponse[R], func(*args, **kwargs)) + + return wrapped + + +def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + + kwargs["extra_headers"] = extra_headers + + return cast(AsyncAPIResponse[R], await func(*args, **kwargs)) + + return wrapped + + +def to_custom_raw_response_wrapper( + func: Callable[P, object], + response_cls: type[_APIResponseT], +) -> Callable[P, _APIResponseT]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + return cast(_APIResponseT, func(*args, **kwargs)) + + return wrapped + + +def async_to_custom_raw_response_wrapper( + func: Callable[P, Awaitable[object]], + response_cls: type[_AsyncAPIResponseT], +) -> Callable[P, Awaitable[_AsyncAPIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs)) + + return wrapped + + +def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type: + """Given a type like `APIResponse[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyResponse(APIResponse[bytes]): + ... + + extract_response_type(MyResponse) -> bytes + ``` + """ + return extract_type_var_from_base( + typ, + generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)), + index=0, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_streaming.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb3e821afadc6e94c1772fa13a0411b132be7df --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_streaming.py @@ -0,0 +1,450 @@ +# Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py +from __future__ import annotations + +import abc +import json +import inspect +import warnings +from types import TracebackType +from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, Optional, AsyncIterator, cast +from typing_extensions import Self, Protocol, TypeGuard, override, get_origin, runtime_checkable + +import httpx + +from ._utils import is_dict, extract_type_var_from_base + +if TYPE_CHECKING: + from ._client import Anthropic, AsyncAnthropic + from ._models import FinalRequestOptions + + +_T = TypeVar("_T") + + +class _SyncStreamMeta(abc.ABCMeta): + @override + def __instancecheck__(self, instance: Any) -> bool: + # we override the `isinstance()` check for `Stream` + # as a previous version of the `MessageStream` class + # inherited from `Stream` & without this workaround, + # changing it to not inherit would be a breaking change. + + from .lib.streaming import MessageStream + + if isinstance(instance, MessageStream): + warnings.warn( + "Using `isinstance()` to check if a `MessageStream` object is an instance of `Stream` is deprecated & will be removed in the next major version", + DeprecationWarning, + stacklevel=2, + ) + return True + + return False + + +class Stream(Generic[_T], metaclass=_SyncStreamMeta): + """Provides the core interface to iterate over a synchronous stream response.""" + + response: httpx.Response + _options: Optional[FinalRequestOptions] = None + _decoder: SSEBytesDecoder + + def __init__( + self, + *, + cast_to: type[_T], + response: httpx.Response, + client: Anthropic, + options: Optional[FinalRequestOptions] = None, + ) -> None: + self.response = response + self._cast_to = cast_to + self._client = client + self._options = options + self._decoder = client._make_sse_decoder() + self._iterator = self.__stream__() + + def __next__(self) -> _T: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[_T]: + for item in self._iterator: + yield item + + def _iter_events(self) -> Iterator[ServerSentEvent]: + yield from self._decoder.iter_bytes(self.response.iter_bytes()) + + def __stream__(self) -> Iterator[_T]: + cast_to = cast(Any, self._cast_to) + response = self.response + process_data = self._client._process_response_data + iterator = self._iter_events() + + try: + for sse in iterator: + if sse.event == "completion": + yield process_data(data=sse.json(), cast_to=cast_to, response=response) + + if ( + sse.event == "message_start" + or sse.event == "message_delta" + or sse.event == "message_stop" + or sse.event == "content_block_start" + or sse.event == "content_block_delta" + or sse.event == "content_block_stop" + or sse.event == "message" + ): + data = sse.json() + if is_dict(data) and "type" not in data: + data["type"] = sse.event + + yield process_data(data=data, cast_to=cast_to, response=response) + + if sse.event == "ping": + continue + + if sse.event == "error": + body = sse.data + + try: + body = sse.json() + err_msg = f"{body}" + except Exception: + err_msg = sse.data or f"Error code: {response.status_code}" + + raise self._client._make_status_error( + err_msg, + body=body, + response=self.response, + ) + finally: + # Ensure the response is closed even if the consumer doesn't read all data + response.close() + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self.response.close() + + +class _AsyncStreamMeta(abc.ABCMeta): + @override + def __instancecheck__(self, instance: Any) -> bool: + # we override the `isinstance()` check for `AsyncStream` + # as a previous version of the `AsyncMessageStream` class + # inherited from `AsyncStream` & without this workaround, + # changing it to not inherit would be a breaking change. + + from .lib.streaming import AsyncMessageStream + + if isinstance(instance, AsyncMessageStream): + warnings.warn( + "Using `isinstance()` to check if a `AsyncMessageStream` object is an instance of `AsyncStream` is deprecated & will be removed in the next major version", + DeprecationWarning, + stacklevel=2, + ) + return True + + return False + + +class AsyncStream(Generic[_T], metaclass=_AsyncStreamMeta): + """Provides the core interface to iterate over an asynchronous stream response.""" + + response: httpx.Response + _options: Optional[FinalRequestOptions] = None + _decoder: SSEDecoder | SSEBytesDecoder + + def __init__( + self, + *, + cast_to: type[_T], + response: httpx.Response, + client: AsyncAnthropic, + options: Optional[FinalRequestOptions] = None, + ) -> None: + self.response = response + self._cast_to = cast_to + self._client = client + self._options = options + self._decoder = client._make_sse_decoder() + self._iterator = self.__stream__() + + async def __anext__(self) -> _T: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[_T]: + async for item in self._iterator: + yield item + + async def _iter_events(self) -> AsyncIterator[ServerSentEvent]: + async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()): + yield sse + + async def __stream__(self) -> AsyncIterator[_T]: + cast_to = cast(Any, self._cast_to) + response = self.response + process_data = self._client._process_response_data + iterator = self._iter_events() + + try: + async for sse in iterator: + if sse.event == "completion": + yield process_data(data=sse.json(), cast_to=cast_to, response=response) + + if ( + sse.event == "message_start" + or sse.event == "message_delta" + or sse.event == "message_stop" + or sse.event == "content_block_start" + or sse.event == "content_block_delta" + or sse.event == "content_block_stop" + or sse.event == "message" + ): + data = sse.json() + if is_dict(data) and "type" not in data: + data["type"] = sse.event + + yield process_data(data=data, cast_to=cast_to, response=response) + + if sse.event == "ping": + continue + + if sse.event == "error": + body = sse.data + + try: + body = sse.json() + err_msg = f"{body}" + except Exception: + err_msg = sse.data or f"Error code: {response.status_code}" + + raise self._client._make_status_error( + err_msg, + body=body, + response=self.response, + ) + finally: + # Ensure the response is closed even if the consumer doesn't read all data + await response.aclose() + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self.response.aclose() + + +class ServerSentEvent: + def __init__( + self, + *, + event: str | None = None, + data: str | None = None, + id: str | None = None, + retry: int | None = None, + ) -> None: + if data is None: + data = "" + + self._id = id + self._data = data + self._event = event or None + self._retry = retry + + @property + def event(self) -> str | None: + return self._event + + @property + def id(self) -> str | None: + return self._id + + @property + def retry(self) -> int | None: + return self._retry + + @property + def data(self) -> str: + return self._data + + def json(self) -> Any: + return json.loads(self.data) + + @override + def __repr__(self) -> str: + return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})" + + +class SSEDecoder: + _data: list[str] + _event: str | None + _retry: int | None + _last_event_id: str | None + + def __init__(self) -> None: + self._event = None + self._data = [] + self._last_event_id = None + self._retry = None + + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + for chunk in self._iter_chunks(iterator): + # Split before decoding so splitlines() only uses \r and \n + for raw_line in chunk.splitlines(): + line = raw_line.decode("utf-8") + sse = self.decode(line) + if sse: + yield sse + + def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]: + """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" + data = b"" + for chunk in iterator: + for line in chunk.splitlines(keepends=True): + data += line + if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): + yield data + data = b"" + if data: + yield data + + async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + async for chunk in self._aiter_chunks(iterator): + # Split before decoding so splitlines() only uses \r and \n + for raw_line in chunk.splitlines(): + line = raw_line.decode("utf-8") + sse = self.decode(line) + if sse: + yield sse + + async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]: + """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" + data = b"" + async for chunk in iterator: + for line in chunk.splitlines(keepends=True): + data += line + if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): + yield data + data = b"" + if data: + yield data + + def decode(self, line: str) -> ServerSentEvent | None: + # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501 + + if not line: + if not self._event and not self._data and not self._last_event_id and self._retry is None: + return None + + sse = ServerSentEvent( + event=self._event, + data="\n".join(self._data), + id=self._last_event_id, + retry=self._retry, + ) + + # NOTE: as per the SSE spec, do not reset last_event_id. + self._event = None + self._data = [] + self._retry = None + + return sse + + if line.startswith(":"): + return None + + fieldname, _, value = line.partition(":") + + if value.startswith(" "): + value = value[1:] + + if fieldname == "event": + self._event = value + elif fieldname == "data": + self._data.append(value) + elif fieldname == "id": + if "\0" in value: + pass + else: + self._last_event_id = value + elif fieldname == "retry": + try: + self._retry = int(value) + except (TypeError, ValueError): + pass + else: + pass # Field is ignored. + + return None + + +@runtime_checkable +class SSEBytesDecoder(Protocol): + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + ... + + def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an async iterator that yields raw binary data, iterate over it & yield every event encountered""" + ... + + +def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]: + """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`""" + origin = get_origin(typ) or typ + return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream)) + + +def extract_stream_chunk_type( + stream_cls: type, + *, + failure_message: str | None = None, +) -> type: + """Given a type like `Stream[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyStream(Stream[bytes]): + ... + + extract_stream_chunk_type(MyStream) -> bytes + ``` + """ + from ._base_client import Stream, AsyncStream + + return extract_type_var_from_base( + stream_cls, + index=0, + generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)), + failure_message=failure_message, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_types.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..16d1ba3f45eb01bf6696aad196ebeb3db6a7ad70 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_types.py @@ -0,0 +1,272 @@ +from __future__ import annotations + +from os import PathLike +from typing import ( + IO, + TYPE_CHECKING, + Any, + Dict, + List, + Type, + Tuple, + Union, + Mapping, + TypeVar, + Callable, + Iterable, + Iterator, + Optional, + Sequence, + AsyncIterable, +) +from typing_extensions import ( + Set, + Literal, + Protocol, + TypeAlias, + TypedDict, + SupportsIndex, + overload, + override, + runtime_checkable, +) + +import httpx +import pydantic +from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport + +if TYPE_CHECKING: + from ._models import BaseModel + from ._response import APIResponse, AsyncAPIResponse + from ._legacy_response import HttpxBinaryResponseContent + +Transport = BaseTransport +AsyncTransport = AsyncBaseTransport +Query = Mapping[str, object] +Body = object +AnyMapping = Mapping[str, object] +ModelT = TypeVar("ModelT", bound=pydantic.BaseModel) +_T = TypeVar("_T") + + +# Approximates httpx internal ProxiesTypes and RequestFiles types +# while adding support for `PathLike` instances +ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]] +ProxiesTypes = Union[str, Proxy, ProxiesDict] +if TYPE_CHECKING: + Base64FileInput = Union[IO[bytes], PathLike[str]] + FileContent = Union[IO[bytes], bytes, PathLike[str]] +else: + Base64FileInput = Union[IO[bytes], PathLike] + FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8. + + +# Used for sending raw binary data / streaming data in request bodies +# e.g. for file uploads without multipart encoding +BinaryTypes = Union[bytes, bytearray, IO[bytes], Iterable[bytes]] +AsyncBinaryTypes = Union[bytes, bytearray, IO[bytes], AsyncIterable[bytes]] + +FileTypes = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], +] +RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] + +# duplicate of the above but without our custom file support +HttpxFileContent = Union[IO[bytes], bytes] +HttpxFileTypes = Union[ + # file (or bytes) + HttpxFileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], HttpxFileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], HttpxFileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]], +] +HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]] + +# Workaround to support (cast_to: Type[ResponseT]) -> ResponseT +# where ResponseT includes `None`. In order to support directly +# passing `None`, overloads would have to be defined for every +# method that uses `ResponseT` which would lead to an unacceptable +# amount of code duplication and make it unreadable. See _base_client.py +# for example usage. +# +# This unfortunately means that you will either have +# to import this type and pass it explicitly: +# +# from anthropic import NoneType +# client.get('/foo', cast_to=NoneType) +# +# or build it yourself: +# +# client.get('/foo', cast_to=type(None)) +if TYPE_CHECKING: + NoneType: Type[None] +else: + NoneType = type(None) + + +class RequestOptions(TypedDict, total=False): + headers: Headers + max_retries: int + timeout: float | Timeout | None + params: Query + extra_json: AnyMapping + idempotency_key: str + follow_redirects: bool + + +# Sentinel class used until PEP 0661 is accepted +class NotGiven: + """ + For parameters with a meaningful None value, we need to distinguish between + the user explicitly passing None, and the user not passing the parameter at + all. + + User code shouldn't need to use not_given directly. + + For example: + + ```py + def create(timeout: Timeout | None | NotGiven = not_given): ... + + + create(timeout=1) # 1s timeout + create(timeout=None) # No timeout + create() # Default timeout behavior + ``` + """ + + def __bool__(self) -> Literal[False]: + return False + + @override + def __repr__(self) -> str: + return "NOT_GIVEN" + + +not_given = NotGiven() +# for backwards compatibility: +NOT_GIVEN = NotGiven() + + +class Omit: + """ + To explicitly omit something from being sent in a request, use `omit`. + + ```py + # as the default `Content-Type` header is `application/json` that will be sent + client.post("/upload/files", files={"file": b"my raw file content"}) + + # you can't explicitly override the header as it has to be dynamically generated + # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983' + client.post(..., headers={"Content-Type": "multipart/form-data"}) + + # instead you can remove the default `application/json` header by passing omit + client.post(..., headers={"Content-Type": omit}) + ``` + """ + + def __bool__(self) -> Literal[False]: + return False + + +omit = Omit() + + +@runtime_checkable +class ModelBuilderProtocol(Protocol): + @classmethod + def build( + cls: type[_T], + *, + response: Response, + data: object, + ) -> _T: ... + + +Headers = Mapping[str, Union[str, Omit]] + + +class HeadersLikeProtocol(Protocol): + def get(self, __key: str) -> str | None: ... + + +HeadersLike = Union[Headers, HeadersLikeProtocol] + +ResponseT = TypeVar( + "ResponseT", + bound=Union[ + object, + str, + None, + "BaseModel", + List[Any], + Dict[str, Any], + Response, + ModelBuilderProtocol, + "APIResponse[Any]", + "AsyncAPIResponse[Any]", + "HttpxBinaryResponseContent", + ], +) + +StrBytesIntFloat = Union[str, bytes, int, float] + +# Note: copied from Pydantic +# https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79 +IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]] + +PostParser = Callable[[Any], Any] + + +@runtime_checkable +class InheritsGeneric(Protocol): + """Represents a type that has inherited from `Generic` + + The `__orig_bases__` property can be used to determine the resolved + type variable for a given base class. + """ + + __orig_bases__: tuple[_GenericAlias] + + +class _GenericAlias(Protocol): + __origin__: type[object] + + +class HttpxSendArgs(TypedDict, total=False): + auth: httpx.Auth + follow_redirects: bool + + +_T_co = TypeVar("_T_co", covariant=True) + + +if TYPE_CHECKING: + # This works because str.__contains__ does not accept object (either in typeshed or at runtime) + # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285 + # + # Note: index() and count() methods are intentionally omitted to allow pyright to properly + # infer TypedDict types when dict literals are used in lists assigned to SequenceNotStr. + class SequenceNotStr(Protocol[_T_co]): + @overload + def __getitem__(self, index: SupportsIndex, /) -> _T_co: ... + @overload + def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ... + def __contains__(self, value: object, /) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... +else: + # just point this to a normal `Sequence` at runtime to avoid having to special case + # deserializing our custom sequence type + SequenceNotStr = Sequence diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/_version.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..9c558dc5ba9aab46b66baec10a22fc2b32817a7a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/_version.py @@ -0,0 +1,4 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +__title__ = "anthropic" +__version__ = "0.94.0" # x-release-please-version diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/pagination.py b/data/miniconda3/lib/python3.13/site-packages/anthropic/pagination.py new file mode 100644 index 0000000000000000000000000000000000000000..470356b4c18acb263717ce33a7cd5812ade8f8b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anthropic/pagination.py @@ -0,0 +1,182 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Generic, TypeVar, Optional +from typing_extensions import override + +from ._base_client import BasePage, PageInfo, BaseSyncPage, BaseAsyncPage + +__all__ = ["SyncPage", "AsyncPage", "SyncTokenPage", "AsyncTokenPage", "SyncPageCursor", "AsyncPageCursor"] + +_T = TypeVar("_T") + + +class SyncPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] + has_more: Optional[bool] = None + first_id: Optional[str] = None + last_id: Optional[str] = None + + @override + def _get_page_items(self) -> List[_T]: + data = self.data + if not data: + return [] + return data + + @override + def has_next_page(self) -> bool: + has_more = self.has_more + if has_more is not None and has_more is False: + return False + + return super().has_next_page() + + @override + def next_page_info(self) -> Optional[PageInfo]: + if self._options.params.get("before_id"): + first_id = self.first_id + if not first_id: + return None + + return PageInfo(params={"before_id": first_id}) + + last_id = self.last_id + if not last_id: + return None + + return PageInfo(params={"after_id": last_id}) + + +class AsyncPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] + has_more: Optional[bool] = None + first_id: Optional[str] = None + last_id: Optional[str] = None + + @override + def _get_page_items(self) -> List[_T]: + data = self.data + if not data: + return [] + return data + + @override + def has_next_page(self) -> bool: + has_more = self.has_more + if has_more is not None and has_more is False: + return False + + return super().has_next_page() + + @override + def next_page_info(self) -> Optional[PageInfo]: + if self._options.params.get("before_id"): + first_id = self.first_id + if not first_id: + return None + + return PageInfo(params={"before_id": first_id}) + + last_id = self.last_id + if not last_id: + return None + + return PageInfo(params={"after_id": last_id}) + + +class SyncTokenPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] + has_more: Optional[bool] = None + next_page: Optional[str] = None + + @override + def _get_page_items(self) -> List[_T]: + data = self.data + if not data: + return [] + return data + + @override + def has_next_page(self) -> bool: + has_more = self.has_more + if has_more is not None and has_more is False: + return False + + return super().has_next_page() + + @override + def next_page_info(self) -> Optional[PageInfo]: + next_page = self.next_page + if not next_page: + return None + + return PageInfo(params={"page_token": next_page}) + + +class AsyncTokenPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] + has_more: Optional[bool] = None + next_page: Optional[str] = None + + @override + def _get_page_items(self) -> List[_T]: + data = self.data + if not data: + return [] + return data + + @override + def has_next_page(self) -> bool: + has_more = self.has_more + if has_more is not None and has_more is False: + return False + + return super().has_next_page() + + @override + def next_page_info(self) -> Optional[PageInfo]: + next_page = self.next_page + if not next_page: + return None + + return PageInfo(params={"page_token": next_page}) + + +class SyncPageCursor(BaseSyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] + next_page: Optional[str] = None + + @override + def _get_page_items(self) -> List[_T]: + data = self.data + if not data: + return [] + return data + + @override + def next_page_info(self) -> Optional[PageInfo]: + next_page = self.next_page + if not next_page: + return None + + return PageInfo(params={"page": next_page}) + + +class AsyncPageCursor(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] + next_page: Optional[str] = None + + @override + def _get_page_items(self) -> List[_T]: + data = self.data + if not data: + return [] + return data + + @override + def next_page_info(self) -> Optional[PageInfo]: + next_page = self.next_page + if not next_page: + return None + + return PageInfo(params={"page": next_page}) diff --git a/data/miniconda3/lib/python3.13/site-packages/anthropic/py.typed b/data/miniconda3/lib/python3.13/site-packages/anthropic/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..2de1cd5521ede953e5f08c09a09a7a6e125049d5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/METADATA @@ -0,0 +1,105 @@ +Metadata-Version: 2.4 +Name: anyio +Version: 4.13.0 +Summary: High-level concurrency and networking framework on top of asyncio or Trio +Author-email: Alex Grönholm +License-Expression: MIT +Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/ +Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html +Project-URL: Source code, https://github.com/agronholm/anyio +Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Framework :: AnyIO +Classifier: Typing :: Typed +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11" +Requires-Dist: idna>=2.8 +Requires-Dist: typing_extensions>=4.5; python_version < "3.13" +Provides-Extra: trio +Requires-Dist: trio>=0.32.0; extra == "trio" +Dynamic: license-file + +.. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg + :target: https://github.com/agronholm/anyio/actions/workflows/test.yml + :alt: Build Status +.. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master + :target: https://coveralls.io/github/agronholm/anyio?branch=master + :alt: Code Coverage +.. image:: https://readthedocs.org/projects/anyio/badge/?version=latest + :target: https://anyio.readthedocs.io/en/latest/?badge=latest + :alt: Documentation +.. image:: https://badges.gitter.im/gitterHQ/gitter.svg + :target: https://gitter.im/python-trio/AnyIO + :alt: Gitter chat +.. image:: https://tidelift.com/badges/package/pypi/anyio + :target: https://tidelift.com/subscription/pkg/pypi-anyio + :alt: Tidelift + +AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or +Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony +with the native SC of Trio itself. + +Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or +Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full +refactoring necessary. It will blend in with the native libraries of your chosen backend. + +To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it +`here `_. + +Documentation +------------- + +View full documentation at: https://anyio.readthedocs.io/ + +Features +-------- + +AnyIO offers the following functionality: + +* Task groups (nurseries_ in trio terminology) +* High-level networking (TCP, UDP and UNIX sockets) + + * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python + 3.8) + * async/await style UDP sockets (unlike asyncio where you still have to use Transports and + Protocols) + +* A versatile API for byte streams and object streams +* Inter-task synchronization and communication (locks, conditions, events, semaphores, object + streams) +* Worker threads +* Subprocesses +* Subinterpreter support for code parallelization (on Python 3.13 and later) +* Asynchronous file I/O (using worker threads) +* Signal handling +* Asynchronous version of the functools_ module + +AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures. +It even works with the popular Hypothesis_ library. + +.. _asyncio: https://docs.python.org/3/library/asyncio.html +.. _Trio: https://github.com/python-trio/trio +.. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency +.. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning +.. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs +.. _pytest: https://docs.pytest.org/en/latest/ +.. _functools: https://docs.python.org/3/library/functools.html +.. _Hypothesis: https://hypothesis.works/ + +Security contact information +---------------------------- + +To report a security vulnerability, please use the `Tidelift security contact`_. +Tidelift will coordinate the fix and disclosure. + +.. _Tidelift security contact: https://tidelift.com/security diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..df5573a3a028f5580c7c611395d2bca66816ff8b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/RECORD @@ -0,0 +1,92 @@ +anyio-4.13.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +anyio-4.13.0.dist-info/METADATA,sha256=F0EYfiPlmTRwmJN2JktNxJg1GNnl0wHhzOWmz7pFvjM,4513 +anyio-4.13.0.dist-info/RECORD,, +anyio-4.13.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +anyio-4.13.0.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39 +anyio-4.13.0.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081 +anyio-4.13.0.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6 +anyio/__init__.py,sha256=7iDVqMUprUuKNY91FuoKqayAhR-OY136YDPI6P78HHk,6170 +anyio/__pycache__/__init__.cpython-313.pyc,, +anyio/__pycache__/from_thread.cpython-313.pyc,, +anyio/__pycache__/functools.cpython-313.pyc,, +anyio/__pycache__/lowlevel.cpython-313.pyc,, +anyio/__pycache__/pytest_plugin.cpython-313.pyc,, +anyio/__pycache__/to_interpreter.cpython-313.pyc,, +anyio/__pycache__/to_process.cpython-313.pyc,, +anyio/__pycache__/to_thread.cpython-313.pyc,, +anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/_backends/__pycache__/__init__.cpython-313.pyc,, +anyio/_backends/__pycache__/_asyncio.cpython-313.pyc,, +anyio/_backends/__pycache__/_trio.cpython-313.pyc,, +anyio/_backends/_asyncio.py,sha256=kuqlg2sBUsFdgY80xSDAw60Gx_4WNCl9iSL5XlY6lCU,99476 +anyio/_backends/_trio.py,sha256=l9U-TsKRxzmTQxSMvOhn0bNeFn_iRx3Ho30jvR5Bdu0,41366 +anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/_core/__pycache__/__init__.cpython-313.pyc,, +anyio/_core/__pycache__/_asyncio_selector_thread.cpython-313.pyc,, +anyio/_core/__pycache__/_contextmanagers.cpython-313.pyc,, +anyio/_core/__pycache__/_eventloop.cpython-313.pyc,, +anyio/_core/__pycache__/_exceptions.cpython-313.pyc,, +anyio/_core/__pycache__/_fileio.cpython-313.pyc,, +anyio/_core/__pycache__/_resources.cpython-313.pyc,, +anyio/_core/__pycache__/_signals.cpython-313.pyc,, +anyio/_core/__pycache__/_sockets.cpython-313.pyc,, +anyio/_core/__pycache__/_streams.cpython-313.pyc,, +anyio/_core/__pycache__/_subprocesses.cpython-313.pyc,, +anyio/_core/__pycache__/_synchronization.cpython-313.pyc,, +anyio/_core/__pycache__/_tasks.cpython-313.pyc,, +anyio/_core/__pycache__/_tempfile.cpython-313.pyc,, +anyio/_core/__pycache__/_testing.cpython-313.pyc,, +anyio/_core/__pycache__/_typedattr.cpython-313.pyc,, +anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626 +anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215 +anyio/_core/_eventloop.py,sha256=c2EdcBX-xnKwxPcC4Pjn3_qG9I-x4IWFO2R9RqCGjM4,6448 +anyio/_core/_exceptions.py,sha256=Y3aq-Wxd7Q2HqwSg7nZPvRsHEuGazv_qeet6gqEBdPk,4407 +anyio/_core/_fileio.py,sha256=CKi1gFNiW2G4knWeBE7He7-rptQwgYjDUWfG8DSlvLs,25665 +anyio/_core/_resources.py,sha256=NbmU5O5UX3xEyACnkmYX28Fmwdl-f-ny0tHym26e0w0,435 +anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016 +anyio/_core/_sockets.py,sha256=RBXHcUqZt5gg_-OOfgHVv8uq2FSKk1uVUzTdpjBoI1o,34977 +anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806 +anyio/_core/_subprocesses.py,sha256=tkmkPKEkEaiMD8C9WRZBlmgjOYRDRbZdte6e-unay2E,7916 +anyio/_core/_synchronization.py,sha256=9G3fvRsPNrrWJ_Z6gD_80wXq8I8qgAyhwM8PvHQnT2c,21061 +anyio/_core/_tasks.py,sha256=pVB7K6AAulzUM8YgXAeqNZG44nSyZ1bYJjH8GznC00I,5435 +anyio/_core/_tempfile.py,sha256=jE2w59FRF3yRo4vjkjfZF2YcqsBZvc66VWRwrJGDYGk,19624 +anyio/_core/_testing.py,sha256=u7MPqGXwpTxqI7hclSdNA30z2GH1Nw258uwKvy_RfBg,2340 +anyio/_core/_typedattr.py,sha256=P4ozZikn3-DbpoYcvyghS_FOYAgbmUxeoU8-L_07pZM,2508 +anyio/abc/__init__.py,sha256=6mWhcl_pGXhrgZVHP_TCfMvIXIOp9mroEFM90fYCU_U,2869 +anyio/abc/__pycache__/__init__.cpython-313.pyc,, +anyio/abc/__pycache__/_eventloop.cpython-313.pyc,, +anyio/abc/__pycache__/_resources.cpython-313.pyc,, +anyio/abc/__pycache__/_sockets.cpython-313.pyc,, +anyio/abc/__pycache__/_streams.cpython-313.pyc,, +anyio/abc/__pycache__/_subprocesses.cpython-313.pyc,, +anyio/abc/__pycache__/_tasks.cpython-313.pyc,, +anyio/abc/__pycache__/_testing.cpython-313.pyc,, +anyio/abc/_eventloop.py,sha256=39lYnmtvoHaZw22sWBKOTA_zv7bamOnr8O49PqgDXdw,10629 +anyio/abc/_resources.py,sha256=DrYvkNN1hH6Uvv5_5uKySvDsnknGVDe8FCKfko0VtN8,783 +anyio/abc/_sockets.py,sha256=OmVDrfemVvF9c5K1tpBgQyV6fn5v0XyCExLAqBOGz9o,13124 +anyio/abc/_streams.py,sha256=HYvna1iZbWcwLROTO6IhLX79RTRLPShZMWe0sG1q54I,7481 +anyio/abc/_subprocesses.py,sha256=cumAPJTktOQtw63IqG0lDpyZqu_l1EElvQHMiwJgL08,2067 +anyio/abc/_tasks.py,sha256=KC7wrciE48AINOI-AhPutnFhe1ewfP7QnamFlDzqesQ,3721 +anyio/abc/_testing.py,sha256=tBJUzkSfOXJw23fe8qSJ03kJlShOYjjaEyFB6k6MYT8,1821 +anyio/from_thread.py,sha256=L-0w1HxJ6BSb-KuVi57k5Tkc3yzQrx3QK5tAxMPcY-0,19141 +anyio/functools.py,sha256=5AWM1iYTKkTzptvUhQDdLSh5GvbBW-vcs-SAUfIfA9A,12076 +anyio/lowlevel.py,sha256=AyKLVK3LaWSoK39LkCKxE4_GDMLKZBNqTrLUgk63y80,5158 +anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/pytest_plugin.py,sha256=t6h4KJstqIxfxwTZ1YO8vpUVuB99nfCLltn0NHfatHo,12775 +anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/streams/__pycache__/__init__.cpython-313.pyc,, +anyio/streams/__pycache__/buffered.cpython-313.pyc,, +anyio/streams/__pycache__/file.cpython-313.pyc,, +anyio/streams/__pycache__/memory.cpython-313.pyc,, +anyio/streams/__pycache__/stapled.cpython-313.pyc,, +anyio/streams/__pycache__/text.cpython-313.pyc,, +anyio/streams/__pycache__/tls.cpython-313.pyc,, +anyio/streams/buffered.py,sha256=2R3PeJhe4EXrdYqz44Y6-Eg9R6DrmlsYrP36Ir43-po,6263 +anyio/streams/file.py,sha256=msnrotVKGMQomUu_Rj2qz9MvIdUp6d3JGr7MOEO8kV4,4428 +anyio/streams/memory.py,sha256=F0zwzvFJKAhX_LRZGoKzzqDC2oMM-f-yyTBrEYEGOaU,10740 +anyio/streams/stapled.py,sha256=T8Xqwf8K6EgURPxbt1N4i7A8BAk-gScv-GRhjLXIf_o,4390 +anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765 +anyio/streams/tls.py,sha256=DQVkXUvsTEYKkBO8dlVU7j_5H8QOtLy4sGi1Wrjqevo,15303 +anyio/to_interpreter.py,sha256=_mLngrMy97TMR6VbW4Y6YzDUk9ZuPcQMPlkuyRh3C9k,7100 +anyio/to_process.py,sha256=J7gAA_YOuoHqnpDAf5fm1Qu6kOmTzdFbiDNvnV755vk,9798 +anyio/to_thread.py,sha256=f6h_k2d743GBv9FhAnhM_YpTvWgIrzBy9cOE0eJ1UJw,2693 diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..44dd9bdc3039122cc98014c1439ca254313fd014 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[pytest11] +anyio = anyio.pytest_plugin diff --git a/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c77c069ecc9b7f8b1f97dbcfec905725db0253a8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anyio-4.13.0.dist-info/top_level.txt @@ -0,0 +1 @@ +anyio diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__init__.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d3a37990145e94ad85406166dbaf52f4c311e5e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__init__.py @@ -0,0 +1,48 @@ +""" +Charset-Normalizer +~~~~~~~~~~~~~~ +The Real First Universal Charset Detector. +A library that helps you read text from an unknown charset encoding. +Motivated by chardet, This package is trying to resolve the issue by taking a new approach. +All IANA character set names for which the Python core library provides codecs are supported. + +Basic usage: + >>> from charset_normalizer import from_bytes + >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието!'.encode('utf_8')) + >>> best_guess = results.best() + >>> str(best_guess) + 'Bсеки човек има право на образование. Oбразованието!' + +Others methods and usages are available - see the full documentation +at . +:copyright: (c) 2021 by Ahmed TAHRI +:license: MIT, see LICENSE for more details. +""" + +from __future__ import annotations + +import logging + +from .api import from_bytes, from_fp, from_path, is_binary +from .legacy import detect +from .models import CharsetMatch, CharsetMatches +from .utils import set_logging_handler +from .version import VERSION, __version__ + +__all__ = ( + "from_fp", + "from_path", + "from_bytes", + "is_binary", + "detect", + "CharsetMatch", + "CharsetMatches", + "__version__", + "VERSION", + "set_logging_handler", +) + +# Attach a NullHandler to the top level logger by default +# https://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library + +logging.getLogger("charset_normalizer").addHandler(logging.NullHandler()) diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__main__.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e76f7bfbb411d4424d3a1834b0ea803d80ea7e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/__main__.py @@ -0,0 +1,6 @@ +from __future__ import annotations + +from .cli import cli_detect + +if __name__ == "__main__": + cli_detect() diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/api.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/api.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd96390507bac07ae21d513b45777011a539892 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/api.py @@ -0,0 +1,669 @@ +from __future__ import annotations + +import logging +from os import PathLike +from typing import BinaryIO + +from .cd import ( + coherence_ratio, + encoding_languages, + mb_encoding_languages, + merge_coherence_ratios, +) +from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE +from .md import mess_ratio +from .models import CharsetMatch, CharsetMatches +from .utils import ( + any_specified_encoding, + cut_sequence_chunks, + iana_name, + identify_sig_or_bom, + is_cp_similar, + is_multi_byte_encoding, + should_strip_sig_or_bom, +) + +logger = logging.getLogger("charset_normalizer") +explain_handler = logging.StreamHandler() +explain_handler.setFormatter( + logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") +) + + +def from_bytes( + sequences: bytes | bytearray, + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.2, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Given a raw bytes sequence, return the best possibles charset usable to render str objects. + If there is no results, it is a strong indicator that the source is binary/not text. + By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence. + And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will. + + The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page + but never take it for granted. Can improve the performance. + + You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that + purpose. + + This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32. + By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain' + toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging. + Custom logging format and handler can be set manually. + """ + + if not isinstance(sequences, (bytearray, bytes)): + raise TypeError( + "Expected object of type bytes or bytearray, got: {}".format( + type(sequences) + ) + ) + + if explain: + previous_logger_level: int = logger.level + logger.addHandler(explain_handler) + logger.setLevel(TRACE) + + length: int = len(sequences) + + if length == 0: + logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.") + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level or logging.WARNING) + return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")]) + + if cp_isolation is not None: + logger.log( + TRACE, + "cp_isolation is set. use this flag for debugging purpose. " + "limited list of encoding allowed : %s.", + ", ".join(cp_isolation), + ) + cp_isolation = [iana_name(cp, False) for cp in cp_isolation] + else: + cp_isolation = [] + + if cp_exclusion is not None: + logger.log( + TRACE, + "cp_exclusion is set. use this flag for debugging purpose. " + "limited list of encoding excluded : %s.", + ", ".join(cp_exclusion), + ) + cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion] + else: + cp_exclusion = [] + + if length <= (chunk_size * steps): + logger.log( + TRACE, + "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.", + steps, + chunk_size, + length, + ) + steps = 1 + chunk_size = length + + if steps > 1 and length / steps < chunk_size: + chunk_size = int(length / steps) + + is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE + is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE + + if is_too_small_sequence: + logger.log( + TRACE, + "Trying to detect encoding from a tiny portion of ({}) byte(s).".format( + length + ), + ) + elif is_too_large_sequence: + logger.log( + TRACE, + "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format( + length + ), + ) + + prioritized_encodings: list[str] = [] + + specified_encoding: str | None = ( + any_specified_encoding(sequences) if preemptive_behaviour else None + ) + + if specified_encoding is not None: + prioritized_encodings.append(specified_encoding) + logger.log( + TRACE, + "Detected declarative mark in sequence. Priority +1 given for %s.", + specified_encoding, + ) + + tested: set[str] = set() + tested_but_hard_failure: list[str] = [] + tested_but_soft_failure: list[str] = [] + + fallback_ascii: CharsetMatch | None = None + fallback_u8: CharsetMatch | None = None + fallback_specified: CharsetMatch | None = None + + results: CharsetMatches = CharsetMatches() + + early_stop_results: CharsetMatches = CharsetMatches() + + sig_encoding, sig_payload = identify_sig_or_bom(sequences) + + if sig_encoding is not None: + prioritized_encodings.append(sig_encoding) + logger.log( + TRACE, + "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.", + len(sig_payload), + sig_encoding, + ) + + prioritized_encodings.append("ascii") + + if "utf_8" not in prioritized_encodings: + prioritized_encodings.append("utf_8") + + for encoding_iana in prioritized_encodings + IANA_SUPPORTED: + if cp_isolation and encoding_iana not in cp_isolation: + continue + + if cp_exclusion and encoding_iana in cp_exclusion: + continue + + if encoding_iana in tested: + continue + + tested.add(encoding_iana) + + decoded_payload: str | None = None + bom_or_sig_available: bool = sig_encoding == encoding_iana + strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom( + encoding_iana + ) + + if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available: + logger.log( + TRACE, + "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.", + encoding_iana, + ) + continue + if encoding_iana in {"utf_7"} and not bom_or_sig_available: + logger.log( + TRACE, + "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.", + encoding_iana, + ) + continue + + try: + is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana) + except (ModuleNotFoundError, ImportError): + logger.log( + TRACE, + "Encoding %s does not provide an IncrementalDecoder", + encoding_iana, + ) + continue + + try: + if is_too_large_sequence and is_multi_byte_decoder is False: + str( + ( + sequences[: int(50e4)] + if strip_sig_or_bom is False + else sequences[len(sig_payload) : int(50e4)] + ), + encoding=encoding_iana, + ) + else: + decoded_payload = str( + ( + sequences + if strip_sig_or_bom is False + else sequences[len(sig_payload) :] + ), + encoding=encoding_iana, + ) + except (UnicodeDecodeError, LookupError) as e: + if not isinstance(e, LookupError): + logger.log( + TRACE, + "Code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + tested_but_hard_failure.append(encoding_iana) + continue + + similar_soft_failure_test: bool = False + + for encoding_soft_failed in tested_but_soft_failure: + if is_cp_similar(encoding_iana, encoding_soft_failed): + similar_soft_failure_test = True + break + + if similar_soft_failure_test: + logger.log( + TRACE, + "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!", + encoding_iana, + encoding_soft_failed, + ) + continue + + r_ = range( + 0 if not bom_or_sig_available else len(sig_payload), + length, + int(length / steps), + ) + + multi_byte_bonus: bool = ( + is_multi_byte_decoder + and decoded_payload is not None + and len(decoded_payload) < length + ) + + if multi_byte_bonus: + logger.log( + TRACE, + "Code page %s is a multi byte encoding table and it appear that at least one character " + "was encoded using n-bytes.", + encoding_iana, + ) + + max_chunk_gave_up: int = int(len(r_) / 4) + + max_chunk_gave_up = max(max_chunk_gave_up, 2) + early_stop_count: int = 0 + lazy_str_hard_failure = False + + md_chunks: list[str] = [] + md_ratios = [] + + try: + for chunk in cut_sequence_chunks( + sequences, + encoding_iana, + r_, + chunk_size, + bom_or_sig_available, + strip_sig_or_bom, + sig_payload, + is_multi_byte_decoder, + decoded_payload, + ): + md_chunks.append(chunk) + + md_ratios.append( + mess_ratio( + chunk, + threshold, + explain is True and 1 <= len(cp_isolation) <= 2, + ) + ) + + if md_ratios[-1] >= threshold: + early_stop_count += 1 + + if (early_stop_count >= max_chunk_gave_up) or ( + bom_or_sig_available and strip_sig_or_bom is False + ): + break + except ( + UnicodeDecodeError + ) as e: # Lazy str loading may have missed something there + logger.log( + TRACE, + "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + early_stop_count = max_chunk_gave_up + lazy_str_hard_failure = True + + # We might want to check the sequence again with the whole content + # Only if initial MD tests passes + if ( + not lazy_str_hard_failure + and is_too_large_sequence + and not is_multi_byte_decoder + ): + try: + sequences[int(50e3) :].decode(encoding_iana, errors="strict") + except UnicodeDecodeError as e: + logger.log( + TRACE, + "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + tested_but_hard_failure.append(encoding_iana) + continue + + mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0 + if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up: + tested_but_soft_failure.append(encoding_iana) + logger.log( + TRACE, + "%s was excluded because of initial chaos probing. Gave up %i time(s). " + "Computed mean chaos is %f %%.", + encoding_iana, + early_stop_count, + round(mean_mess_ratio * 100, ndigits=3), + ) + # Preparing those fallbacks in case we got nothing. + if ( + enable_fallback + and encoding_iana + in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"] + and not lazy_str_hard_failure + ): + fallback_entry = CharsetMatch( + sequences, + encoding_iana, + threshold, + bom_or_sig_available, + [], + decoded_payload, + preemptive_declaration=specified_encoding, + ) + if encoding_iana == specified_encoding: + fallback_specified = fallback_entry + elif encoding_iana == "ascii": + fallback_ascii = fallback_entry + else: + fallback_u8 = fallback_entry + continue + + logger.log( + TRACE, + "%s passed initial chaos probing. Mean measured chaos is %f %%", + encoding_iana, + round(mean_mess_ratio * 100, ndigits=3), + ) + + if not is_multi_byte_decoder: + target_languages: list[str] = encoding_languages(encoding_iana) + else: + target_languages = mb_encoding_languages(encoding_iana) + + if target_languages: + logger.log( + TRACE, + "{} should target any language(s) of {}".format( + encoding_iana, str(target_languages) + ), + ) + + cd_ratios = [] + + # We shall skip the CD when its about ASCII + # Most of the time its not relevant to run "language-detection" on it. + if encoding_iana != "ascii": + for chunk in md_chunks: + chunk_languages = coherence_ratio( + chunk, + language_threshold, + ",".join(target_languages) if target_languages else None, + ) + + cd_ratios.append(chunk_languages) + + cd_ratios_merged = merge_coherence_ratios(cd_ratios) + + if cd_ratios_merged: + logger.log( + TRACE, + "We detected language {} using {}".format( + cd_ratios_merged, encoding_iana + ), + ) + + current_match = CharsetMatch( + sequences, + encoding_iana, + mean_mess_ratio, + bom_or_sig_available, + cd_ratios_merged, + ( + decoded_payload + if ( + is_too_large_sequence is False + or encoding_iana in [specified_encoding, "ascii", "utf_8"] + ) + else None + ), + preemptive_declaration=specified_encoding, + ) + + results.append(current_match) + + if ( + encoding_iana in [specified_encoding, "ascii", "utf_8"] + and mean_mess_ratio < 0.1 + ): + # If md says nothing to worry about, then... stop immediately! + if mean_mess_ratio == 0.0: + logger.debug( + "Encoding detection: %s is most likely the one.", + current_match.encoding, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + return CharsetMatches([current_match]) + + early_stop_results.append(current_match) + + if ( + len(early_stop_results) + and (specified_encoding is None or specified_encoding in tested) + and "ascii" in tested + and "utf_8" in tested + ): + probable_result: CharsetMatch = early_stop_results.best() # type: ignore[assignment] + logger.debug( + "Encoding detection: %s is most likely the one.", + probable_result.encoding, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + + return CharsetMatches([probable_result]) + + if encoding_iana == sig_encoding: + logger.debug( + "Encoding detection: %s is most likely the one as we detected a BOM or SIG within " + "the beginning of the sequence.", + encoding_iana, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + return CharsetMatches([results[encoding_iana]]) + + if len(results) == 0: + if fallback_u8 or fallback_ascii or fallback_specified: + logger.log( + TRACE, + "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.", + ) + + if fallback_specified: + logger.debug( + "Encoding detection: %s will be used as a fallback match", + fallback_specified.encoding, + ) + results.append(fallback_specified) + elif ( + (fallback_u8 and fallback_ascii is None) + or ( + fallback_u8 + and fallback_ascii + and fallback_u8.fingerprint != fallback_ascii.fingerprint + ) + or (fallback_u8 is not None) + ): + logger.debug("Encoding detection: utf_8 will be used as a fallback match") + results.append(fallback_u8) + elif fallback_ascii: + logger.debug("Encoding detection: ascii will be used as a fallback match") + results.append(fallback_ascii) + + if results: + logger.debug( + "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.", + results.best().encoding, # type: ignore + len(results) - 1, + ) + else: + logger.debug("Encoding detection: Unable to determine any suitable charset.") + + if explain: + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + + return results + + +def from_fp( + fp: BinaryIO, + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Same thing than the function from_bytes but using a file pointer that is already ready. + Will not close the file pointer. + """ + return from_bytes( + fp.read(), + steps, + chunk_size, + threshold, + cp_isolation, + cp_exclusion, + preemptive_behaviour, + explain, + language_threshold, + enable_fallback, + ) + + +def from_path( + path: str | bytes | PathLike, # type: ignore[type-arg] + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode. + Can raise IOError. + """ + with open(path, "rb") as fp: + return from_fp( + fp, + steps, + chunk_size, + threshold, + cp_isolation, + cp_exclusion, + preemptive_behaviour, + explain, + language_threshold, + enable_fallback, + ) + + +def is_binary( + fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg] + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = False, +) -> bool: + """ + Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string. + Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match + are disabled to be stricter around ASCII-compatible but unlikely to be a string. + """ + if isinstance(fp_or_path_or_payload, (str, PathLike)): + guesses = from_path( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + elif isinstance( + fp_or_path_or_payload, + ( + bytes, + bytearray, + ), + ): + guesses = from_bytes( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + else: + guesses = from_fp( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + + return not guesses diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/cd.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/cd.py new file mode 100644 index 0000000000000000000000000000000000000000..71a3ed5197f788135bb700a15a64594780aa6337 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/cd.py @@ -0,0 +1,395 @@ +from __future__ import annotations + +import importlib +from codecs import IncrementalDecoder +from collections import Counter +from functools import lru_cache +from typing import Counter as TypeCounter + +from .constant import ( + FREQUENCIES, + KO_NAMES, + LANGUAGE_SUPPORTED_COUNT, + TOO_SMALL_SEQUENCE, + ZH_NAMES, +) +from .md import is_suspiciously_successive_range +from .models import CoherenceMatches +from .utils import ( + is_accentuated, + is_latin, + is_multi_byte_encoding, + is_unicode_range_secondary, + unicode_range, +) + + +def encoding_unicode_range(iana_name: str) -> list[str]: + """ + Return associated unicode ranges in a single byte code page. + """ + if is_multi_byte_encoding(iana_name): + raise OSError("Function not supported on multi-byte code page") + + decoder = importlib.import_module(f"encodings.{iana_name}").IncrementalDecoder + + p: IncrementalDecoder = decoder(errors="ignore") + seen_ranges: dict[str, int] = {} + character_count: int = 0 + + for i in range(0x40, 0xFF): + chunk: str = p.decode(bytes([i])) + + if chunk: + character_range: str | None = unicode_range(chunk) + + if character_range is None: + continue + + if is_unicode_range_secondary(character_range) is False: + if character_range not in seen_ranges: + seen_ranges[character_range] = 0 + seen_ranges[character_range] += 1 + character_count += 1 + + return sorted( + [ + character_range + for character_range in seen_ranges + if seen_ranges[character_range] / character_count >= 0.15 + ] + ) + + +def unicode_range_languages(primary_range: str) -> list[str]: + """ + Return inferred languages used with a unicode range. + """ + languages: list[str] = [] + + for language, characters in FREQUENCIES.items(): + for character in characters: + if unicode_range(character) == primary_range: + languages.append(language) + break + + return languages + + +@lru_cache() +def encoding_languages(iana_name: str) -> list[str]: + """ + Single-byte encoding language association. Some code page are heavily linked to particular language(s). + This function does the correspondence. + """ + unicode_ranges: list[str] = encoding_unicode_range(iana_name) + primary_range: str | None = None + + for specified_range in unicode_ranges: + if "Latin" not in specified_range: + primary_range = specified_range + break + + if primary_range is None: + return ["Latin Based"] + + return unicode_range_languages(primary_range) + + +@lru_cache() +def mb_encoding_languages(iana_name: str) -> list[str]: + """ + Multi-byte encoding language association. Some code page are heavily linked to particular language(s). + This function does the correspondence. + """ + if ( + iana_name.startswith("shift_") + or iana_name.startswith("iso2022_jp") + or iana_name.startswith("euc_j") + or iana_name == "cp932" + ): + return ["Japanese"] + if iana_name.startswith("gb") or iana_name in ZH_NAMES: + return ["Chinese"] + if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: + return ["Korean"] + + return [] + + +@lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT) +def get_target_features(language: str) -> tuple[bool, bool]: + """ + Determine main aspects from a supported language if it contains accents and if is pure Latin. + """ + target_have_accents: bool = False + target_pure_latin: bool = True + + for character in FREQUENCIES[language]: + if not target_have_accents and is_accentuated(character): + target_have_accents = True + if target_pure_latin and is_latin(character) is False: + target_pure_latin = False + + return target_have_accents, target_pure_latin + + +def alphabet_languages( + characters: list[str], ignore_non_latin: bool = False +) -> list[str]: + """ + Return associated languages associated to given characters. + """ + languages: list[tuple[str, float]] = [] + + source_have_accents = any(is_accentuated(character) for character in characters) + + for language, language_characters in FREQUENCIES.items(): + target_have_accents, target_pure_latin = get_target_features(language) + + if ignore_non_latin and target_pure_latin is False: + continue + + if target_have_accents is False and source_have_accents: + continue + + character_count: int = len(language_characters) + + character_match_count: int = len( + [c for c in language_characters if c in characters] + ) + + ratio: float = character_match_count / character_count + + if ratio >= 0.2: + languages.append((language, ratio)) + + languages = sorted(languages, key=lambda x: x[1], reverse=True) + + return [compatible_language[0] for compatible_language in languages] + + +def characters_popularity_compare( + language: str, ordered_characters: list[str] +) -> float: + """ + Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. + The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). + Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) + """ + if language not in FREQUENCIES: + raise ValueError(f"{language} not available") + + character_approved_count: int = 0 + FREQUENCIES_language_set = set(FREQUENCIES[language]) + + ordered_characters_count: int = len(ordered_characters) + target_language_characters_count: int = len(FREQUENCIES[language]) + + large_alphabet: bool = target_language_characters_count > 26 + + for character, character_rank in zip( + ordered_characters, range(0, ordered_characters_count) + ): + if character not in FREQUENCIES_language_set: + continue + + character_rank_in_language: int = FREQUENCIES[language].index(character) + expected_projection_ratio: float = ( + target_language_characters_count / ordered_characters_count + ) + character_rank_projection: int = int(character_rank * expected_projection_ratio) + + if ( + large_alphabet is False + and abs(character_rank_projection - character_rank_in_language) > 4 + ): + continue + + if ( + large_alphabet is True + and abs(character_rank_projection - character_rank_in_language) + < target_language_characters_count / 3 + ): + character_approved_count += 1 + continue + + characters_before_source: list[str] = FREQUENCIES[language][ + 0:character_rank_in_language + ] + characters_after_source: list[str] = FREQUENCIES[language][ + character_rank_in_language: + ] + characters_before: list[str] = ordered_characters[0:character_rank] + characters_after: list[str] = ordered_characters[character_rank:] + + before_match_count: int = len( + set(characters_before) & set(characters_before_source) + ) + + after_match_count: int = len( + set(characters_after) & set(characters_after_source) + ) + + if len(characters_before_source) == 0 and before_match_count <= 4: + character_approved_count += 1 + continue + + if len(characters_after_source) == 0 and after_match_count <= 4: + character_approved_count += 1 + continue + + if ( + before_match_count / len(characters_before_source) >= 0.4 + or after_match_count / len(characters_after_source) >= 0.4 + ): + character_approved_count += 1 + continue + + return character_approved_count / len(ordered_characters) + + +def alpha_unicode_split(decoded_sequence: str) -> list[str]: + """ + Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. + Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; + One containing the latin letters and the other hebrew. + """ + layers: dict[str, str] = {} + + for character in decoded_sequence: + if character.isalpha() is False: + continue + + character_range: str | None = unicode_range(character) + + if character_range is None: + continue + + layer_target_range: str | None = None + + for discovered_range in layers: + if ( + is_suspiciously_successive_range(discovered_range, character_range) + is False + ): + layer_target_range = discovered_range + break + + if layer_target_range is None: + layer_target_range = character_range + + if layer_target_range not in layers: + layers[layer_target_range] = character.lower() + continue + + layers[layer_target_range] += character.lower() + + return list(layers.values()) + + +def merge_coherence_ratios(results: list[CoherenceMatches]) -> CoherenceMatches: + """ + This function merge results previously given by the function coherence_ratio. + The return type is the same as coherence_ratio. + """ + per_language_ratios: dict[str, list[float]] = {} + for result in results: + for sub_result in result: + language, ratio = sub_result + if language not in per_language_ratios: + per_language_ratios[language] = [ratio] + continue + per_language_ratios[language].append(ratio) + + merge = [ + ( + language, + round( + sum(per_language_ratios[language]) / len(per_language_ratios[language]), + 4, + ), + ) + for language in per_language_ratios + ] + + return sorted(merge, key=lambda x: x[1], reverse=True) + + +def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches: + """ + We shall NOT return "English—" in CoherenceMatches because it is an alternative + of "English". This function only keeps the best match and remove the em-dash in it. + """ + index_results: dict[str, list[float]] = dict() + + for result in results: + language, ratio = result + no_em_name: str = language.replace("—", "") + + if no_em_name not in index_results: + index_results[no_em_name] = [] + + index_results[no_em_name].append(ratio) + + if any(len(index_results[e]) > 1 for e in index_results): + filtered_results: CoherenceMatches = [] + + for language in index_results: + filtered_results.append((language, max(index_results[language]))) + + return filtered_results + + return results + + +@lru_cache(maxsize=2048) +def coherence_ratio( + decoded_sequence: str, threshold: float = 0.1, lg_inclusion: str | None = None +) -> CoherenceMatches: + """ + Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers. + A layer = Character extraction by alphabets/ranges. + """ + + results: list[tuple[str, float]] = [] + ignore_non_latin: bool = False + + sufficient_match_count: int = 0 + + lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else [] + if "Latin Based" in lg_inclusion_list: + ignore_non_latin = True + lg_inclusion_list.remove("Latin Based") + + for layer in alpha_unicode_split(decoded_sequence): + sequence_frequencies: TypeCounter[str] = Counter(layer) + most_common = sequence_frequencies.most_common() + + character_count: int = sum(o for c, o in most_common) + + if character_count <= TOO_SMALL_SEQUENCE: + continue + + popular_character_ordered: list[str] = [c for c, o in most_common] + + for language in lg_inclusion_list or alphabet_languages( + popular_character_ordered, ignore_non_latin + ): + ratio: float = characters_popularity_compare( + language, popular_character_ordered + ) + + if ratio < threshold: + continue + elif ratio >= 0.8: + sufficient_match_count += 1 + + results.append((language, round(ratio, 4))) + + if sufficient_match_count >= 3: + break + + return sorted( + filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/constant.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/constant.py new file mode 100644 index 0000000000000000000000000000000000000000..cc71a019c7fdd7b99c7fdd5b6bb084ab2840ff63 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/constant.py @@ -0,0 +1,2015 @@ +from __future__ import annotations + +from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE +from encodings.aliases import aliases +from re import IGNORECASE +from re import compile as re_compile + +# Contain for each eligible encoding a list of/item bytes SIG/BOM +ENCODING_MARKS: dict[str, bytes | list[bytes]] = { + "utf_8": BOM_UTF8, + "utf_7": [ + b"\x2b\x2f\x76\x38", + b"\x2b\x2f\x76\x39", + b"\x2b\x2f\x76\x2b", + b"\x2b\x2f\x76\x2f", + b"\x2b\x2f\x76\x38\x2d", + ], + "gb18030": b"\x84\x31\x95\x33", + "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE], + "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE], +} + +TOO_SMALL_SEQUENCE: int = 32 +TOO_BIG_SEQUENCE: int = int(10e6) + +UTF8_MAXIMAL_ALLOCATION: int = 1_112_064 + +# Up-to-date Unicode ucd/15.0.0 +UNICODE_RANGES_COMBINED: dict[str, range] = { + "Control character": range(32), + "Basic Latin": range(32, 128), + "Latin-1 Supplement": range(128, 256), + "Latin Extended-A": range(256, 384), + "Latin Extended-B": range(384, 592), + "IPA Extensions": range(592, 688), + "Spacing Modifier Letters": range(688, 768), + "Combining Diacritical Marks": range(768, 880), + "Greek and Coptic": range(880, 1024), + "Cyrillic": range(1024, 1280), + "Cyrillic Supplement": range(1280, 1328), + "Armenian": range(1328, 1424), + "Hebrew": range(1424, 1536), + "Arabic": range(1536, 1792), + "Syriac": range(1792, 1872), + "Arabic Supplement": range(1872, 1920), + "Thaana": range(1920, 1984), + "NKo": range(1984, 2048), + "Samaritan": range(2048, 2112), + "Mandaic": range(2112, 2144), + "Syriac Supplement": range(2144, 2160), + "Arabic Extended-B": range(2160, 2208), + "Arabic Extended-A": range(2208, 2304), + "Devanagari": range(2304, 2432), + "Bengali": range(2432, 2560), + "Gurmukhi": range(2560, 2688), + "Gujarati": range(2688, 2816), + "Oriya": range(2816, 2944), + "Tamil": range(2944, 3072), + "Telugu": range(3072, 3200), + "Kannada": range(3200, 3328), + "Malayalam": range(3328, 3456), + "Sinhala": range(3456, 3584), + "Thai": range(3584, 3712), + "Lao": range(3712, 3840), + "Tibetan": range(3840, 4096), + "Myanmar": range(4096, 4256), + "Georgian": range(4256, 4352), + "Hangul Jamo": range(4352, 4608), + "Ethiopic": range(4608, 4992), + "Ethiopic Supplement": range(4992, 5024), + "Cherokee": range(5024, 5120), + "Unified Canadian Aboriginal Syllabics": range(5120, 5760), + "Ogham": range(5760, 5792), + "Runic": range(5792, 5888), + "Tagalog": range(5888, 5920), + "Hanunoo": range(5920, 5952), + "Buhid": range(5952, 5984), + "Tagbanwa": range(5984, 6016), + "Khmer": range(6016, 6144), + "Mongolian": range(6144, 6320), + "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6400), + "Limbu": range(6400, 6480), + "Tai Le": range(6480, 6528), + "New Tai Lue": range(6528, 6624), + "Khmer Symbols": range(6624, 6656), + "Buginese": range(6656, 6688), + "Tai Tham": range(6688, 6832), + "Combining Diacritical Marks Extended": range(6832, 6912), + "Balinese": range(6912, 7040), + "Sundanese": range(7040, 7104), + "Batak": range(7104, 7168), + "Lepcha": range(7168, 7248), + "Ol Chiki": range(7248, 7296), + "Cyrillic Extended-C": range(7296, 7312), + "Georgian Extended": range(7312, 7360), + "Sundanese Supplement": range(7360, 7376), + "Vedic Extensions": range(7376, 7424), + "Phonetic Extensions": range(7424, 7552), + "Phonetic Extensions Supplement": range(7552, 7616), + "Combining Diacritical Marks Supplement": range(7616, 7680), + "Latin Extended Additional": range(7680, 7936), + "Greek Extended": range(7936, 8192), + "General Punctuation": range(8192, 8304), + "Superscripts and Subscripts": range(8304, 8352), + "Currency Symbols": range(8352, 8400), + "Combining Diacritical Marks for Symbols": range(8400, 8448), + "Letterlike Symbols": range(8448, 8528), + "Number Forms": range(8528, 8592), + "Arrows": range(8592, 8704), + "Mathematical Operators": range(8704, 8960), + "Miscellaneous Technical": range(8960, 9216), + "Control Pictures": range(9216, 9280), + "Optical Character Recognition": range(9280, 9312), + "Enclosed Alphanumerics": range(9312, 9472), + "Box Drawing": range(9472, 9600), + "Block Elements": range(9600, 9632), + "Geometric Shapes": range(9632, 9728), + "Miscellaneous Symbols": range(9728, 9984), + "Dingbats": range(9984, 10176), + "Miscellaneous Mathematical Symbols-A": range(10176, 10224), + "Supplemental Arrows-A": range(10224, 10240), + "Braille Patterns": range(10240, 10496), + "Supplemental Arrows-B": range(10496, 10624), + "Miscellaneous Mathematical Symbols-B": range(10624, 10752), + "Supplemental Mathematical Operators": range(10752, 11008), + "Miscellaneous Symbols and Arrows": range(11008, 11264), + "Glagolitic": range(11264, 11360), + "Latin Extended-C": range(11360, 11392), + "Coptic": range(11392, 11520), + "Georgian Supplement": range(11520, 11568), + "Tifinagh": range(11568, 11648), + "Ethiopic Extended": range(11648, 11744), + "Cyrillic Extended-A": range(11744, 11776), + "Supplemental Punctuation": range(11776, 11904), + "CJK Radicals Supplement": range(11904, 12032), + "Kangxi Radicals": range(12032, 12256), + "Ideographic Description Characters": range(12272, 12288), + "CJK Symbols and Punctuation": range(12288, 12352), + "Hiragana": range(12352, 12448), + "Katakana": range(12448, 12544), + "Bopomofo": range(12544, 12592), + "Hangul Compatibility Jamo": range(12592, 12688), + "Kanbun": range(12688, 12704), + "Bopomofo Extended": range(12704, 12736), + "CJK Strokes": range(12736, 12784), + "Katakana Phonetic Extensions": range(12784, 12800), + "Enclosed CJK Letters and Months": range(12800, 13056), + "CJK Compatibility": range(13056, 13312), + "CJK Unified Ideographs Extension A": range(13312, 19904), + "Yijing Hexagram Symbols": range(19904, 19968), + "CJK Unified Ideographs": range(19968, 40960), + "Yi Syllables": range(40960, 42128), + "Yi Radicals": range(42128, 42192), + "Lisu": range(42192, 42240), + "Vai": range(42240, 42560), + "Cyrillic Extended-B": range(42560, 42656), + "Bamum": range(42656, 42752), + "Modifier Tone Letters": range(42752, 42784), + "Latin Extended-D": range(42784, 43008), + "Syloti Nagri": range(43008, 43056), + "Common Indic Number Forms": range(43056, 43072), + "Phags-pa": range(43072, 43136), + "Saurashtra": range(43136, 43232), + "Devanagari Extended": range(43232, 43264), + "Kayah Li": range(43264, 43312), + "Rejang": range(43312, 43360), + "Hangul Jamo Extended-A": range(43360, 43392), + "Javanese": range(43392, 43488), + "Myanmar Extended-B": range(43488, 43520), + "Cham": range(43520, 43616), + "Myanmar Extended-A": range(43616, 43648), + "Tai Viet": range(43648, 43744), + "Meetei Mayek Extensions": range(43744, 43776), + "Ethiopic Extended-A": range(43776, 43824), + "Latin Extended-E": range(43824, 43888), + "Cherokee Supplement": range(43888, 43968), + "Meetei Mayek": range(43968, 44032), + "Hangul Syllables": range(44032, 55216), + "Hangul Jamo Extended-B": range(55216, 55296), + "High Surrogates": range(55296, 56192), + "High Private Use Surrogates": range(56192, 56320), + "Low Surrogates": range(56320, 57344), + "Private Use Area": range(57344, 63744), + "CJK Compatibility Ideographs": range(63744, 64256), + "Alphabetic Presentation Forms": range(64256, 64336), + "Arabic Presentation Forms-A": range(64336, 65024), + "Variation Selectors": range(65024, 65040), + "Vertical Forms": range(65040, 65056), + "Combining Half Marks": range(65056, 65072), + "CJK Compatibility Forms": range(65072, 65104), + "Small Form Variants": range(65104, 65136), + "Arabic Presentation Forms-B": range(65136, 65280), + "Halfwidth and Fullwidth Forms": range(65280, 65520), + "Specials": range(65520, 65536), + "Linear B Syllabary": range(65536, 65664), + "Linear B Ideograms": range(65664, 65792), + "Aegean Numbers": range(65792, 65856), + "Ancient Greek Numbers": range(65856, 65936), + "Ancient Symbols": range(65936, 66000), + "Phaistos Disc": range(66000, 66048), + "Lycian": range(66176, 66208), + "Carian": range(66208, 66272), + "Coptic Epact Numbers": range(66272, 66304), + "Old Italic": range(66304, 66352), + "Gothic": range(66352, 66384), + "Old Permic": range(66384, 66432), + "Ugaritic": range(66432, 66464), + "Old Persian": range(66464, 66528), + "Deseret": range(66560, 66640), + "Shavian": range(66640, 66688), + "Osmanya": range(66688, 66736), + "Osage": range(66736, 66816), + "Elbasan": range(66816, 66864), + "Caucasian Albanian": range(66864, 66928), + "Vithkuqi": range(66928, 67008), + "Linear A": range(67072, 67456), + "Latin Extended-F": range(67456, 67520), + "Cypriot Syllabary": range(67584, 67648), + "Imperial Aramaic": range(67648, 67680), + "Palmyrene": range(67680, 67712), + "Nabataean": range(67712, 67760), + "Hatran": range(67808, 67840), + "Phoenician": range(67840, 67872), + "Lydian": range(67872, 67904), + "Meroitic Hieroglyphs": range(67968, 68000), + "Meroitic Cursive": range(68000, 68096), + "Kharoshthi": range(68096, 68192), + "Old South Arabian": range(68192, 68224), + "Old North Arabian": range(68224, 68256), + "Manichaean": range(68288, 68352), + "Avestan": range(68352, 68416), + "Inscriptional Parthian": range(68416, 68448), + "Inscriptional Pahlavi": range(68448, 68480), + "Psalter Pahlavi": range(68480, 68528), + "Old Turkic": range(68608, 68688), + "Old Hungarian": range(68736, 68864), + "Hanifi Rohingya": range(68864, 68928), + "Rumi Numeral Symbols": range(69216, 69248), + "Yezidi": range(69248, 69312), + "Arabic Extended-C": range(69312, 69376), + "Old Sogdian": range(69376, 69424), + "Sogdian": range(69424, 69488), + "Old Uyghur": range(69488, 69552), + "Chorasmian": range(69552, 69600), + "Elymaic": range(69600, 69632), + "Brahmi": range(69632, 69760), + "Kaithi": range(69760, 69840), + "Sora Sompeng": range(69840, 69888), + "Chakma": range(69888, 69968), + "Mahajani": range(69968, 70016), + "Sharada": range(70016, 70112), + "Sinhala Archaic Numbers": range(70112, 70144), + "Khojki": range(70144, 70224), + "Multani": range(70272, 70320), + "Khudawadi": range(70320, 70400), + "Grantha": range(70400, 70528), + "Newa": range(70656, 70784), + "Tirhuta": range(70784, 70880), + "Siddham": range(71040, 71168), + "Modi": range(71168, 71264), + "Mongolian Supplement": range(71264, 71296), + "Takri": range(71296, 71376), + "Ahom": range(71424, 71504), + "Dogra": range(71680, 71760), + "Warang Citi": range(71840, 71936), + "Dives Akuru": range(71936, 72032), + "Nandinagari": range(72096, 72192), + "Zanabazar Square": range(72192, 72272), + "Soyombo": range(72272, 72368), + "Unified Canadian Aboriginal Syllabics Extended-A": range(72368, 72384), + "Pau Cin Hau": range(72384, 72448), + "Devanagari Extended-A": range(72448, 72544), + "Bhaiksuki": range(72704, 72816), + "Marchen": range(72816, 72896), + "Masaram Gondi": range(72960, 73056), + "Gunjala Gondi": range(73056, 73136), + "Makasar": range(73440, 73472), + "Kawi": range(73472, 73568), + "Lisu Supplement": range(73648, 73664), + "Tamil Supplement": range(73664, 73728), + "Cuneiform": range(73728, 74752), + "Cuneiform Numbers and Punctuation": range(74752, 74880), + "Early Dynastic Cuneiform": range(74880, 75088), + "Cypro-Minoan": range(77712, 77824), + "Egyptian Hieroglyphs": range(77824, 78896), + "Egyptian Hieroglyph Format Controls": range(78896, 78944), + "Anatolian Hieroglyphs": range(82944, 83584), + "Bamum Supplement": range(92160, 92736), + "Mro": range(92736, 92784), + "Tangsa": range(92784, 92880), + "Bassa Vah": range(92880, 92928), + "Pahawh Hmong": range(92928, 93072), + "Medefaidrin": range(93760, 93856), + "Miao": range(93952, 94112), + "Ideographic Symbols and Punctuation": range(94176, 94208), + "Tangut": range(94208, 100352), + "Tangut Components": range(100352, 101120), + "Khitan Small Script": range(101120, 101632), + "Tangut Supplement": range(101632, 101760), + "Kana Extended-B": range(110576, 110592), + "Kana Supplement": range(110592, 110848), + "Kana Extended-A": range(110848, 110896), + "Small Kana Extension": range(110896, 110960), + "Nushu": range(110960, 111360), + "Duployan": range(113664, 113824), + "Shorthand Format Controls": range(113824, 113840), + "Znamenny Musical Notation": range(118528, 118736), + "Byzantine Musical Symbols": range(118784, 119040), + "Musical Symbols": range(119040, 119296), + "Ancient Greek Musical Notation": range(119296, 119376), + "Kaktovik Numerals": range(119488, 119520), + "Mayan Numerals": range(119520, 119552), + "Tai Xuan Jing Symbols": range(119552, 119648), + "Counting Rod Numerals": range(119648, 119680), + "Mathematical Alphanumeric Symbols": range(119808, 120832), + "Sutton SignWriting": range(120832, 121520), + "Latin Extended-G": range(122624, 122880), + "Glagolitic Supplement": range(122880, 122928), + "Cyrillic Extended-D": range(122928, 123024), + "Nyiakeng Puachue Hmong": range(123136, 123216), + "Toto": range(123536, 123584), + "Wancho": range(123584, 123648), + "Nag Mundari": range(124112, 124160), + "Ethiopic Extended-B": range(124896, 124928), + "Mende Kikakui": range(124928, 125152), + "Adlam": range(125184, 125280), + "Indic Siyaq Numbers": range(126064, 126144), + "Ottoman Siyaq Numbers": range(126208, 126288), + "Arabic Mathematical Alphabetic Symbols": range(126464, 126720), + "Mahjong Tiles": range(126976, 127024), + "Domino Tiles": range(127024, 127136), + "Playing Cards": range(127136, 127232), + "Enclosed Alphanumeric Supplement": range(127232, 127488), + "Enclosed Ideographic Supplement": range(127488, 127744), + "Miscellaneous Symbols and Pictographs": range(127744, 128512), + "Emoticons range(Emoji)": range(128512, 128592), + "Ornamental Dingbats": range(128592, 128640), + "Transport and Map Symbols": range(128640, 128768), + "Alchemical Symbols": range(128768, 128896), + "Geometric Shapes Extended": range(128896, 129024), + "Supplemental Arrows-C": range(129024, 129280), + "Supplemental Symbols and Pictographs": range(129280, 129536), + "Chess Symbols": range(129536, 129648), + "Symbols and Pictographs Extended-A": range(129648, 129792), + "Symbols for Legacy Computing": range(129792, 130048), + "CJK Unified Ideographs Extension B": range(131072, 173792), + "CJK Unified Ideographs Extension C": range(173824, 177984), + "CJK Unified Ideographs Extension D": range(177984, 178208), + "CJK Unified Ideographs Extension E": range(178208, 183984), + "CJK Unified Ideographs Extension F": range(183984, 191472), + "CJK Compatibility Ideographs Supplement": range(194560, 195104), + "CJK Unified Ideographs Extension G": range(196608, 201552), + "CJK Unified Ideographs Extension H": range(201552, 205744), + "Tags": range(917504, 917632), + "Variation Selectors Supplement": range(917760, 918000), + "Supplementary Private Use Area-A": range(983040, 1048576), + "Supplementary Private Use Area-B": range(1048576, 1114112), +} + + +UNICODE_SECONDARY_RANGE_KEYWORD: list[str] = [ + "Supplement", + "Extended", + "Extensions", + "Modifier", + "Marks", + "Punctuation", + "Symbols", + "Forms", + "Operators", + "Miscellaneous", + "Drawing", + "Block", + "Shapes", + "Supplemental", + "Tags", +] + +RE_POSSIBLE_ENCODING_INDICATION = re_compile( + r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)", + IGNORECASE, +) + +IANA_NO_ALIASES = [ + "cp720", + "cp737", + "cp856", + "cp874", + "cp875", + "cp1006", + "koi8_r", + "koi8_t", + "koi8_u", +] + +IANA_SUPPORTED: list[str] = sorted( + filter( + lambda x: x.endswith("_codec") is False + and x not in {"rot_13", "tactis", "mbcs"}, + list(set(aliases.values())) + IANA_NO_ALIASES, + ) +) + +IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED) + +# pre-computed code page that are similar using the function cp_similarity. +IANA_SUPPORTED_SIMILAR: dict[str, list[str]] = { + "cp037": ["cp1026", "cp1140", "cp273", "cp500"], + "cp1026": ["cp037", "cp1140", "cp273", "cp500"], + "cp1125": ["cp866"], + "cp1140": ["cp037", "cp1026", "cp273", "cp500"], + "cp1250": ["iso8859_2"], + "cp1251": ["kz1048", "ptcp154"], + "cp1252": ["iso8859_15", "iso8859_9", "latin_1"], + "cp1253": ["iso8859_7"], + "cp1254": ["iso8859_15", "iso8859_9", "latin_1"], + "cp1257": ["iso8859_13"], + "cp273": ["cp037", "cp1026", "cp1140", "cp500"], + "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"], + "cp500": ["cp037", "cp1026", "cp1140", "cp273"], + "cp850": ["cp437", "cp857", "cp858", "cp865"], + "cp857": ["cp850", "cp858", "cp865"], + "cp858": ["cp437", "cp850", "cp857", "cp865"], + "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"], + "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"], + "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"], + "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"], + "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"], + "cp866": ["cp1125"], + "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"], + "iso8859_11": ["tis_620"], + "iso8859_13": ["cp1257"], + "iso8859_14": [ + "iso8859_10", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_15": [ + "cp1252", + "cp1254", + "iso8859_10", + "iso8859_14", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_16": [ + "iso8859_14", + "iso8859_15", + "iso8859_2", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"], + "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"], + "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"], + "iso8859_7": ["cp1253"], + "iso8859_9": [ + "cp1252", + "cp1254", + "cp1258", + "iso8859_10", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_4", + "latin_1", + ], + "kz1048": ["cp1251", "ptcp154"], + "latin_1": [ + "cp1252", + "cp1254", + "cp1258", + "iso8859_10", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_4", + "iso8859_9", + ], + "mac_iceland": ["mac_roman", "mac_turkish"], + "mac_roman": ["mac_iceland", "mac_turkish"], + "mac_turkish": ["mac_iceland", "mac_roman"], + "ptcp154": ["cp1251", "kz1048"], + "tis_620": ["iso8859_11"], +} + + +CHARDET_CORRESPONDENCE: dict[str, str] = { + "iso2022_kr": "ISO-2022-KR", + "iso2022_jp": "ISO-2022-JP", + "euc_kr": "EUC-KR", + "tis_620": "TIS-620", + "utf_32": "UTF-32", + "euc_jp": "EUC-JP", + "koi8_r": "KOI8-R", + "iso8859_1": "ISO-8859-1", + "iso8859_2": "ISO-8859-2", + "iso8859_5": "ISO-8859-5", + "iso8859_6": "ISO-8859-6", + "iso8859_7": "ISO-8859-7", + "iso8859_8": "ISO-8859-8", + "utf_16": "UTF-16", + "cp855": "IBM855", + "mac_cyrillic": "MacCyrillic", + "gb2312": "GB2312", + "gb18030": "GB18030", + "cp932": "CP932", + "cp866": "IBM866", + "utf_8": "utf-8", + "utf_8_sig": "UTF-8-SIG", + "shift_jis": "SHIFT_JIS", + "big5": "Big5", + "cp1250": "windows-1250", + "cp1251": "windows-1251", + "cp1252": "Windows-1252", + "cp1253": "windows-1253", + "cp1255": "windows-1255", + "cp1256": "windows-1256", + "cp1254": "Windows-1254", + "cp949": "CP949", +} + + +COMMON_SAFE_ASCII_CHARACTERS: set[str] = { + "<", + ">", + "=", + ":", + "/", + "&", + ";", + "{", + "}", + "[", + "]", + ",", + "|", + '"', + "-", + "(", + ")", +} + +# Sample character sets — replace with full lists if needed +COMMON_CHINESE_CHARACTERS = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严龙飞" + +COMMON_JAPANESE_CHARACTERS = "日一国年大十二本中長出三時行見月分後前生五間上東四今金九入学高円子外八六下来気小七山話女北午百書先名川千水半男西電校語土木聞食車何南万毎白天母火右読友左休父雨" + +COMMON_KOREAN_CHARACTERS = "一二三四五六七八九十百千萬上下左右中人女子大小山川日月火水木金土父母天地國名年時文校學生" + +# Combine all into a set +COMMON_CJK_CHARACTERS = set( + "".join( + [ + COMMON_CHINESE_CHARACTERS, + COMMON_JAPANESE_CHARACTERS, + COMMON_KOREAN_CHARACTERS, + ] + ) +) + +KO_NAMES: set[str] = {"johab", "cp949", "euc_kr"} +ZH_NAMES: set[str] = {"big5", "cp950", "big5hkscs", "hz"} + +# Logging LEVEL below DEBUG +TRACE: int = 5 + + +# Language label that contain the em dash "—" +# character are to be considered alternative seq to origin +FREQUENCIES: dict[str, list[str]] = { + "English": [ + "e", + "a", + "t", + "i", + "o", + "n", + "s", + "r", + "h", + "l", + "d", + "c", + "u", + "m", + "f", + "p", + "g", + "w", + "y", + "b", + "v", + "k", + "x", + "j", + "z", + "q", + ], + "English—": [ + "e", + "a", + "t", + "i", + "o", + "n", + "s", + "r", + "h", + "l", + "d", + "c", + "m", + "u", + "f", + "p", + "g", + "w", + "b", + "y", + "v", + "k", + "j", + "x", + "z", + "q", + ], + "German": [ + "e", + "n", + "i", + "r", + "s", + "t", + "a", + "d", + "h", + "u", + "l", + "g", + "o", + "c", + "m", + "b", + "f", + "k", + "w", + "z", + "p", + "v", + "ü", + "ä", + "ö", + "j", + ], + "French": [ + "e", + "a", + "s", + "n", + "i", + "t", + "r", + "l", + "u", + "o", + "d", + "c", + "p", + "m", + "é", + "v", + "g", + "f", + "b", + "h", + "q", + "à", + "x", + "è", + "y", + "j", + ], + "Dutch": [ + "e", + "n", + "a", + "i", + "r", + "t", + "o", + "d", + "s", + "l", + "g", + "h", + "v", + "m", + "u", + "k", + "c", + "p", + "b", + "w", + "j", + "z", + "f", + "y", + "x", + "ë", + ], + "Italian": [ + "e", + "i", + "a", + "o", + "n", + "l", + "t", + "r", + "s", + "c", + "d", + "u", + "p", + "m", + "g", + "v", + "f", + "b", + "z", + "h", + "q", + "è", + "à", + "k", + "y", + "ò", + ], + "Polish": [ + "a", + "i", + "o", + "e", + "n", + "r", + "z", + "w", + "s", + "c", + "t", + "k", + "y", + "d", + "p", + "m", + "u", + "l", + "j", + "ł", + "g", + "b", + "h", + "ą", + "ę", + "ó", + ], + "Spanish": [ + "e", + "a", + "o", + "n", + "s", + "r", + "i", + "l", + "d", + "t", + "c", + "u", + "m", + "p", + "b", + "g", + "v", + "f", + "y", + "ó", + "h", + "q", + "í", + "j", + "z", + "á", + ], + "Russian": [ + "о", + "а", + "е", + "и", + "н", + "с", + "т", + "р", + "в", + "л", + "к", + "м", + "д", + "п", + "у", + "г", + "я", + "ы", + "з", + "б", + "й", + "ь", + "ч", + "х", + "ж", + "ц", + ], + # Jap-Kanji + "Japanese": [ + "人", + "一", + "大", + "亅", + "丁", + "丨", + "竹", + "笑", + "口", + "日", + "今", + "二", + "彳", + "行", + "十", + "土", + "丶", + "寸", + "寺", + "時", + "乙", + "丿", + "乂", + "气", + "気", + "冂", + "巾", + "亠", + "市", + "目", + "儿", + "見", + "八", + "小", + "凵", + "県", + "月", + "彐", + "門", + "間", + "木", + "東", + "山", + "出", + "本", + "中", + "刀", + "分", + "耳", + "又", + "取", + "最", + "言", + "田", + "心", + "思", + "刂", + "前", + "京", + "尹", + "事", + "生", + "厶", + "云", + "会", + "未", + "来", + "白", + "冫", + "楽", + "灬", + "馬", + "尸", + "尺", + "駅", + "明", + "耂", + "者", + "了", + "阝", + "都", + "高", + "卜", + "占", + "厂", + "广", + "店", + "子", + "申", + "奄", + "亻", + "俺", + "上", + "方", + "冖", + "学", + "衣", + "艮", + "食", + "自", + ], + # Jap-Katakana + "Japanese—": [ + "ー", + "ン", + "ス", + "・", + "ル", + "ト", + "リ", + "イ", + "ア", + "ラ", + "ッ", + "ク", + "ド", + "シ", + "レ", + "ジ", + "タ", + "フ", + "ロ", + "カ", + "テ", + "マ", + "ィ", + "グ", + "バ", + "ム", + "プ", + "オ", + "コ", + "デ", + "ニ", + "ウ", + "メ", + "サ", + "ビ", + "ナ", + "ブ", + "ャ", + "エ", + "ュ", + "チ", + "キ", + "ズ", + "ダ", + "パ", + "ミ", + "ェ", + "ョ", + "ハ", + "セ", + "ベ", + "ガ", + "モ", + "ツ", + "ネ", + "ボ", + "ソ", + "ノ", + "ァ", + "ヴ", + "ワ", + "ポ", + "ペ", + "ピ", + "ケ", + "ゴ", + "ギ", + "ザ", + "ホ", + "ゲ", + "ォ", + "ヤ", + "ヒ", + "ユ", + "ヨ", + "ヘ", + "ゼ", + "ヌ", + "ゥ", + "ゾ", + "ヶ", + "ヂ", + "ヲ", + "ヅ", + "ヵ", + "ヱ", + "ヰ", + "ヮ", + "ヽ", + "゠", + "ヾ", + "ヷ", + "ヿ", + "ヸ", + "ヹ", + "ヺ", + ], + # Jap-Hiragana + "Japanese——": [ + "の", + "に", + "る", + "た", + "と", + "は", + "し", + "い", + "を", + "で", + "て", + "が", + "な", + "れ", + "か", + "ら", + "さ", + "っ", + "り", + "す", + "あ", + "も", + "こ", + "ま", + "う", + "く", + "よ", + "き", + "ん", + "め", + "お", + "け", + "そ", + "つ", + "だ", + "や", + "え", + "ど", + "わ", + "ち", + "み", + "せ", + "じ", + "ば", + "へ", + "び", + "ず", + "ろ", + "ほ", + "げ", + "む", + "べ", + "ひ", + "ょ", + "ゆ", + "ぶ", + "ご", + "ゃ", + "ね", + "ふ", + "ぐ", + "ぎ", + "ぼ", + "ゅ", + "づ", + "ざ", + "ぞ", + "ぬ", + "ぜ", + "ぱ", + "ぽ", + "ぷ", + "ぴ", + "ぃ", + "ぁ", + "ぇ", + "ぺ", + "ゞ", + "ぢ", + "ぉ", + "ぅ", + "ゐ", + "ゝ", + "ゑ", + "゛", + "゜", + "ゎ", + "ゔ", + "゚", + "ゟ", + "゙", + "ゕ", + "ゖ", + ], + "Portuguese": [ + "a", + "e", + "o", + "s", + "i", + "r", + "d", + "n", + "t", + "m", + "u", + "c", + "l", + "p", + "g", + "v", + "b", + "f", + "h", + "ã", + "q", + "é", + "ç", + "á", + "z", + "í", + ], + "Swedish": [ + "e", + "a", + "n", + "r", + "t", + "s", + "i", + "l", + "d", + "o", + "m", + "k", + "g", + "v", + "h", + "f", + "u", + "p", + "ä", + "c", + "b", + "ö", + "å", + "y", + "j", + "x", + ], + "Chinese": [ + "的", + "一", + "是", + "不", + "了", + "在", + "人", + "有", + "我", + "他", + "这", + "个", + "们", + "中", + "来", + "上", + "大", + "为", + "和", + "国", + "地", + "到", + "以", + "说", + "时", + "要", + "就", + "出", + "会", + "可", + "也", + "你", + "对", + "生", + "能", + "而", + "子", + "那", + "得", + "于", + "着", + "下", + "自", + "之", + "年", + "过", + "发", + "后", + "作", + "里", + "用", + "道", + "行", + "所", + "然", + "家", + "种", + "事", + "成", + "方", + "多", + "经", + "么", + "去", + "法", + "学", + "如", + "都", + "同", + "现", + "当", + "没", + "动", + "面", + "起", + "看", + "定", + "天", + "分", + "还", + "进", + "好", + "小", + "部", + "其", + "些", + "主", + "样", + "理", + "心", + "她", + "本", + "前", + "开", + "但", + "因", + "只", + "从", + "想", + "实", + ], + "Ukrainian": [ + "о", + "а", + "н", + "і", + "и", + "р", + "в", + "т", + "е", + "с", + "к", + "л", + "у", + "д", + "м", + "п", + "з", + "я", + "ь", + "б", + "г", + "й", + "ч", + "х", + "ц", + "ї", + ], + "Norwegian": [ + "e", + "r", + "n", + "t", + "a", + "s", + "i", + "o", + "l", + "d", + "g", + "k", + "m", + "v", + "f", + "p", + "u", + "b", + "h", + "å", + "y", + "j", + "ø", + "c", + "æ", + "w", + ], + "Finnish": [ + "a", + "i", + "n", + "t", + "e", + "s", + "l", + "o", + "u", + "k", + "ä", + "m", + "r", + "v", + "j", + "h", + "p", + "y", + "d", + "ö", + "g", + "c", + "b", + "f", + "w", + "z", + ], + "Vietnamese": [ + "n", + "h", + "t", + "i", + "c", + "g", + "a", + "o", + "u", + "m", + "l", + "r", + "à", + "đ", + "s", + "e", + "v", + "p", + "b", + "y", + "ư", + "d", + "á", + "k", + "ộ", + "ế", + ], + "Czech": [ + "o", + "e", + "a", + "n", + "t", + "s", + "i", + "l", + "v", + "r", + "k", + "d", + "u", + "m", + "p", + "í", + "c", + "h", + "z", + "á", + "y", + "j", + "b", + "ě", + "é", + "ř", + ], + "Hungarian": [ + "e", + "a", + "t", + "l", + "s", + "n", + "k", + "r", + "i", + "o", + "z", + "á", + "é", + "g", + "m", + "b", + "y", + "v", + "d", + "h", + "u", + "p", + "j", + "ö", + "f", + "c", + ], + "Korean": [ + "이", + "다", + "에", + "의", + "는", + "로", + "하", + "을", + "가", + "고", + "지", + "서", + "한", + "은", + "기", + "으", + "년", + "대", + "사", + "시", + "를", + "리", + "도", + "인", + "스", + "일", + ], + "Indonesian": [ + "a", + "n", + "e", + "i", + "r", + "t", + "u", + "s", + "d", + "k", + "m", + "l", + "g", + "p", + "b", + "o", + "h", + "y", + "j", + "c", + "w", + "f", + "v", + "z", + "x", + "q", + ], + "Turkish": [ + "a", + "e", + "i", + "n", + "r", + "l", + "ı", + "k", + "d", + "t", + "s", + "m", + "y", + "u", + "o", + "b", + "ü", + "ş", + "v", + "g", + "z", + "h", + "c", + "p", + "ç", + "ğ", + ], + "Romanian": [ + "e", + "i", + "a", + "r", + "n", + "t", + "u", + "l", + "o", + "c", + "s", + "d", + "p", + "m", + "ă", + "f", + "v", + "î", + "g", + "b", + "ș", + "ț", + "z", + "h", + "â", + "j", + ], + "Farsi": [ + "ا", + "ی", + "ر", + "د", + "ن", + "ه", + "و", + "م", + "ت", + "ب", + "س", + "ل", + "ک", + "ش", + "ز", + "ف", + "گ", + "ع", + "خ", + "ق", + "ج", + "آ", + "پ", + "ح", + "ط", + "ص", + ], + "Arabic": [ + "ا", + "ل", + "ي", + "م", + "و", + "ن", + "ر", + "ت", + "ب", + "ة", + "ع", + "د", + "س", + "ف", + "ه", + "ك", + "ق", + "أ", + "ح", + "ج", + "ش", + "ط", + "ص", + "ى", + "خ", + "إ", + ], + "Danish": [ + "e", + "r", + "n", + "t", + "a", + "i", + "s", + "d", + "l", + "o", + "g", + "m", + "k", + "f", + "v", + "u", + "b", + "h", + "p", + "å", + "y", + "ø", + "æ", + "c", + "j", + "w", + ], + "Serbian": [ + "а", + "и", + "о", + "е", + "н", + "р", + "с", + "у", + "т", + "к", + "ј", + "в", + "д", + "м", + "п", + "л", + "г", + "з", + "б", + "a", + "i", + "e", + "o", + "n", + "ц", + "ш", + ], + "Lithuanian": [ + "i", + "a", + "s", + "o", + "r", + "e", + "t", + "n", + "u", + "k", + "m", + "l", + "p", + "v", + "d", + "j", + "g", + "ė", + "b", + "y", + "ų", + "š", + "ž", + "c", + "ą", + "į", + ], + "Slovene": [ + "e", + "a", + "i", + "o", + "n", + "r", + "s", + "l", + "t", + "j", + "v", + "k", + "d", + "p", + "m", + "u", + "z", + "b", + "g", + "h", + "č", + "c", + "š", + "ž", + "f", + "y", + ], + "Slovak": [ + "o", + "a", + "e", + "n", + "i", + "r", + "v", + "t", + "s", + "l", + "k", + "d", + "m", + "p", + "u", + "c", + "h", + "j", + "b", + "z", + "á", + "y", + "ý", + "í", + "č", + "é", + ], + "Hebrew": [ + "י", + "ו", + "ה", + "ל", + "ר", + "ב", + "ת", + "מ", + "א", + "ש", + "נ", + "ע", + "ם", + "ד", + "ק", + "ח", + "פ", + "ס", + "כ", + "ג", + "ט", + "צ", + "ן", + "ז", + "ך", + ], + "Bulgarian": [ + "а", + "и", + "о", + "е", + "н", + "т", + "р", + "с", + "в", + "л", + "к", + "д", + "п", + "м", + "з", + "г", + "я", + "ъ", + "у", + "б", + "ч", + "ц", + "й", + "ж", + "щ", + "х", + ], + "Croatian": [ + "a", + "i", + "o", + "e", + "n", + "r", + "j", + "s", + "t", + "u", + "k", + "l", + "v", + "d", + "m", + "p", + "g", + "z", + "b", + "c", + "č", + "h", + "š", + "ž", + "ć", + "f", + ], + "Hindi": [ + "क", + "र", + "स", + "न", + "त", + "म", + "ह", + "प", + "य", + "ल", + "व", + "ज", + "द", + "ग", + "ब", + "श", + "ट", + "अ", + "ए", + "थ", + "भ", + "ड", + "च", + "ध", + "ष", + "इ", + ], + "Estonian": [ + "a", + "i", + "e", + "s", + "t", + "l", + "u", + "n", + "o", + "k", + "r", + "d", + "m", + "v", + "g", + "p", + "j", + "h", + "ä", + "b", + "õ", + "ü", + "f", + "c", + "ö", + "y", + ], + "Thai": [ + "า", + "น", + "ร", + "อ", + "ก", + "เ", + "ง", + "ม", + "ย", + "ล", + "ว", + "ด", + "ท", + "ส", + "ต", + "ะ", + "ป", + "บ", + "ค", + "ห", + "แ", + "จ", + "พ", + "ช", + "ข", + "ใ", + ], + "Greek": [ + "α", + "τ", + "ο", + "ι", + "ε", + "ν", + "ρ", + "σ", + "κ", + "η", + "π", + "ς", + "υ", + "μ", + "λ", + "ί", + "ό", + "ά", + "γ", + "έ", + "δ", + "ή", + "ω", + "χ", + "θ", + "ύ", + ], + "Tamil": [ + "க", + "த", + "ப", + "ட", + "ர", + "ம", + "ல", + "ன", + "வ", + "ற", + "ய", + "ள", + "ச", + "ந", + "இ", + "ண", + "அ", + "ஆ", + "ழ", + "ங", + "எ", + "உ", + "ஒ", + "ஸ", + ], + "Kazakh": [ + "а", + "ы", + "е", + "н", + "т", + "р", + "л", + "і", + "д", + "с", + "м", + "қ", + "к", + "о", + "б", + "и", + "у", + "ғ", + "ж", + "ң", + "з", + "ш", + "й", + "п", + "г", + "ө", + ], +} + +LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES) diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/legacy.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..360a3107bdce817594db33de158e71d9fe793a3b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/legacy.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from warnings import warn + +from .api import from_bytes +from .constant import CHARDET_CORRESPONDENCE, TOO_SMALL_SEQUENCE + +# TODO: remove this check when dropping Python 3.7 support +if TYPE_CHECKING: + from typing_extensions import TypedDict + + class ResultDict(TypedDict): + encoding: str | None + language: str + confidence: float | None + + +def detect( + byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any +) -> ResultDict: + """ + chardet legacy method + Detect the encoding of the given byte string. It should be mostly backward-compatible. + Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it) + This function is deprecated and should be used to migrate your project easily, consult the documentation for + further information. Not planned for removal. + + :param byte_str: The byte sequence to examine. + :param should_rename_legacy: Should we rename legacy encodings + to their more modern equivalents? + """ + if len(kwargs): + warn( + f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()" + ) + + if not isinstance(byte_str, (bytearray, bytes)): + raise TypeError( # pragma: nocover + f"Expected object of type bytes or bytearray, got: {type(byte_str)}" + ) + + if isinstance(byte_str, bytearray): + byte_str = bytes(byte_str) + + r = from_bytes(byte_str).best() + + encoding = r.encoding if r is not None else None + language = r.language if r is not None and r.language != "Unknown" else "" + confidence = 1.0 - r.chaos if r is not None else None + + # automatically lower confidence + # on small bytes samples. + # https://github.com/jawah/charset_normalizer/issues/391 + if ( + confidence is not None + and confidence >= 0.9 + and encoding + not in { + "utf_8", + "ascii", + } + and r.bom is False # type: ignore[union-attr] + and len(byte_str) < TOO_SMALL_SEQUENCE + ): + confidence -= 0.2 + + # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process + # but chardet does return 'utf-8-sig' and it is a valid codec name. + if r is not None and encoding == "utf_8" and r.bom: + encoding += "_sig" + + if should_rename_legacy is False and encoding in CHARDET_CORRESPONDENCE: + encoding = CHARDET_CORRESPONDENCE[encoding] + + return { + "encoding": encoding, + "language": language, + "confidence": confidence, + } diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/md.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/md.py new file mode 100644 index 0000000000000000000000000000000000000000..12ce024bd34c7eee369ddf438f5534e855a59839 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/md.py @@ -0,0 +1,635 @@ +from __future__ import annotations + +from functools import lru_cache +from logging import getLogger + +from .constant import ( + COMMON_SAFE_ASCII_CHARACTERS, + TRACE, + UNICODE_SECONDARY_RANGE_KEYWORD, +) +from .utils import ( + is_accentuated, + is_arabic, + is_arabic_isolated_form, + is_case_variable, + is_cjk, + is_emoticon, + is_hangul, + is_hiragana, + is_katakana, + is_latin, + is_punctuation, + is_separator, + is_symbol, + is_thai, + is_unprintable, + remove_accent, + unicode_range, + is_cjk_uncommon, +) + + +class MessDetectorPlugin: + """ + Base abstract class used for mess detection plugins. + All detectors MUST extend and implement given methods. + """ + + def eligible(self, character: str) -> bool: + """ + Determine if given character should be fed in. + """ + raise NotImplementedError # pragma: nocover + + def feed(self, character: str) -> None: + """ + The main routine to be executed upon character. + Insert the logic in witch the text would be considered chaotic. + """ + raise NotImplementedError # pragma: nocover + + def reset(self) -> None: # pragma: no cover + """ + Permit to reset the plugin to the initial state. + """ + raise NotImplementedError + + @property + def ratio(self) -> float: + """ + Compute the chaos ratio based on what your feed() has seen. + Must NOT be lower than 0.; No restriction gt 0. + """ + raise NotImplementedError # pragma: nocover + + +class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._punctuation_count: int = 0 + self._symbol_count: int = 0 + self._character_count: int = 0 + + self._last_printable_char: str | None = None + self._frenzy_symbol_in_word: bool = False + + def eligible(self, character: str) -> bool: + return character.isprintable() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if ( + character != self._last_printable_char + and character not in COMMON_SAFE_ASCII_CHARACTERS + ): + if is_punctuation(character): + self._punctuation_count += 1 + elif ( + character.isdigit() is False + and is_symbol(character) + and is_emoticon(character) is False + ): + self._symbol_count += 2 + + self._last_printable_char = character + + def reset(self) -> None: # Abstract + self._punctuation_count = 0 + self._character_count = 0 + self._symbol_count = 0 + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + ratio_of_punctuation: float = ( + self._punctuation_count + self._symbol_count + ) / self._character_count + + return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0 + + +class TooManyAccentuatedPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._character_count: int = 0 + self._accentuated_count: int = 0 + + def eligible(self, character: str) -> bool: + return character.isalpha() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_accentuated(character): + self._accentuated_count += 1 + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._accentuated_count = 0 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + ratio_of_accentuation: float = self._accentuated_count / self._character_count + return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0 + + +class UnprintablePlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._unprintable_count: int = 0 + self._character_count: int = 0 + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + if is_unprintable(character): + self._unprintable_count += 1 + self._character_count += 1 + + def reset(self) -> None: # Abstract + self._unprintable_count = 0 + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return (self._unprintable_count * 8) / self._character_count + + +class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._successive_count: int = 0 + self._character_count: int = 0 + + self._last_latin_character: str | None = None + + def eligible(self, character: str) -> bool: + return character.isalpha() and is_latin(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + if ( + self._last_latin_character is not None + and is_accentuated(character) + and is_accentuated(self._last_latin_character) + ): + if character.isupper() and self._last_latin_character.isupper(): + self._successive_count += 1 + # Worse if its the same char duplicated with different accent. + if remove_accent(character) == remove_accent(self._last_latin_character): + self._successive_count += 1 + self._last_latin_character = character + + def reset(self) -> None: # Abstract + self._successive_count = 0 + self._character_count = 0 + self._last_latin_character = None + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return (self._successive_count * 2) / self._character_count + + +class SuspiciousRange(MessDetectorPlugin): + def __init__(self) -> None: + self._suspicious_successive_range_count: int = 0 + self._character_count: int = 0 + self._last_printable_seen: str | None = None + + def eligible(self, character: str) -> bool: + return character.isprintable() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if ( + character.isspace() + or is_punctuation(character) + or character in COMMON_SAFE_ASCII_CHARACTERS + ): + self._last_printable_seen = None + return + + if self._last_printable_seen is None: + self._last_printable_seen = character + return + + unicode_range_a: str | None = unicode_range(self._last_printable_seen) + unicode_range_b: str | None = unicode_range(character) + + if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): + self._suspicious_successive_range_count += 1 + + self._last_printable_seen = character + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._suspicious_successive_range_count = 0 + self._last_printable_seen = None + + @property + def ratio(self) -> float: + if self._character_count <= 13: + return 0.0 + + ratio_of_suspicious_range_usage: float = ( + self._suspicious_successive_range_count * 2 + ) / self._character_count + + return ratio_of_suspicious_range_usage + + +class SuperWeirdWordPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._word_count: int = 0 + self._bad_word_count: int = 0 + self._foreign_long_count: int = 0 + + self._is_current_word_bad: bool = False + self._foreign_long_watch: bool = False + + self._character_count: int = 0 + self._bad_character_count: int = 0 + + self._buffer: str = "" + self._buffer_accent_count: int = 0 + self._buffer_glyph_count: int = 0 + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + if character.isalpha(): + self._buffer += character + if is_accentuated(character): + self._buffer_accent_count += 1 + if ( + self._foreign_long_watch is False + and (is_latin(character) is False or is_accentuated(character)) + and is_cjk(character) is False + and is_hangul(character) is False + and is_katakana(character) is False + and is_hiragana(character) is False + and is_thai(character) is False + ): + self._foreign_long_watch = True + if ( + is_cjk(character) + or is_hangul(character) + or is_katakana(character) + or is_hiragana(character) + or is_thai(character) + ): + self._buffer_glyph_count += 1 + return + if not self._buffer: + return + if ( + character.isspace() or is_punctuation(character) or is_separator(character) + ) and self._buffer: + self._word_count += 1 + buffer_length: int = len(self._buffer) + + self._character_count += buffer_length + + if buffer_length >= 4: + if self._buffer_accent_count / buffer_length >= 0.5: + self._is_current_word_bad = True + # Word/Buffer ending with an upper case accentuated letter are so rare, + # that we will consider them all as suspicious. Same weight as foreign_long suspicious. + elif ( + is_accentuated(self._buffer[-1]) + and self._buffer[-1].isupper() + and all(_.isupper() for _ in self._buffer) is False + ): + self._foreign_long_count += 1 + self._is_current_word_bad = True + elif self._buffer_glyph_count == 1: + self._is_current_word_bad = True + self._foreign_long_count += 1 + if buffer_length >= 24 and self._foreign_long_watch: + camel_case_dst = [ + i + for c, i in zip(self._buffer, range(0, buffer_length)) + if c.isupper() + ] + probable_camel_cased: bool = False + + if camel_case_dst and (len(camel_case_dst) / buffer_length <= 0.3): + probable_camel_cased = True + + if not probable_camel_cased: + self._foreign_long_count += 1 + self._is_current_word_bad = True + + if self._is_current_word_bad: + self._bad_word_count += 1 + self._bad_character_count += len(self._buffer) + self._is_current_word_bad = False + + self._foreign_long_watch = False + self._buffer = "" + self._buffer_accent_count = 0 + self._buffer_glyph_count = 0 + elif ( + character not in {"<", ">", "-", "=", "~", "|", "_"} + and character.isdigit() is False + and is_symbol(character) + ): + self._is_current_word_bad = True + self._buffer += character + + def reset(self) -> None: # Abstract + self._buffer = "" + self._is_current_word_bad = False + self._foreign_long_watch = False + self._bad_word_count = 0 + self._word_count = 0 + self._character_count = 0 + self._bad_character_count = 0 + self._foreign_long_count = 0 + + @property + def ratio(self) -> float: + if self._word_count <= 10 and self._foreign_long_count == 0: + return 0.0 + + return self._bad_character_count / self._character_count + + +class CjkUncommonPlugin(MessDetectorPlugin): + """ + Detect messy CJK text that probably means nothing. + """ + + def __init__(self) -> None: + self._character_count: int = 0 + self._uncommon_count: int = 0 + + def eligible(self, character: str) -> bool: + return is_cjk(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_cjk_uncommon(character): + self._uncommon_count += 1 + return + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._uncommon_count = 0 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + uncommon_form_usage: float = self._uncommon_count / self._character_count + + # we can be pretty sure it's garbage when uncommon characters are widely + # used. otherwise it could just be traditional chinese for example. + return uncommon_form_usage / 10 if uncommon_form_usage > 0.5 else 0.0 + + +class ArchaicUpperLowerPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._buf: bool = False + + self._character_count_since_last_sep: int = 0 + + self._successive_upper_lower_count: int = 0 + self._successive_upper_lower_count_final: int = 0 + + self._character_count: int = 0 + + self._last_alpha_seen: str | None = None + self._current_ascii_only: bool = True + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + is_concerned = character.isalpha() and is_case_variable(character) + chunk_sep = is_concerned is False + + if chunk_sep and self._character_count_since_last_sep > 0: + if ( + self._character_count_since_last_sep <= 64 + and character.isdigit() is False + and self._current_ascii_only is False + ): + self._successive_upper_lower_count_final += ( + self._successive_upper_lower_count + ) + + self._successive_upper_lower_count = 0 + self._character_count_since_last_sep = 0 + self._last_alpha_seen = None + self._buf = False + self._character_count += 1 + self._current_ascii_only = True + + return + + if self._current_ascii_only is True and character.isascii() is False: + self._current_ascii_only = False + + if self._last_alpha_seen is not None: + if (character.isupper() and self._last_alpha_seen.islower()) or ( + character.islower() and self._last_alpha_seen.isupper() + ): + if self._buf is True: + self._successive_upper_lower_count += 2 + self._buf = False + else: + self._buf = True + else: + self._buf = False + + self._character_count += 1 + self._character_count_since_last_sep += 1 + self._last_alpha_seen = character + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._character_count_since_last_sep = 0 + self._successive_upper_lower_count = 0 + self._successive_upper_lower_count_final = 0 + self._last_alpha_seen = None + self._buf = False + self._current_ascii_only = True + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return self._successive_upper_lower_count_final / self._character_count + + +class ArabicIsolatedFormPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._character_count: int = 0 + self._isolated_form_count: int = 0 + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._isolated_form_count = 0 + + def eligible(self, character: str) -> bool: + return is_arabic(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_arabic_isolated_form(character): + self._isolated_form_count += 1 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + isolated_form_usage: float = self._isolated_form_count / self._character_count + + return isolated_form_usage + + +@lru_cache(maxsize=1024) +def is_suspiciously_successive_range( + unicode_range_a: str | None, unicode_range_b: str | None +) -> bool: + """ + Determine if two Unicode range seen next to each other can be considered as suspicious. + """ + if unicode_range_a is None or unicode_range_b is None: + return True + + if unicode_range_a == unicode_range_b: + return False + + if "Latin" in unicode_range_a and "Latin" in unicode_range_b: + return False + + if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b: + return False + + # Latin characters can be accompanied with a combining diacritical mark + # eg. Vietnamese. + if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and ( + "Combining" in unicode_range_a or "Combining" in unicode_range_b + ): + return False + + keywords_range_a, keywords_range_b = ( + unicode_range_a.split(" "), + unicode_range_b.split(" "), + ) + + for el in keywords_range_a: + if el in UNICODE_SECONDARY_RANGE_KEYWORD: + continue + if el in keywords_range_b: + return False + + # Japanese Exception + range_a_jp_chars, range_b_jp_chars = ( + unicode_range_a + in ( + "Hiragana", + "Katakana", + ), + unicode_range_b in ("Hiragana", "Katakana"), + ) + if (range_a_jp_chars or range_b_jp_chars) and ( + "CJK" in unicode_range_a or "CJK" in unicode_range_b + ): + return False + if range_a_jp_chars and range_b_jp_chars: + return False + + if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b: + if "CJK" in unicode_range_a or "CJK" in unicode_range_b: + return False + if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": + return False + + # Chinese/Japanese use dedicated range for punctuation and/or separators. + if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or ( + unicode_range_a in ["Katakana", "Hiragana"] + and unicode_range_b in ["Katakana", "Hiragana"] + ): + if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b: + return False + if "Forms" in unicode_range_a or "Forms" in unicode_range_b: + return False + if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": + return False + + return True + + +@lru_cache(maxsize=2048) +def mess_ratio( + decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False +) -> float: + """ + Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. + """ + + detectors: list[MessDetectorPlugin] = [ + md_class() for md_class in MessDetectorPlugin.__subclasses__() + ] + + length: int = len(decoded_sequence) + 1 + + mean_mess_ratio: float = 0.0 + + if length < 512: + intermediary_mean_mess_ratio_calc: int = 32 + elif length <= 1024: + intermediary_mean_mess_ratio_calc = 64 + else: + intermediary_mean_mess_ratio_calc = 128 + + for character, index in zip(decoded_sequence + "\n", range(length)): + for detector in detectors: + if detector.eligible(character): + detector.feed(character) + + if ( + index > 0 and index % intermediary_mean_mess_ratio_calc == 0 + ) or index == length - 1: + mean_mess_ratio = sum(dt.ratio for dt in detectors) + + if mean_mess_ratio >= maximum_threshold: + break + + if debug: + logger = getLogger("charset_normalizer") + + logger.log( + TRACE, + "Mess-detector extended-analysis start. " + f"intermediary_mean_mess_ratio_calc={intermediary_mean_mess_ratio_calc} mean_mess_ratio={mean_mess_ratio} " + f"maximum_threshold={maximum_threshold}", + ) + + if len(decoded_sequence) > 16: + logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}") + logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}") + + for dt in detectors: + logger.log(TRACE, f"{dt.__class__}: {dt.ratio}") + + return round(mean_mess_ratio, 3) diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/models.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/models.py new file mode 100644 index 0000000000000000000000000000000000000000..1042758f873d2a54f7078c5411b17ffc11dca4ee --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/models.py @@ -0,0 +1,360 @@ +from __future__ import annotations + +from encodings.aliases import aliases +from hashlib import sha256 +from json import dumps +from re import sub +from typing import Any, Iterator, List, Tuple + +from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE +from .utils import iana_name, is_multi_byte_encoding, unicode_range + + +class CharsetMatch: + def __init__( + self, + payload: bytes, + guessed_encoding: str, + mean_mess_ratio: float, + has_sig_or_bom: bool, + languages: CoherenceMatches, + decoded_payload: str | None = None, + preemptive_declaration: str | None = None, + ): + self._payload: bytes = payload + + self._encoding: str = guessed_encoding + self._mean_mess_ratio: float = mean_mess_ratio + self._languages: CoherenceMatches = languages + self._has_sig_or_bom: bool = has_sig_or_bom + self._unicode_ranges: list[str] | None = None + + self._leaves: list[CharsetMatch] = [] + self._mean_coherence_ratio: float = 0.0 + + self._output_payload: bytes | None = None + self._output_encoding: str | None = None + + self._string: str | None = decoded_payload + + self._preemptive_declaration: str | None = preemptive_declaration + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CharsetMatch): + if isinstance(other, str): + return iana_name(other) == self.encoding + return False + return self.encoding == other.encoding and self.fingerprint == other.fingerprint + + def __lt__(self, other: object) -> bool: + """ + Implemented to make sorted available upon CharsetMatches items. + """ + if not isinstance(other, CharsetMatch): + raise ValueError + + chaos_difference: float = abs(self.chaos - other.chaos) + coherence_difference: float = abs(self.coherence - other.coherence) + + # Below 1% difference --> Use Coherence + if chaos_difference < 0.01 and coherence_difference > 0.02: + return self.coherence > other.coherence + elif chaos_difference < 0.01 and coherence_difference <= 0.02: + # When having a difficult decision, use the result that decoded as many multi-byte as possible. + # preserve RAM usage! + if len(self._payload) >= TOO_BIG_SEQUENCE: + return self.chaos < other.chaos + return self.multi_byte_usage > other.multi_byte_usage + + return self.chaos < other.chaos + + @property + def multi_byte_usage(self) -> float: + return 1.0 - (len(str(self)) / len(self.raw)) + + def __str__(self) -> str: + # Lazy Str Loading + if self._string is None: + self._string = str(self._payload, self._encoding, "strict") + return self._string + + def __repr__(self) -> str: + return f"" + + def add_submatch(self, other: CharsetMatch) -> None: + if not isinstance(other, CharsetMatch) or other == self: + raise ValueError( + "Unable to add instance <{}> as a submatch of a CharsetMatch".format( + other.__class__ + ) + ) + + other._string = None # Unload RAM usage; dirty trick. + self._leaves.append(other) + + @property + def encoding(self) -> str: + return self._encoding + + @property + def encoding_aliases(self) -> list[str]: + """ + Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855. + """ + also_known_as: list[str] = [] + for u, p in aliases.items(): + if self.encoding == u: + also_known_as.append(p) + elif self.encoding == p: + also_known_as.append(u) + return also_known_as + + @property + def bom(self) -> bool: + return self._has_sig_or_bom + + @property + def byte_order_mark(self) -> bool: + return self._has_sig_or_bom + + @property + def languages(self) -> list[str]: + """ + Return the complete list of possible languages found in decoded sequence. + Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'. + """ + return [e[0] for e in self._languages] + + @property + def language(self) -> str: + """ + Most probable language found in decoded sequence. If none were detected or inferred, the property will return + "Unknown". + """ + if not self._languages: + # Trying to infer the language based on the given encoding + # Its either English or we should not pronounce ourselves in certain cases. + if "ascii" in self.could_be_from_charset: + return "English" + + # doing it there to avoid circular import + from charset_normalizer.cd import encoding_languages, mb_encoding_languages + + languages = ( + mb_encoding_languages(self.encoding) + if is_multi_byte_encoding(self.encoding) + else encoding_languages(self.encoding) + ) + + if len(languages) == 0 or "Latin Based" in languages: + return "Unknown" + + return languages[0] + + return self._languages[0][0] + + @property + def chaos(self) -> float: + return self._mean_mess_ratio + + @property + def coherence(self) -> float: + if not self._languages: + return 0.0 + return self._languages[0][1] + + @property + def percent_chaos(self) -> float: + return round(self.chaos * 100, ndigits=3) + + @property + def percent_coherence(self) -> float: + return round(self.coherence * 100, ndigits=3) + + @property + def raw(self) -> bytes: + """ + Original untouched bytes. + """ + return self._payload + + @property + def submatch(self) -> list[CharsetMatch]: + return self._leaves + + @property + def has_submatch(self) -> bool: + return len(self._leaves) > 0 + + @property + def alphabets(self) -> list[str]: + if self._unicode_ranges is not None: + return self._unicode_ranges + # list detected ranges + detected_ranges: list[str | None] = [unicode_range(char) for char in str(self)] + # filter and sort + self._unicode_ranges = sorted(list({r for r in detected_ranges if r})) + return self._unicode_ranges + + @property + def could_be_from_charset(self) -> list[str]: + """ + The complete list of encoding that output the exact SAME str result and therefore could be the originating + encoding. + This list does include the encoding available in property 'encoding'. + """ + return [self._encoding] + [m.encoding for m in self._leaves] + + def output(self, encoding: str = "utf_8") -> bytes: + """ + Method to get re-encoded bytes payload using given target encoding. Default to UTF-8. + Any errors will be simply ignored by the encoder NOT replaced. + """ + if self._output_encoding is None or self._output_encoding != encoding: + self._output_encoding = encoding + decoded_string = str(self) + if ( + self._preemptive_declaration is not None + and self._preemptive_declaration.lower() + not in ["utf-8", "utf8", "utf_8"] + ): + patched_header = sub( + RE_POSSIBLE_ENCODING_INDICATION, + lambda m: m.string[m.span()[0] : m.span()[1]].replace( + m.groups()[0], + iana_name(self._output_encoding).replace("_", "-"), # type: ignore[arg-type] + ), + decoded_string[:8192], + count=1, + ) + + decoded_string = patched_header + decoded_string[8192:] + + self._output_payload = decoded_string.encode(encoding, "replace") + + return self._output_payload # type: ignore + + @property + def fingerprint(self) -> str: + """ + Retrieve the unique SHA256 computed using the transformed (re-encoded) payload. Not the original one. + """ + return sha256(self.output()).hexdigest() + + +class CharsetMatches: + """ + Container with every CharsetMatch items ordered by default from most probable to the less one. + Act like a list(iterable) but does not implements all related methods. + """ + + def __init__(self, results: list[CharsetMatch] | None = None): + self._results: list[CharsetMatch] = sorted(results) if results else [] + + def __iter__(self) -> Iterator[CharsetMatch]: + yield from self._results + + def __getitem__(self, item: int | str) -> CharsetMatch: + """ + Retrieve a single item either by its position or encoding name (alias may be used here). + Raise KeyError upon invalid index or encoding not present in results. + """ + if isinstance(item, int): + return self._results[item] + if isinstance(item, str): + item = iana_name(item, False) + for result in self._results: + if item in result.could_be_from_charset: + return result + raise KeyError + + def __len__(self) -> int: + return len(self._results) + + def __bool__(self) -> bool: + return len(self._results) > 0 + + def append(self, item: CharsetMatch) -> None: + """ + Insert a single match. Will be inserted accordingly to preserve sort. + Can be inserted as a submatch. + """ + if not isinstance(item, CharsetMatch): + raise ValueError( + "Cannot append instance '{}' to CharsetMatches".format( + str(item.__class__) + ) + ) + # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage) + if len(item.raw) < TOO_BIG_SEQUENCE: + for match in self._results: + if match.fingerprint == item.fingerprint and match.chaos == item.chaos: + match.add_submatch(item) + return + self._results.append(item) + self._results = sorted(self._results) + + def best(self) -> CharsetMatch | None: + """ + Simply return the first match. Strict equivalent to matches[0]. + """ + if not self._results: + return None + return self._results[0] + + def first(self) -> CharsetMatch | None: + """ + Redundant method, call the method best(). Kept for BC reasons. + """ + return self.best() + + +CoherenceMatch = Tuple[str, float] +CoherenceMatches = List[CoherenceMatch] + + +class CliDetectionResult: + def __init__( + self, + path: str, + encoding: str | None, + encoding_aliases: list[str], + alternative_encodings: list[str], + language: str, + alphabets: list[str], + has_sig_or_bom: bool, + chaos: float, + coherence: float, + unicode_path: str | None, + is_preferred: bool, + ): + self.path: str = path + self.unicode_path: str | None = unicode_path + self.encoding: str | None = encoding + self.encoding_aliases: list[str] = encoding_aliases + self.alternative_encodings: list[str] = alternative_encodings + self.language: str = language + self.alphabets: list[str] = alphabets + self.has_sig_or_bom: bool = has_sig_or_bom + self.chaos: float = chaos + self.coherence: float = coherence + self.is_preferred: bool = is_preferred + + @property + def __dict__(self) -> dict[str, Any]: # type: ignore + return { + "path": self.path, + "encoding": self.encoding, + "encoding_aliases": self.encoding_aliases, + "alternative_encodings": self.alternative_encodings, + "language": self.language, + "alphabets": self.alphabets, + "has_sig_or_bom": self.has_sig_or_bom, + "chaos": self.chaos, + "coherence": self.coherence, + "unicode_path": self.unicode_path, + "is_preferred": self.is_preferred, + } + + def to_json(self) -> str: + return dumps(self.__dict__, ensure_ascii=True, indent=4) diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/py.typed b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/utils.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf0384ccf94216f79881674f54182a93e17def0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/utils.py @@ -0,0 +1,414 @@ +from __future__ import annotations + +import importlib +import logging +import unicodedata +from codecs import IncrementalDecoder +from encodings.aliases import aliases +from functools import lru_cache +from re import findall +from typing import Generator + +from _multibytecodec import ( # type: ignore[import-not-found,import] + MultibyteIncrementalDecoder, +) + +from .constant import ( + ENCODING_MARKS, + IANA_SUPPORTED_SIMILAR, + RE_POSSIBLE_ENCODING_INDICATION, + UNICODE_RANGES_COMBINED, + UNICODE_SECONDARY_RANGE_KEYWORD, + UTF8_MAXIMAL_ALLOCATION, + COMMON_CJK_CHARACTERS, +) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_accentuated(character: str) -> bool: + try: + description: str = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + return ( + "WITH GRAVE" in description + or "WITH ACUTE" in description + or "WITH CEDILLA" in description + or "WITH DIAERESIS" in description + or "WITH CIRCUMFLEX" in description + or "WITH TILDE" in description + or "WITH MACRON" in description + or "WITH RING ABOVE" in description + ) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def remove_accent(character: str) -> str: + decomposed: str = unicodedata.decomposition(character) + if not decomposed: + return character + + codes: list[str] = decomposed.split(" ") + + return chr(int(codes[0], 16)) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def unicode_range(character: str) -> str | None: + """ + Retrieve the Unicode range official name from a single character. + """ + character_ord: int = ord(character) + + for range_name, ord_range in UNICODE_RANGES_COMBINED.items(): + if character_ord in ord_range: + return range_name + + return None + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_latin(character: str) -> bool: + try: + description: str = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + return "LATIN" in description + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_punctuation(character: str) -> bool: + character_category: str = unicodedata.category(character) + + if "P" in character_category: + return True + + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Punctuation" in character_range + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_symbol(character: str) -> bool: + character_category: str = unicodedata.category(character) + + if "S" in character_category or "N" in character_category: + return True + + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Forms" in character_range and character_category != "Lo" + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_emoticon(character: str) -> bool: + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Emoticons" in character_range or "Pictographs" in character_range + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_separator(character: str) -> bool: + if character.isspace() or character in {"|", "+", "<", ">"}: + return True + + character_category: str = unicodedata.category(character) + + return "Z" in character_category or character_category in {"Po", "Pd", "Pc"} + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_case_variable(character: str) -> bool: + return character.islower() != character.isupper() + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_cjk(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "CJK" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_hiragana(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "HIRAGANA" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_katakana(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "KATAKANA" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_hangul(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "HANGUL" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_thai(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "THAI" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_arabic(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "ARABIC" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_arabic_isolated_form(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "ARABIC" in character_name and "ISOLATED FORM" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_cjk_uncommon(character: str) -> bool: + return character not in COMMON_CJK_CHARACTERS + + +@lru_cache(maxsize=len(UNICODE_RANGES_COMBINED)) +def is_unicode_range_secondary(range_name: str) -> bool: + return any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_unprintable(character: str) -> bool: + return ( + character.isspace() is False # includes \n \t \r \v + and character.isprintable() is False + and character != "\x1a" # Why? Its the ASCII substitute character. + and character != "\ufeff" # bug discovered in Python, + # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space. + ) + + +def any_specified_encoding(sequence: bytes, search_zone: int = 8192) -> str | None: + """ + Extract using ASCII-only decoder any specified encoding in the first n-bytes. + """ + if not isinstance(sequence, bytes): + raise TypeError + + seq_len: int = len(sequence) + + results: list[str] = findall( + RE_POSSIBLE_ENCODING_INDICATION, + sequence[: min(seq_len, search_zone)].decode("ascii", errors="ignore"), + ) + + if len(results) == 0: + return None + + for specified_encoding in results: + specified_encoding = specified_encoding.lower().replace("-", "_") + + encoding_alias: str + encoding_iana: str + + for encoding_alias, encoding_iana in aliases.items(): + if encoding_alias == specified_encoding: + return encoding_iana + if encoding_iana == specified_encoding: + return encoding_iana + + return None + + +@lru_cache(maxsize=128) +def is_multi_byte_encoding(name: str) -> bool: + """ + Verify is a specific encoding is a multi byte one based on it IANA name + """ + return name in { + "utf_8", + "utf_8_sig", + "utf_16", + "utf_16_be", + "utf_16_le", + "utf_32", + "utf_32_le", + "utf_32_be", + "utf_7", + } or issubclass( + importlib.import_module(f"encodings.{name}").IncrementalDecoder, + MultibyteIncrementalDecoder, + ) + + +def identify_sig_or_bom(sequence: bytes) -> tuple[str | None, bytes]: + """ + Identify and extract SIG/BOM in given sequence. + """ + + for iana_encoding in ENCODING_MARKS: + marks: bytes | list[bytes] = ENCODING_MARKS[iana_encoding] + + if isinstance(marks, bytes): + marks = [marks] + + for mark in marks: + if sequence.startswith(mark): + return iana_encoding, mark + + return None, b"" + + +def should_strip_sig_or_bom(iana_encoding: str) -> bool: + return iana_encoding not in {"utf_16", "utf_32"} + + +def iana_name(cp_name: str, strict: bool = True) -> str: + """Returns the Python normalized encoding name (Not the IANA official name).""" + cp_name = cp_name.lower().replace("-", "_") + + encoding_alias: str + encoding_iana: str + + for encoding_alias, encoding_iana in aliases.items(): + if cp_name in [encoding_alias, encoding_iana]: + return encoding_iana + + if strict: + raise ValueError(f"Unable to retrieve IANA for '{cp_name}'") + + return cp_name + + +def cp_similarity(iana_name_a: str, iana_name_b: str) -> float: + if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b): + return 0.0 + + decoder_a = importlib.import_module(f"encodings.{iana_name_a}").IncrementalDecoder + decoder_b = importlib.import_module(f"encodings.{iana_name_b}").IncrementalDecoder + + id_a: IncrementalDecoder = decoder_a(errors="ignore") + id_b: IncrementalDecoder = decoder_b(errors="ignore") + + character_match_count: int = 0 + + for i in range(255): + to_be_decoded: bytes = bytes([i]) + if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded): + character_match_count += 1 + + return character_match_count / 254 + + +def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool: + """ + Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using + the function cp_similarity. + """ + return ( + iana_name_a in IANA_SUPPORTED_SIMILAR + and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a] + ) + + +def set_logging_handler( + name: str = "charset_normalizer", + level: int = logging.INFO, + format_string: str = "%(asctime)s | %(levelname)s | %(message)s", +) -> None: + logger = logging.getLogger(name) + logger.setLevel(level) + + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter(format_string)) + logger.addHandler(handler) + + +def cut_sequence_chunks( + sequences: bytes, + encoding_iana: str, + offsets: range, + chunk_size: int, + bom_or_sig_available: bool, + strip_sig_or_bom: bool, + sig_payload: bytes, + is_multi_byte_decoder: bool, + decoded_payload: str | None = None, +) -> Generator[str, None, None]: + if decoded_payload and is_multi_byte_decoder is False: + for i in offsets: + chunk = decoded_payload[i : i + chunk_size] + if not chunk: + break + yield chunk + else: + for i in offsets: + chunk_end = i + chunk_size + if chunk_end > len(sequences) + 8: + continue + + cut_sequence = sequences[i : i + chunk_size] + + if bom_or_sig_available and strip_sig_or_bom is False: + cut_sequence = sig_payload + cut_sequence + + chunk = cut_sequence.decode( + encoding_iana, + errors="ignore" if is_multi_byte_decoder else "strict", + ) + + # multi-byte bad cutting detector and adjustment + # not the cleanest way to perform that fix but clever enough for now. + if is_multi_byte_decoder and i > 0: + chunk_partial_size_chk: int = min(chunk_size, 16) + + if ( + decoded_payload + and chunk[:chunk_partial_size_chk] not in decoded_payload + ): + for j in range(i, i - 4, -1): + cut_sequence = sequences[j:chunk_end] + + if bom_or_sig_available and strip_sig_or_bom is False: + cut_sequence = sig_payload + cut_sequence + + chunk = cut_sequence.decode(encoding_iana, errors="ignore") + + if chunk[:chunk_partial_size_chk] in decoded_payload: + break + + yield chunk diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/version.py b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/version.py new file mode 100644 index 0000000000000000000000000000000000000000..c843e5331131fe69b5bba96d3f0c1160dcaa943b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer/version.py @@ -0,0 +1,8 @@ +""" +Expose version +""" + +from __future__ import annotations + +__version__ = "3.4.4" +VERSION = __version__.split(".") diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..658a7637871919fad01ae60e30c42bc9cc4fa2ab --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/METADATA @@ -0,0 +1,85 @@ +Metadata-Version: 2.4 +Name: conda-libmamba-solver +Version: 25.11.0 +Summary: The fast mamba solver, now in conda +Project-URL: homepage, https://github.com/conda/conda-libmamba-solver +Author-email: "Anaconda, Inc." +License: BSD 3-Clause License + + Copyright (c) 2022, Anaconda, Inc. + Copyright (c) 2023, conda + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + --- + + This work also includes code borrowed from mamba.utils v0.19, licensed as BSD 3-Clause +License-File: AUTHORS.md +License-File: LICENSE +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.10 +Requires-Dist: boltons>=23.0.0 +Requires-Dist: conda>=25.9 +Requires-Dist: msgpack>=1.1.1 +Requires-Dist: requests<3,>=2.28.0 +Requires-Dist: zstandard>=0.15 +Description-Content-Type: text/markdown + +# conda-libmamba-solver + +The fast mamba solver, now in conda! + +## What is this exactly? + +conda-libmamba-solver is a new solver for the +[conda package manager](https://docs.conda.io/) which uses the solver from the +[mamba project](https://mamba.readthedocs.io/) behind the scenes, while +carefully implementing conda's functionality and expected behaviors on top. +The library used by mamba to do the heavy-lifting is called [libsolv](https://github.com/openSUSE/libsolv). + +Additional information about the project can be found in the blog post on Anaconda's weblog: +[A Faster Solver for Conda: Libmamba](https://www.anaconda.com/blog/a-faster-conda-for-a-growing-community). + +## Documentation + +Check the [documentation](https://conda.github.io/conda-libmamba-solver/) for +instructions on how to install, use and make the most out the new conda solver! + + +## Build status + +| [![Build status](https://github.com/conda/conda-libmamba-solver/actions/workflows/tests.yml/badge.svg)](https://github.com/conda/conda-libmamba-solver/actions/workflows/tests.yml?query=branch%3Amain) [![Docs status](https://github.com/conda/conda-libmamba-solver/actions/workflows/docs.yml/badge.svg)](https://github.com/conda/conda-libmamba-solver/actions/workflows/docs.yml?query=branch%3Amain) [![codecov](https://codecov.io/gh/conda/conda-libmamba-solver/branch/main/graph/badge.svg)](https://codecov.io/gh/conda/conda-libmamba-solver) [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/conda/conda-libmamba-solver/main.svg)](https://results.pre-commit.ci/latest/github/conda/conda-libmamba-solver/main) [![CalVer version used YY.MM.MICRO](https://img.shields.io/badge/calver-YY.MM.MICRO-22bfda.svg?style=flat-square)](https://calver.org) | [![Anaconda-Server Badge](https://anaconda.org/conda-canary/conda-libmamba-solver/badges/latest_release_date.svg)](https://anaconda.org/conda-canary/conda-libmamba-solver) | +| --- | :-: | +| [`conda install defaults::conda-libmamba-solver`](https://anaconda.org/anaconda/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/anaconda/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/anaconda/conda-libmamba-solver) | +| [`conda install conda-forge::conda-libmamba-solver`](https://anaconda.org/conda-forge/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/conda-forge/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/conda-forge/conda-libmamba-solver) | +| [`conda install conda-canary/label/dev::conda-libmamba-solver`](https://anaconda.org/conda-canary/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/conda-canary/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/conda-canary/conda-libmamba-solver) | diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e3c3f9d776e094e2d73e75d07a67c378c33804bc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/RECORD @@ -0,0 +1,37 @@ +conda_libmamba_solver-25.11.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +conda_libmamba_solver-25.11.0.dist-info/METADATA,sha256=o_oBj8RWJpOCXYes0y_xHvd0ah1I0_yWpKtS5297cQw,5662 +conda_libmamba_solver-25.11.0.dist-info/RECORD,, +conda_libmamba_solver-25.11.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda_libmamba_solver-25.11.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +conda_libmamba_solver-25.11.0.dist-info/direct_url.json,sha256=rNWoGbk7ksTJ2DfIZjsYd-dXx8QUlaoMivpQcp2YVPU,103 +conda_libmamba_solver-25.11.0.dist-info/entry_points.txt,sha256=JHAxZa0f1SAUCgVquOdUUOGqSRcMyz3rkpiXL1Ploc8,61 +conda_libmamba_solver-25.11.0.dist-info/licenses/AUTHORS.md,sha256=_NosLCcbDN9KQZSQXyQmP-0kWKdoxEHt3K3OdocuyuE,460 +conda_libmamba_solver-25.11.0.dist-info/licenses/LICENSE,sha256=s5c3lMy_FgHDSK7ltL_gNFw7zSHcDcgKOEQbmUBf67A,1663 +conda_libmamba_solver/__init__.py,sha256=Er13Z9pJpQJ1pZna7WBWjS2q-ZWP6MbTRvNbtuE8GVs,564 +conda_libmamba_solver/__pycache__/__init__.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/conda_build_exceptions.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/exceptions.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/index.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/mamba_utils.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/plugin.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/repoquery.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/shards.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/shards_cache.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/shards_subset.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/shards_typing.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/solver.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/state.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/utils.cpython-314.pyc,, +conda_libmamba_solver/conda_build_exceptions.py,sha256=uPc7PKn9IN-V44wEpKeZHZpojiH2hwuQKdBzCfZHEK0,1396 +conda_libmamba_solver/exceptions.py,sha256=AqESkZmhveRKxUfRTo-QSPEWFb1DIeX6W8-wYZ9qhvM,485 +conda_libmamba_solver/index.py,sha256=xTcHO8lr29eRrz_e3qsWlB4lZOLuoDf8LHmaRTRWXLQ,31625 +conda_libmamba_solver/mamba_utils.py,sha256=aWL-IXqPx9akbkk7jgOeJgjhdzYOBZqluEyrR9LJxCE,6879 +conda_libmamba_solver/plugin.py,sha256=_P6NUwil6vTEt5Pp1jm9qkKUmq4qou5vePBdfG_I2AU,1149 +conda_libmamba_solver/repoquery.py,sha256=2IrzDBcfeM6Gq7vN0fkmJN5TKWMM8TvvpdH1dIbhOf8,7610 +conda_libmamba_solver/shards.py,sha256=RK3Caz2e42FHsi-Go8b6eUU1pJMlPE9HwdQ2fVA5xb4,24542 +conda_libmamba_solver/shards_cache.py,sha256=-KR98kr8at8-lAt_w1coRmMfRxCGLo-9BEz-QwJjGTY,5005 +conda_libmamba_solver/shards_subset.py,sha256=EorIgQAD-f9rmnElwY1-D9vDrX8fzIgkeCPvp-DqOok,21890 +conda_libmamba_solver/shards_typing.py,sha256=xxeOQzb9nqk0gN8bJyr0bhM7I30mk3RVpy81fBgSADU,1574 +conda_libmamba_solver/solver.py,sha256=KSk3mNq-PbytZaCSwvrjOz1ezjedAm-LG0NxZH_8mAA,48671 +conda_libmamba_solver/state.py,sha256=BPWt8O706ArlKBtumRuGJNkO3ZNFIzA3j-TcX2PzlRU,33572 +conda_libmamba_solver/utils.py,sha256=QoorafpuqtBbn4YPhmjprAelIsp-2SInA84z0QhztW0,3833 diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..4d30df6a4bee0031fb0524608eb58f4cf9c67a4d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///C:/miniconda3/conda-bld/conda-libmamba-solver_1764245615235/work/src"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..4423474395b8f751cbe687c9fe1d6a598a7ca838 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[conda] +conda-libmamba-solver = conda_libmamba_solver.plugin diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/__init__.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea370a8e55e9af5fcda45d1f12372a47d86f1a69 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/__init__.py @@ -0,0 +1 @@ +__version__ = "0.12.0" diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/create.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/create.py new file mode 100644 index 0000000000000000000000000000000000000000..732474d1f8afa95fcb485e1bc7fc5d0efa561788 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/create.py @@ -0,0 +1,191 @@ +""" +Tools for creating ``.conda``-format archives. + +Uses ``tempfile.SpooledTemporaryFile`` to buffer ``pkg-*.tar`` and +``info-*.tar``, then compress directly into an open `ZipFile` at the end. +`SpooledTemporaryFile` buffers the first 10MB of the package and its metadata in +memory, but writes out to disk for larger packages. + +Uses more disk space than ``conda-package-handling`` (temporary uncompressed +tarballs of the package contents) but accepts streams instead of just +files-on-the-filesystem. +""" + +from __future__ import annotations + +import json +import shutil +import tarfile +import tempfile +import zipfile +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Callable + +import zstandard + +# increase to reduce speed and increase compression (levels above 19 use much +# more memory) +ZSTD_COMPRESS_LEVEL = 19 +# increase to reduce compression and increase speed +ZSTD_COMPRESS_THREADS = 1 + +CONDA_PACKAGE_FORMAT_VERSION = 2 + +# Account for growth from "2 GB of /dev/urandom" to not exceed ZIP64_LIMIT after +# compression +CONDA_ZIP64_LIMIT = zipfile.ZIP64_LIMIT - (1 << 18) - 1 + + +def anonymize(tarinfo: tarfile.TarInfo): + """ + Pass to ``tarfile.add(..., filter=anonymize)`` to anonymize uid/gid. + + Does not anonymize mtime or any other field. + """ + tarinfo.uid = tarinfo.gid = 0 + tarinfo.uname = tarinfo.gname = "" + return tarinfo + + +class CondaTarFile(tarfile.TarFile): + """ + Subclass of :external+python:py:class:`tarfile.TarFile` that adds members to + a second ``info`` tar if they match ``is_info(name)``. + + Create this with ``conda_builder(...)`` which sets up the component + archives, then wraps them into a ``.conda`` on exit. + + Only useful for creating, not extracting ``.conda``. + """ + + info_tar: tarfile.TarFile + is_info: Callable + + def __init__( + self, + *args, + info_tar: tarfile.TarFile, + is_info=lambda name: name.startswith("info/"), + **kwargs, + ): + super().__init__(*args, **kwargs) + self.info_tar = info_tar + self.is_info = is_info + + def addfile(self, tarinfo, fileobj=None): + """ + Add the TarInfo object ``tarinfo`` to the archive. If ``fileobj`` is + given, it should be a binary file, and tarinfo.size bytes are read from + it and added to the archive. You can create TarInfo objects directly, or + by using ``gettarinfo()``. + + If ``self.is_info(tarinfo.name)`` returns ``True``, add ``tarinfo`` to + ``self.info_tar`` instead. + """ + if self.is_info(tarinfo.name): + return self.info_tar.addfile(tarinfo, fileobj=fileobj) + else: + return super().addfile(tarinfo, fileobj) + + +@contextmanager +def conda_builder( + stem, + path, + *, + compressor: Callable[ + [], zstandard.ZstdCompressor + ] = lambda: zstandard.ZstdCompressor( + level=ZSTD_COMPRESS_LEVEL, threads=ZSTD_COMPRESS_THREADS + ), + is_info: Callable[[str], bool] = lambda filename: filename.startswith("info/"), + encoding="utf-8", +) -> Iterator[CondaTarFile]: + """ + Produce a ``TarFile`` subclass used to build a ``.conda`` package. The + subclass delegates ``addfile()`` to the ``info-`` component when ``is_info`` + returns True. + + When the context manager exits, ``{path}/{stem}.conda`` is written with + the component tar archives. + + Args: + stem: output filename without extension + + path: destination path for transmuted .conda package compressor: A + function that creates instances of ``zstandard.ZstdCompressor()``. + + encoding: passed to TarFile constructor. Keep default "utf-8" for valid + .conda. + + Yields: + ``CondaTarFile`` + """ + output_path = Path(path, f"{stem}.conda") + with ( + tempfile.SpooledTemporaryFile() as info_file, + tempfile.SpooledTemporaryFile() as pkg_file, + ): + with ( + tarfile.TarFile(fileobj=info_file, mode="w", encoding=encoding) as info_tar, + CondaTarFile( + fileobj=pkg_file, + mode="w", + info_tar=info_tar, + is_info=is_info, + encoding=encoding, + ) as pkg_tar, + ): + # If we wanted to compress these at a low setting to save temporary + # space, we could insert a file object that counts bytes written in + # front of a zstd (level between 1..3) compressor. + yield pkg_tar + + info_tar.close() + pkg_tar.close() + + info_size = info_file.tell() + pkg_size = pkg_file.tell() + + info_file.seek(0) + pkg_file.seek(0) + + with zipfile.ZipFile( + output_path, + "x", # x to not append to existing + compresslevel=zipfile.ZIP_STORED, + ) as conda_file: + # Use a maximum of one Zstd compressor, stream_writer at a time to save + # # memory. + data_compress = compressor() + + pkg_metadata = {"conda_pkg_format_version": CONDA_PACKAGE_FORMAT_VERSION} + conda_file.writestr("metadata.json", json.dumps(pkg_metadata)) + + with ( + conda_file.open( + f"pkg-{stem}.tar.zst", + "w", + force_zip64=(pkg_size > CONDA_ZIP64_LIMIT), + ) as pkg_file_zip, + data_compress.stream_writer( + pkg_file_zip, size=pkg_size, closefd=False + ) as pkg_stream, + ): + shutil.copyfileobj(pkg_file._file, pkg_stream) + + with ( + conda_file.open( + f"info-{stem}.tar.zst", + "w", + force_zip64=(info_size > CONDA_ZIP64_LIMIT), + ) as info_file_zip, + data_compress.stream_writer( + info_file_zip, + size=info_size, + closefd=False, + ) as info_stream, + ): + shutil.copyfileobj(info_file._file, info_stream) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..269c387f1fb9019dc103e74d50d65f9a297943ba --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/exceptions.py @@ -0,0 +1,19 @@ +import tarfile + + +class SafetyError(tarfile.TarError): + def __init__(self, msg, *args, **kw): + msg = f"Error with archive. {msg}" + super().__init__(msg) + + +class CaseInsensitiveFileSystemError(OSError): + def __init__(self): + message = """\ +Cannot extract package to a case-insensitive file system. Your install +destination does not differentiate between upper and lowercase characters, and +this breaks things. Try installing to a location that is case-sensitive. Windows +drives are usually the culprit here - can you install to a native Unix drive, or +turn on case sensitivity for this (Windows) location? + """ + super().__init__(message) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/extract.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/extract.py new file mode 100644 index 0000000000000000000000000000000000000000..6398a2d57247fa0177f465de6e1fec3184d00eb6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/extract.py @@ -0,0 +1,93 @@ +""" +Extract package to directory, with checks against tar members extracting outside +the target directory. +""" + +from __future__ import annotations + +import os +import tarfile +from collections.abc import Generator +from errno import ELOOP +from pathlib import Path + +from . import exceptions, package_streaming + +__all__ = ["extract_stream", "extract"] +HAS_TAR_FILTER = hasattr(tarfile, "tar_filter") + + +def extract_stream( + stream: Generator[tuple[tarfile.TarFile, tarfile.TarInfo]], + dest_dir: Path | str, + tar_filter: str | None = None, +): + """ + Pipe ``stream_conda_component`` output here to extract every member into + dest_dir. + + For ``.conda`` will need to be called twice (for info and pkg components); + for ``.tar.bz2`` every member is extracted. + """ + dest_dir = os.path.realpath(dest_dir) + + def is_within_dest_dir(name): + abs_target = os.path.realpath(os.path.join(dest_dir, name)) + prefix = os.path.commonpath((dest_dir, abs_target)) + return prefix == dest_dir + + for tar_file, _ in stream: + # careful not to seek backwards + def checked_members(): + # from conda_package_handling + for member in tar_file: + if not is_within_dest_dir(member.name): + raise exceptions.SafetyError(f"contains unsafe path: {member.name}") + yield member + + try: + # Drop checked_members() when HAS_TAR_FILTER once we are 100% + # certain the stdlib filter maintains same permissions as + # checked_members(). + tar_args = {"path": dest_dir, "members": checked_members()} + if HAS_TAR_FILTER: + tar_args["filter"] = tar_filter or "fully_trusted" + tar_file.extractall(**tar_args) + except OSError as e: + if e.errno == ELOOP: + raise exceptions.CaseInsensitiveFileSystemError() from e + raise + + # next iteraton of for loop raises GeneratorExit in stream + stream.close() + + +def extract(filename, dest_dir=None, fileobj=None): + """ + Extract all components of conda package to dest_dir. + + fileobj: must be seekable if provided, if a ``.conda`` package. + """ + assert dest_dir, "dest_dir is required" + if str(filename).endswith(".conda"): + components = [ + package_streaming.CondaComponent.pkg, + package_streaming.CondaComponent.info, + ] + else: # .tar.bz2 doesn't filter by component + components = [package_streaming.CondaComponent.pkg] + + closefd = False + if not fileobj: + fileobj = open(filename, "rb") + closefd = True + + try: + for component in components: + stream = package_streaming.stream_conda_component( + filename, fileobj, component=component + ) + extract_stream(stream, dest_dir) + finally: + if closefd: + fileobj.close() diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/lazy_wheel.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/lazy_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..39a9bc9f42efb70be7e9281aa17989943e97debf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/lazy_wheel.py @@ -0,0 +1,331 @@ +"""Lazy ZIP over HTTP""" + +from __future__ import annotations + +import logging +import zipfile +from bisect import bisect_left, bisect_right +from collections.abc import Iterator +from contextlib import contextmanager +from tempfile import NamedTemporaryFile +from typing import Any +from zipfile import BadZipfile, ZipFile + +from requests import HTTPError, Session +from requests.models import CONTENT_CHUNK_SIZE, Response + +# from pip 22.0.3 with fixes & remove imports from pip + + +log = logging.getLogger(__name__) + +# If-Match (etag) to detect file changed during fetch would also be nice +HEADERS = {"Accept-Encoding": "identity"} + + +class HTTPRangeRequestUnsupported(Exception): + pass + + +class LazyZipOverHTTP: + """File-like object mapped to a ZIP file over HTTP. + + This uses HTTP range requests to lazily fetch the file's content, + which is supposed to be fed to ZipFile. If such requests are not + supported by the server, raise HTTPRangeRequestUnsupported + during initialization. + """ + + def __init__( + self, + url: str, + session: Session, + chunk_size: int = CONTENT_CHUNK_SIZE, + fall_back_to_full_download: bool = False, + ) -> None: + """ + Initialize a LazyZipOverHTTP object. + + :param session: The session to use for web requests. + :param chunk_size: The chunk size to use for downloading. + :param fall_back_to_full_download: If true, we fall back to downloading + the whole file if the server incorrectly responds with 416 + (Range Not Satisfiable) to an HTTP range request. + """ + # if CONTENT_CHUNK_SIZE is bigger than the file: + # In [8]: response.headers["Content-Range"] + # Out[8]: 'bytes 0-3133374/3133375' + + self._request_count = 0 + + self._session, self._url, self._chunk_size = session, url, chunk_size + + self._fall_back_to_full_download: bool = fall_back_to_full_download + self._has_streaming_support: bool = True + + # If the server returns 416 (Range Not Satisfiable) and the fallback is + # enabled, we request the whole file and set this to False. Some package + # servers incorrectly respond with 416 (Range Not Satisfiable) if the + # file is smaller than the range requested. + + # initial range request for the end of the file + # if the server does not support range requests, this sets + # _has_streaming_support to False + tail = self._stream_response(start="", end=CONTENT_CHUNK_SIZE) + # e.g. {'accept-ranges': 'bytes', 'content-length': '10240', + # 'content-range': 'bytes 12824-23063/23064', 'last-modified': 'Sat, 16 + # Apr 2022 13:03:02 GMT', 'date': 'Thu, 21 Apr 2022 11:34:04 GMT'} + + if self._has_streaming_support and tail.status_code != 206: + raise HTTPRangeRequestUnsupported("range request is not supported") + + if self._has_streaming_support: + # lowercase content-range to support s3 + self._length = int(tail.headers["content-range"].partition("/")[-1]) + else: + # the file is already downloaded + self._length = len(tail.content) + + self._file = NamedTemporaryFile() + self.truncate(self._length) + + # length is also in Content-Length and Content-Range header + with self._stay(): + if self._has_streaming_support: + content_length = int(tail.headers["content-length"]) + if hasattr(tail, "content"): + assert content_length == len(tail.content) + else: + content_length = len(tail.content) + self.seek(self._length - content_length) + for chunk in tail.iter_content(self._chunk_size): + self._file.write(chunk) + self._left: list[int] = [self._length - content_length] + self._right: list[int] = [self._length - 1] + + @property + def mode(self) -> str: + """Opening mode, which is always rb.""" + return "rb" + + @property + def name(self) -> str: + """Path to the underlying file.""" + return self._file.name + + def seekable(self) -> bool: + """Return whether random access is supported, which is True.""" + return True + + def close(self) -> None: + """Close the file.""" + self._file.close() + + @property + def closed(self) -> bool: + """Whether the file is closed.""" + return self._file.closed + + def read(self, size: int = -1) -> bytes: + """Read up to size bytes from the object and return them. + + As a convenience, if size is unspecified or -1, + all bytes until EOF are returned. Fewer than + size bytes may be returned if EOF is reached. + """ + # BUG does not download correctly if size is unspecified + download_size = size + start, length = self.tell(), self._length + stop = length if size < 0 else min(start + download_size, length) + start = max(0, stop - download_size) + self._download(start, stop - 1) + return self._file.read(size) + + def readable(self) -> bool: + """Return whether the file is readable, which is True.""" + return True + + def seek(self, offset: int, whence: int = 0) -> int: + """Change stream position and return the new absolute position. + + Seek to offset relative position indicated by whence: + * 0: Start of stream (the default). pos should be >= 0; + * 1: Current position - pos may be negative; + * 2: End of stream - pos usually negative. + """ + return self._file.seek(offset, whence) + + def tell(self) -> int: + """Return the current position.""" + return self._file.tell() + + def truncate(self, size: int | None = None) -> int: + """Resize the stream to the given size in bytes. + + If size is unspecified resize to the current position. + The current stream position isn't changed. + + Return the new file size. + """ + return self._file.truncate(size) + + def writable(self) -> bool: + """Return False.""" + return False + + def __enter__(self) -> LazyZipOverHTTP: + self._file.__enter__() + return self + + def __exit__(self, *exc: Any) -> bool | None: + return self._file.__exit__(*exc) + + @contextmanager + def _stay(self) -> Iterator[None]: + """Return a context manager keeping the position. + + At the end of the block, seek back to original position. + """ + pos = self.tell() + try: + yield + finally: + self.seek(pos) + + def _check_zip(self) -> None: + """Check and download until the file is a valid ZIP.""" + end = self._length - 1 + for start in reversed(range(0, end, self._chunk_size)): + self._download(start, end) + with self._stay(): + try: + # For read-only ZIP files, ZipFile only needs + # methods read, seek, seekable and tell. + ZipFile(self) # type: ignore + except BadZipfile: + pass + else: + break + + def _stream_response( + self, start: int | str, end: int, base_headers: dict[str, str] = HEADERS + ) -> Response: + """ + Return HTTP response to a range request from start to end. + If the does not support range requests, the whole file is requested. + + :param start: if "", request `end` bytes from end of file. + """ + headers = base_headers.copy() + headers["Range"] = f"bytes={start}-{end}" + log.debug("%s", headers["Range"]) + # TODO: Get range requests to be correctly cached + headers["Cache-Control"] = "no-cache" + self._request_count += 1 + + if self._has_streaming_support: + response = self._session.get(self._url, headers=headers, stream=True) + + if response.status_code == 416 and self._fall_back_to_full_download: + # Range Not Satisfiable -> enable fallback + self._has_streaming_support = False + elif response.status_code == 416: + # fallback disabled, print helpful error message + raise HTTPError( + "The server returned 416 (Range Not Satisfiable). " + "This can occur on a buggy server if the file is smaller " + "than the range requested. Set the fall_back_to_full_download flag " + "to work around this issue.", + response=response, + ) + else: + response.raise_for_status() + return response + + # no streaming support, try to get the whole file + del headers["Range"] + response = self._session.get(self._url, headers=headers, stream=True) + + response.raise_for_status() + return response + + def _merge( + self, start: int, end: int, left: int, right: int + ) -> Iterator[tuple[int, int]]: + """Return an iterator of intervals to be fetched. + + Args: + start (int): Start of needed interval + end (int): End of needed interval + left (int): Index of first overlapping downloaded data + right (int): Index after last overlapping downloaded data + """ + lslice, rslice = self._left[left:right], self._right[left:right] + i = start = min([start] + lslice[:1]) + end = max([end] + rslice[-1:]) + for j, k in zip(lslice, rslice): + if j > i: + yield i, j - 1 + i = k + 1 + if i <= end: + yield i, end + self._left[left:right], self._right[left:right] = [start], [end] + + def _download(self, start: int, end: int) -> None: + """ + Download bytes from start to end inclusively. If the server does not support + streaming for this file, this does nothing as the entire file is already + downloaded. + """ + # these assertions should hold, but read() violates them + # assert 0 <= start <= end + # assert end < self._length + + with self._stay(): + left = bisect_left(self._right, start) + right = bisect_right(self._left, end) + for start, end in self._merge(start, end, left, right): + response = self._stream_response(start, end) + self.seek(start) + for chunk in response.iter_content(self._chunk_size): + self._file.write(chunk) + + +class LazyConda(LazyZipOverHTTP): + def prefetch(self, conda_file_id): + """ + Conda fork specific. Prefetch the `.info` range from the remote archive. + Reduces number of Range requests to 2 or 3 (1 or 2 for the directory, 1 + for the file). + + conda_file_id: name of .conda without path or `.conda` extension + """ + target_file = f"info-{conda_file_id}.tar.zst" + with self._stay(): # not strictly necessary + # try to read entire conda info in one request + zf = zipfile.ZipFile(self) + infolist = zf.infolist() + for i, info in enumerate(infolist): + if info.filename == target_file: + # could be incorrect if zipfile was concatenated to another + # file (not likely for .conda) + start = info.header_offset + try: + end = infolist[i + 1].header_offset + # or info.header_offset + # + len(info.filename) + # + len(info.extra) + # + info.compress_size + # (unless Zip64) + except IndexError: + end = zf.start_dir + self.seek(start) + self.read(end - start) + log.debug( + "prefetch %s-%s", + info.header_offset, + end, + ) + break + else: + log.debug("no zip prefetch") diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/package_streaming.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/package_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..ff9ffcf2d2bbfb9508f5c36705dc06c15614e224 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/package_streaming.py @@ -0,0 +1,154 @@ +""" +Unpack conda packages without using a temporary file. +""" + +from __future__ import annotations + +import bz2 +import os +import os.path +import tarfile +import zipfile +from collections.abc import Generator +from enum import Enum + +# acquire umask taking advantage of import system lock, instead of possibly in +# multiple threads at once. +UMASK = os.umask(0) +os.umask(UMASK) + +try: + import zstandard +except ImportError: + import warnings + + warnings.warn("zstandard could not be imported. Running without .conda support.") + + zstandard = None + + +class CondaComponent(Enum): + pkg = "pkg" + info = "info" + + def __str__(self): + return self.value + + +class TarfileNoSameOwner(tarfile.TarFile): + def __init__(self, *args, umask: int | None = None, **kwargs): + """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to + read from an existing archive, 'a' to append data to an existing + file or 'w' to create a new file overwriting an existing one. `mode' + defaults to 'r'. + If `fileobj' is given, it is used for reading or writing data. If it + can be determined, `mode' is overridden by `fileobj's mode. + `fileobj' is not closed, when TarFile is closed. + """ + super().__init__(*args, **kwargs) + self.umask = umask if umask is not None else UMASK + + def chown(self, tarinfo, targetpath, numeric_owner): + """ + Override chown to be a no-op, since we don't want to preserve ownership + here. (tarfile.TarFile only lets us toggle all of (chown, chmod, mtime)) + """ + return + + def chmod(self, tarinfo, targetpath): + """ + Set file permissions of targetpath according to tarinfo, respecting + umask. + """ + if tarinfo.mode is None: + return + + try: + os.chmod(targetpath, tarinfo.mode & (-1 & (~self.umask))) + except OSError as e: + raise tarfile.ExtractError("could not change mode") from e + + +def tar_generator( + fileobj, tarfile_open=TarfileNoSameOwner.open, closefd=False, *, encoding="utf-8" +) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]: + """ + Yield (tar, member) from fileobj. + + Args: + fileobj: file-like object + + encoding: "utf-8" passed to TarFile.open(); can be changed for testing. + """ + # tarfile will not close fileobj because _extfileobj is True + # caller should take care to close files all the way back to the http request... + try: + with tarfile_open(fileobj=fileobj, mode="r|", encoding=encoding) as tar: + for member in tar: + yield tar, member + finally: + if closefd: + fileobj.close() + + +def stream_conda_info( + filename, fileobj=None +) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]: + """ + Yield members from conda's embedded info/ tarball. + + For .tar.bz2 packages, yield all members. + + Yields (tar, member) tuples. You must only use the current member to + prevent tar seeks and scans. + + To extract to disk, it's possible to call ``tar.extractall(path)`` on the + first result and then ignore the rest of this generator. ``extractall`` takes + care of some directory permissions/mtime issues, compared to ``extract`` or + writing out the file objects yourself. + """ + component = "info" + return stream_conda_component(filename, fileobj, component) + + +def stream_conda_component( + filename, + fileobj=None, + component: CondaComponent | str = CondaComponent.pkg, + *, + encoding="utf-8", +) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]: + """ + Yield members from .conda's embedded {component}- tarball. "info" or "pkg". + + For .tar.bz2 packages, yield all members. + + Yields (tar, member) tuples. You must only use the current member to + prevent tar seeks and scans. + + To extract to disk, it's possible to call ``tar.extractall(path)`` on the + first result and then ignore the rest of this generator. ``extractall`` takes + care of some directory permissions/mtime issues, compared to ``extract`` or + writing out the file objects yourself. + """ + if str(filename).endswith(".conda"): + if zstandard is None: + raise RuntimeError("Cannot unpack `.conda` without zstandard") + + zf = zipfile.ZipFile(fileobj or filename) + stem, _, _ = os.path.basename(filename).rpartition(".") + component_name = f"{component}-{stem}" + component_filename = [ + info for info in zf.infolist() if info.filename.startswith(component_name) + ] + if not component_filename: + raise LookupError(f"didn't find {component_name} component in {filename}") + assert len(component_filename) == 1 + reader = zstandard.ZstdDecompressor().stream_reader( + zf.open(component_filename[0]) + ) + elif str(filename).endswith(".tar.bz2"): + reader = bz2.open(fileobj or filename, mode="rb") + else: + raise ValueError("unsupported file extension") + return tar_generator(reader, closefd=fileobj is None, encoding=encoding) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/s3.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/s3.py new file mode 100644 index 0000000000000000000000000000000000000000..8aceb0ab80c226483dfee033cca6333eb98ed57a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/s3.py @@ -0,0 +1,83 @@ +""" +Adapt s3 to package_streaming +""" + +from __future__ import annotations + +import typing +from contextlib import closing +from typing import Any + +from . import package_streaming + +if typing.TYPE_CHECKING: # pragma: no cover + from mypy_boto3_s3 import Client + from mypy_boto3_s3.type_defs import GetObjectOutputTypeDef +else: + Client = GetObjectOutputTypeDef = None + +from .url import conda_reader_for_url + +__all__ = ["stream_conda_info", "conda_reader_for_s3"] + + +class ResponseFacade: + def __init__(self, response: GetObjectOutputTypeDef): + self.response = response + self.raw: Any = response["Body"] + + def raise_for_status(self): + # s3 get_object raises automatically? + pass + + @property + def status_code(self): + return self.response["ResponseMetadata"]["HTTPStatusCode"] + + @property + def headers(self): + # a case-sensitive dict; keys may be lowercased always? + return self.response["ResponseMetadata"]["HTTPHeaders"] + + def iter_content(self, n: int): + return iter(lambda: self.raw.read(n), b"") + + +class SessionFacade: + """ + Make s3 client look just enough like a requests.session for LazyZipOverHTTP + """ + + def __init__(self, client: Client, bucket: str, key: str): + self.client = client + self.bucket = bucket + self.key = key + + def get(self, url, *, headers: dict | None = None, stream=True): + if headers and "Range" in headers: + response = self.client.get_object( + Bucket=self.bucket, Key=self.key, Range=headers["Range"] + ) + else: + response = self.client.get_object(Bucket=self.bucket, Key=self.key) + return ResponseFacade(response) + + +def stream_conda_info(client, bucket, key): + """ + Yield (tar, member) for conda package. + + Just "info/" for .conda, all members for tar. + """ + filename, conda = conda_reader_for_s3(client, bucket, key) + + with closing(conda): + yield from package_streaming.stream_conda_info(filename, conda) + + +def conda_reader_for_s3(client: Client, bucket: str, key: str): + """ + Return (name, file_like) suitable for package_streaming APIs + """ + session: Any = SessionFacade(client, bucket, key) + return conda_reader_for_url(key, session) diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/transmute.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/transmute.py new file mode 100644 index 0000000000000000000000000000000000000000..c959b9f3d08a95027c2864bf21f6a702e726eea6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/transmute.py @@ -0,0 +1,162 @@ +""" +Convert .tar.bz2 to .conda + +Uses ``tempfile.SpooledTemporaryFile`` to buffer ``pkg-*.tar`` and +``info-*.tar``, then compress directly into an open `ZipFile` at the end. +`SpooledTemporaryFile` buffers the first 10MB of the package and its metadata in +memory, but writes out to disk for larger packages. +""" + +from __future__ import annotations + +import os +import tarfile +from collections.abc import Iterator +from pathlib import Path +from typing import Callable + +import zstandard + +from .create import ZSTD_COMPRESS_LEVEL, ZSTD_COMPRESS_THREADS, conda_builder + +# streams everything in .tar.bz2 mode +from .package_streaming import CondaComponent, stream_conda_component + + +def transmute( + package, + path, + *, + compressor: Callable[ + [], zstandard.ZstdCompressor + ] = lambda: zstandard.ZstdCompressor( + level=ZSTD_COMPRESS_LEVEL, threads=ZSTD_COMPRESS_THREADS + ), + is_info: Callable[[str], bool] = lambda filename: filename.startswith("info/"), +) -> Path: + """ + Convert .tar.bz2 conda package to .conda-format under path. + + :param package: path to .tar.bz2 conda package + :param path: destination path for transmuted .conda package + :param compressor: A function that creates instances of + ``zstandard.ZstdCompressor()`` to override defaults. + :param is_info: A function that returns True if a file belongs in the + ``info`` component of a `.conda` package. ``conda-package-handling`` + (not this package ``conda-package-streaming``) uses a set of regular + expressions to keep expected items in the info- component, while other + items starting with ``info/`` wind up in the pkg- component. + + :return: Path to transmuted package. + """ + assert package.endswith(".tar.bz2"), "can only convert .tar.bz2 to .conda" + assert os.path.isdir(path) + stem = os.path.basename(package)[: -len(".tar.bz2")] + package_stream = stream_conda_component(package) + + return transmute_stream( + stem, + path, + compressor=compressor, + is_info=is_info, + package_stream=package_stream, + ) + + +def transmute_stream( + stem, + path, + *, + compressor: Callable[ + [], zstandard.ZstdCompressor + ] = lambda: zstandard.ZstdCompressor( + level=ZSTD_COMPRESS_LEVEL, threads=ZSTD_COMPRESS_THREADS + ), + is_info: Callable[[str], bool] = lambda filename: filename.startswith("info/"), + package_stream: Iterator[tuple[tarfile.TarFile, tarfile.TarInfo]], +): + """ + Convert (TarFile, TarInfo) iterator like those produced by + ``stream_conda_component`` to .conda-format under path. Allows for more + creative data sources. + + e.g. recompress ``.conda``: + + .. code-block:: python + + transmute_stream(..., package_stream=itertools.chain( + stream_conda_component("package.conda", + component=CondaComponent.pkg), + stream_conda_component("package.conda", + component=CondaComponent.info), + )) + + This example could move files between the ``pkg-`` and ``info-`` components + depending on the ``is_info`` function. + + :param stem: output filename without extension + :param path: destination path for transmuted .conda package + :param compressor: A function that creates instances of + ``zstandard.ZstdCompressor()`` to override defaults. + :param is_info: A function that returns True if a file belongs in the + ``info`` component of a `.conda` package. ``conda-package-handling`` + (not this package ``conda-package-streaming``) uses a set of regular + expressions to keep expected items in the info- component, while other + items starting with ``info/`` wind up in the pkg- component. + :param package_stream: Iterator of (Tarfile, TarInfo) tuples. + + :return: Path to transmuted package. + """ + output_path = Path(path, f"{stem}.conda") + with conda_builder(stem, path, compressor=compressor, is_info=is_info) as conda_tar: + for tar, member in package_stream: + if member.isfile(): + conda_tar.addfile(member, tar.extractfile(member)) + else: + conda_tar.addfile(member) + + return output_path + + +def transmute_tar_bz2( + package: str, + path, +) -> Path: + """ + Convert .conda package to .tar.bz2 format under path. + + Can recompress .tar.bz2 packages. + + Args: + package: path to .conda or .tar.bz2 package. + path: destination path for transmuted package. + + Returns: + Path to transmuted package. + """ + assert package.endswith((".tar.bz2", ".conda")), "Unknown extension" + assert os.path.isdir(path) + + incoming_format = ".conda" if package.endswith(".conda") else ".tar.bz2" + + file_id = os.path.basename(package)[: -len(incoming_format)] + + if incoming_format == ".conda": + # .tar.bz2 MUST place info/ first. + components = [CondaComponent.info, CondaComponent.pkg] + else: + # .tar.bz2 doesn't filter by component + components = [CondaComponent.pkg] + + output_path = Path(path, f"{file_id}.tar.bz2") + + with open(package, "rb") as fileobj, tarfile.open(output_path, "x:bz2") as pkg_tar: + for component in components: + stream = iter(stream_conda_component(package, fileobj, component=component)) + for tar, member in stream: + if member.isfile(): + pkg_tar.addfile(member, tar.extractfile(member)) + else: + pkg_tar.addfile(member) + + return output_path diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/url.py b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/url.py new file mode 100644 index 0000000000000000000000000000000000000000..2941318abc85f94931447d10cde8d63651739133 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda_package_streaming/url.py @@ -0,0 +1,100 @@ +""" +Fetch metadata from remote .conda or .tar.bz2 package. + +Try to fetch less than the whole file if possible. + +This module should only be used to make *partial* reads against a remote +package, typically just the ``info`` portion. If a full ``.conda`` format +package is needed, it is more efficient to download locally first and then use +the file-based API. +""" + +import logging +import sys +import urllib.parse +from pathlib import Path + +import requests + +from . import package_streaming + +# Excellent HTTP Range request file-like object +from .lazy_wheel import LazyConda + +log = logging.getLogger(__name__) + +session = requests.Session() +session.headers["User-Agent"] = "conda-package-streaming/0.1.0" + + +METADATA_CHECKLIST = frozenset({"info/index.json", "info/recipe/meta.yaml"}) + + +def extract_conda_info(url, destdir, checklist=METADATA_CHECKLIST, session=session): + """ + Extract info/index.json and info/recipe/meta.yaml from url to destdir; close + url as soon as those files are found. + """ + checklist = set(checklist) + stream = stream_conda_info(url, session=session) + for tar, member in stream: + if member.name in checklist: + tar.extract(member, destdir) + checklist.remove(member.name) + if not checklist: + stream.close() + # next iteraton of for loop raises GeneratorExit in stream + + +def stream_conda_info(url, session=session): + """ + Yield (tar, member) for conda package at url + + Just "info/" for .conda, all members for tar. + """ + filename, conda = conda_reader_for_url(url, session=session) + + try: + yield from package_streaming.stream_conda_info(filename, conda) + finally: + if hasattr(conda, "release_conn"): + # For .tar.bz2. Take extra care to drop connections after we are + # done reading a partial response. + conda.release_conn() + conda.close() + + +def conda_reader_for_url( + url, session: requests.Session = session, fall_back_to_full_download: bool = False +): + """ + Return (name, file_like) suitable for package_streaming APIs + + :param url: URL to conda package + :param session: The session to use for web requests. + :param fall_back_to_full_download: If true, fall back to downloading the entire + package instead of streaming it in the case of a specific issue where the server + incorrectly responds with 416 (Range Not Satisfiable). See LazyZipOverHTTP for + more details. + """ + parsed_url = urllib.parse.urlparse(url) + *_, filename = parsed_url.path.rsplit("/", 1) + if filename.endswith(".conda"): + file_id = filename[: -len(".conda")] + conda = LazyConda( + url, session, fall_back_to_full_download=fall_back_to_full_download + ) + conda.prefetch(file_id) + elif filename.endswith(".tar.bz2"): + response = session.get(url, stream=True, headers={"Connection": "close"}) + conda = response.raw + else: + raise ValueError("Unsupported extension %s", url) + return filename, conda + + +if __name__ == "__main__": # pragma: no cover + import logging + + logging.basicConfig(level=logging.DEBUG) + extract_conda_info(sys.argv[1], Path(sys.argv[2]).absolute()) diff --git a/data/miniconda3/lib/python3.13/site-packages/distro/__init__.py b/data/miniconda3/lib/python3.13/site-packages/distro/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7686fe85a7cc94188da76bfb1c10ad2a10821256 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/distro/__init__.py @@ -0,0 +1,54 @@ +from .distro import ( + NORMALIZED_DISTRO_ID, + NORMALIZED_LSB_ID, + NORMALIZED_OS_ID, + LinuxDistribution, + __version__, + build_number, + codename, + distro_release_attr, + distro_release_info, + id, + info, + like, + linux_distribution, + lsb_release_attr, + lsb_release_info, + major_version, + minor_version, + name, + os_release_attr, + os_release_info, + uname_attr, + uname_info, + version, + version_parts, +) + +__all__ = [ + "NORMALIZED_DISTRO_ID", + "NORMALIZED_LSB_ID", + "NORMALIZED_OS_ID", + "LinuxDistribution", + "build_number", + "codename", + "distro_release_attr", + "distro_release_info", + "id", + "info", + "like", + "linux_distribution", + "lsb_release_attr", + "lsb_release_info", + "major_version", + "minor_version", + "name", + "os_release_attr", + "os_release_info", + "uname_attr", + "uname_info", + "version", + "version_parts", +] + +__version__ = __version__ diff --git a/data/miniconda3/lib/python3.13/site-packages/distro/__main__.py b/data/miniconda3/lib/python3.13/site-packages/distro/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..0c01d5b08b6b44379b931d54d7fcf5221fdc9fde --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/distro/__main__.py @@ -0,0 +1,4 @@ +from .distro import main + +if __name__ == "__main__": + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/distro/distro.py b/data/miniconda3/lib/python3.13/site-packages/distro/distro.py new file mode 100644 index 0000000000000000000000000000000000000000..78ccdfa402ac29a8ef8aaddf7b527a0efb568d43 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/distro/distro.py @@ -0,0 +1,1403 @@ +#!/usr/bin/env python +# Copyright 2015-2021 Nir Cohen +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +The ``distro`` package (``distro`` stands for Linux Distribution) provides +information about the Linux distribution it runs on, such as a reliable +machine-readable distro ID, or version information. + +It is the recommended replacement for Python's original +:py:func:`platform.linux_distribution` function, but it provides much more +functionality. An alternative implementation became necessary because Python +3.5 deprecated this function, and Python 3.8 removed it altogether. Its +predecessor function :py:func:`platform.dist` was already deprecated since +Python 2.6 and removed in Python 3.8. Still, there are many cases in which +access to OS distribution information is needed. See `Python issue 1322 +`_ for more information. +""" + +import argparse +import json +import logging +import os +import re +import shlex +import subprocess +import sys +import warnings +from typing import ( + Any, + Callable, + Dict, + Iterable, + Optional, + Sequence, + TextIO, + Tuple, + Type, +) + +try: + from typing import TypedDict +except ImportError: + # Python 3.7 + TypedDict = dict + +__version__ = "1.9.0" + + +class VersionDict(TypedDict): + major: str + minor: str + build_number: str + + +class InfoDict(TypedDict): + id: str + version: str + version_parts: VersionDict + like: str + codename: str + + +_UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc") +_UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib") +_OS_RELEASE_BASENAME = "os-release" + +#: Translation table for normalizing the "ID" attribute defined in os-release +#: files, for use by the :func:`distro.id` method. +#: +#: * Key: Value as defined in the os-release file, translated to lower case, +#: with blanks translated to underscores. +#: +#: * Value: Normalized value. +NORMALIZED_OS_ID = { + "ol": "oracle", # Oracle Linux + "opensuse-leap": "opensuse", # Newer versions of OpenSuSE report as opensuse-leap +} + +#: Translation table for normalizing the "Distributor ID" attribute returned by +#: the lsb_release command, for use by the :func:`distro.id` method. +#: +#: * Key: Value as returned by the lsb_release command, translated to lower +#: case, with blanks translated to underscores. +#: +#: * Value: Normalized value. +NORMALIZED_LSB_ID = { + "enterpriseenterpriseas": "oracle", # Oracle Enterprise Linux 4 + "enterpriseenterpriseserver": "oracle", # Oracle Linux 5 + "redhatenterpriseworkstation": "rhel", # RHEL 6, 7 Workstation + "redhatenterpriseserver": "rhel", # RHEL 6, 7 Server + "redhatenterprisecomputenode": "rhel", # RHEL 6 ComputeNode +} + +#: Translation table for normalizing the distro ID derived from the file name +#: of distro release files, for use by the :func:`distro.id` method. +#: +#: * Key: Value as derived from the file name of a distro release file, +#: translated to lower case, with blanks translated to underscores. +#: +#: * Value: Normalized value. +NORMALIZED_DISTRO_ID = { + "redhat": "rhel", # RHEL 6.x, 7.x +} + +# Pattern for content of distro release file (reversed) +_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile( + r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)" +) + +# Pattern for base file name of distro release file +_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$") + +# Base file names to be looked up for if _UNIXCONFDIR is not readable. +_DISTRO_RELEASE_BASENAMES = [ + "SuSE-release", + "altlinux-release", + "arch-release", + "base-release", + "centos-release", + "fedora-release", + "gentoo-release", + "mageia-release", + "mandrake-release", + "mandriva-release", + "mandrivalinux-release", + "manjaro-release", + "oracle-release", + "redhat-release", + "rocky-release", + "sl-release", + "slackware-version", +] + +# Base file names to be ignored when searching for distro release file +_DISTRO_RELEASE_IGNORE_BASENAMES = ( + "debian_version", + "lsb-release", + "oem-release", + _OS_RELEASE_BASENAME, + "system-release", + "plesk-release", + "iredmail-release", + "board-release", + "ec2_version", +) + + +def linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]: + """ + .. deprecated:: 1.6.0 + + :func:`distro.linux_distribution()` is deprecated. It should only be + used as a compatibility shim with Python's + :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`, + :func:`distro.version` and :func:`distro.name` instead. + + Return information about the current OS distribution as a tuple + ``(id_name, version, codename)`` with items as follows: + + * ``id_name``: If *full_distribution_name* is false, the result of + :func:`distro.id`. Otherwise, the result of :func:`distro.name`. + + * ``version``: The result of :func:`distro.version`. + + * ``codename``: The extra item (usually in parentheses) after the + os-release version number, or the result of :func:`distro.codename`. + + The interface of this function is compatible with the original + :py:func:`platform.linux_distribution` function, supporting a subset of + its parameters. + + The data it returns may not exactly be the same, because it uses more data + sources than the original function, and that may lead to different data if + the OS distribution is not consistent across multiple data sources it + provides (there are indeed such distributions ...). + + Another reason for differences is the fact that the :func:`distro.id` + method normalizes the distro ID string to a reliable machine-readable value + for a number of popular OS distributions. + """ + warnings.warn( + "distro.linux_distribution() is deprecated. It should only be used as a " + "compatibility shim with Python's platform.linux_distribution(). Please use " + "distro.id(), distro.version() and distro.name() instead.", + DeprecationWarning, + stacklevel=2, + ) + return _distro.linux_distribution(full_distribution_name) + + +def id() -> str: + """ + Return the distro ID of the current distribution, as a + machine-readable string. + + For a number of OS distributions, the returned distro ID value is + *reliable*, in the sense that it is documented and that it does not change + across releases of the distribution. + + This package maintains the following reliable distro ID values: + + ============== ========================================= + Distro ID Distribution + ============== ========================================= + "ubuntu" Ubuntu + "debian" Debian + "rhel" RedHat Enterprise Linux + "centos" CentOS + "fedora" Fedora + "sles" SUSE Linux Enterprise Server + "opensuse" openSUSE + "amzn" Amazon Linux + "arch" Arch Linux + "buildroot" Buildroot + "cloudlinux" CloudLinux OS + "exherbo" Exherbo Linux + "gentoo" GenToo Linux + "ibm_powerkvm" IBM PowerKVM + "kvmibm" KVM for IBM z Systems + "linuxmint" Linux Mint + "mageia" Mageia + "mandriva" Mandriva Linux + "parallels" Parallels + "pidora" Pidora + "raspbian" Raspbian + "oracle" Oracle Linux (and Oracle Enterprise Linux) + "scientific" Scientific Linux + "slackware" Slackware + "xenserver" XenServer + "openbsd" OpenBSD + "netbsd" NetBSD + "freebsd" FreeBSD + "midnightbsd" MidnightBSD + "rocky" Rocky Linux + "aix" AIX + "guix" Guix System + "altlinux" ALT Linux + ============== ========================================= + + If you have a need to get distros for reliable IDs added into this set, + or if you find that the :func:`distro.id` function returns a different + distro ID for one of the listed distros, please create an issue in the + `distro issue tracker`_. + + **Lookup hierarchy and transformations:** + + First, the ID is obtained from the following sources, in the specified + order. The first available and non-empty value is used: + + * the value of the "ID" attribute of the os-release file, + + * the value of the "Distributor ID" attribute returned by the lsb_release + command, + + * the first part of the file name of the distro release file, + + The so determined ID value then passes the following transformations, + before it is returned by this method: + + * it is translated to lower case, + + * blanks (which should not be there anyway) are translated to underscores, + + * a normalization of the ID is performed, based upon + `normalization tables`_. The purpose of this normalization is to ensure + that the ID is as reliable as possible, even across incompatible changes + in the OS distributions. A common reason for an incompatible change is + the addition of an os-release file, or the addition of the lsb_release + command, with ID values that differ from what was previously determined + from the distro release file name. + """ + return _distro.id() + + +def name(pretty: bool = False) -> str: + """ + Return the name of the current OS distribution, as a human-readable + string. + + If *pretty* is false, the name is returned without version or codename. + (e.g. "CentOS Linux") + + If *pretty* is true, the version and codename are appended. + (e.g. "CentOS Linux 7.1.1503 (Core)") + + **Lookup hierarchy:** + + The name is obtained from the following sources, in the specified order. + The first available and non-empty value is used: + + * If *pretty* is false: + + - the value of the "NAME" attribute of the os-release file, + + - the value of the "Distributor ID" attribute returned by the lsb_release + command, + + - the value of the "" field of the distro release file. + + * If *pretty* is true: + + - the value of the "PRETTY_NAME" attribute of the os-release file, + + - the value of the "Description" attribute returned by the lsb_release + command, + + - the value of the "" field of the distro release file, appended + with the value of the pretty version ("" and "" + fields) of the distro release file, if available. + """ + return _distro.name(pretty) + + +def version(pretty: bool = False, best: bool = False) -> str: + """ + Return the version of the current OS distribution, as a human-readable + string. + + If *pretty* is false, the version is returned without codename (e.g. + "7.0"). + + If *pretty* is true, the codename in parenthesis is appended, if the + codename is non-empty (e.g. "7.0 (Maipo)"). + + Some distributions provide version numbers with different precisions in + the different sources of distribution information. Examining the different + sources in a fixed priority order does not always yield the most precise + version (e.g. for Debian 8.2, or CentOS 7.1). + + Some other distributions may not provide this kind of information. In these + cases, an empty string would be returned. This behavior can be observed + with rolling releases distributions (e.g. Arch Linux). + + The *best* parameter can be used to control the approach for the returned + version: + + If *best* is false, the first non-empty version number in priority order of + the examined sources is returned. + + If *best* is true, the most precise version number out of all examined + sources is returned. + + **Lookup hierarchy:** + + In all cases, the version number is obtained from the following sources. + If *best* is false, this order represents the priority order: + + * the value of the "VERSION_ID" attribute of the os-release file, + * the value of the "Release" attribute returned by the lsb_release + command, + * the version number parsed from the "" field of the first line + of the distro release file, + * the version number parsed from the "PRETTY_NAME" attribute of the + os-release file, if it follows the format of the distro release files. + * the version number parsed from the "Description" attribute returned by + the lsb_release command, if it follows the format of the distro release + files. + """ + return _distro.version(pretty, best) + + +def version_parts(best: bool = False) -> Tuple[str, str, str]: + """ + Return the version of the current OS distribution as a tuple + ``(major, minor, build_number)`` with items as follows: + + * ``major``: The result of :func:`distro.major_version`. + + * ``minor``: The result of :func:`distro.minor_version`. + + * ``build_number``: The result of :func:`distro.build_number`. + + For a description of the *best* parameter, see the :func:`distro.version` + method. + """ + return _distro.version_parts(best) + + +def major_version(best: bool = False) -> str: + """ + Return the major version of the current OS distribution, as a string, + if provided. + Otherwise, the empty string is returned. The major version is the first + part of the dot-separated version string. + + For a description of the *best* parameter, see the :func:`distro.version` + method. + """ + return _distro.major_version(best) + + +def minor_version(best: bool = False) -> str: + """ + Return the minor version of the current OS distribution, as a string, + if provided. + Otherwise, the empty string is returned. The minor version is the second + part of the dot-separated version string. + + For a description of the *best* parameter, see the :func:`distro.version` + method. + """ + return _distro.minor_version(best) + + +def build_number(best: bool = False) -> str: + """ + Return the build number of the current OS distribution, as a string, + if provided. + Otherwise, the empty string is returned. The build number is the third part + of the dot-separated version string. + + For a description of the *best* parameter, see the :func:`distro.version` + method. + """ + return _distro.build_number(best) + + +def like() -> str: + """ + Return a space-separated list of distro IDs of distributions that are + closely related to the current OS distribution in regards to packaging + and programming interfaces, for example distributions the current + distribution is a derivative from. + + **Lookup hierarchy:** + + This information item is only provided by the os-release file. + For details, see the description of the "ID_LIKE" attribute in the + `os-release man page + `_. + """ + return _distro.like() + + +def codename() -> str: + """ + Return the codename for the release of the current OS distribution, + as a string. + + If the distribution does not have a codename, an empty string is returned. + + Note that the returned codename is not always really a codename. For + example, openSUSE returns "x86_64". This function does not handle such + cases in any special way and just returns the string it finds, if any. + + **Lookup hierarchy:** + + * the codename within the "VERSION" attribute of the os-release file, if + provided, + + * the value of the "Codename" attribute returned by the lsb_release + command, + + * the value of the "" field of the distro release file. + """ + return _distro.codename() + + +def info(pretty: bool = False, best: bool = False) -> InfoDict: + """ + Return certain machine-readable information items about the current OS + distribution in a dictionary, as shown in the following example: + + .. sourcecode:: python + + { + 'id': 'rhel', + 'version': '7.0', + 'version_parts': { + 'major': '7', + 'minor': '0', + 'build_number': '' + }, + 'like': 'fedora', + 'codename': 'Maipo' + } + + The dictionary structure and keys are always the same, regardless of which + information items are available in the underlying data sources. The values + for the various keys are as follows: + + * ``id``: The result of :func:`distro.id`. + + * ``version``: The result of :func:`distro.version`. + + * ``version_parts -> major``: The result of :func:`distro.major_version`. + + * ``version_parts -> minor``: The result of :func:`distro.minor_version`. + + * ``version_parts -> build_number``: The result of + :func:`distro.build_number`. + + * ``like``: The result of :func:`distro.like`. + + * ``codename``: The result of :func:`distro.codename`. + + For a description of the *pretty* and *best* parameters, see the + :func:`distro.version` method. + """ + return _distro.info(pretty, best) + + +def os_release_info() -> Dict[str, str]: + """ + Return a dictionary containing key-value pairs for the information items + from the os-release file data source of the current OS distribution. + + See `os-release file`_ for details about these information items. + """ + return _distro.os_release_info() + + +def lsb_release_info() -> Dict[str, str]: + """ + Return a dictionary containing key-value pairs for the information items + from the lsb_release command data source of the current OS distribution. + + See `lsb_release command output`_ for details about these information + items. + """ + return _distro.lsb_release_info() + + +def distro_release_info() -> Dict[str, str]: + """ + Return a dictionary containing key-value pairs for the information items + from the distro release file data source of the current OS distribution. + + See `distro release file`_ for details about these information items. + """ + return _distro.distro_release_info() + + +def uname_info() -> Dict[str, str]: + """ + Return a dictionary containing key-value pairs for the information items + from the distro release file data source of the current OS distribution. + """ + return _distro.uname_info() + + +def os_release_attr(attribute: str) -> str: + """ + Return a single named information item from the os-release file data source + of the current OS distribution. + + Parameters: + + * ``attribute`` (string): Key of the information item. + + Returns: + + * (string): Value of the information item, if the item exists. + The empty string, if the item does not exist. + + See `os-release file`_ for details about these information items. + """ + return _distro.os_release_attr(attribute) + + +def lsb_release_attr(attribute: str) -> str: + """ + Return a single named information item from the lsb_release command output + data source of the current OS distribution. + + Parameters: + + * ``attribute`` (string): Key of the information item. + + Returns: + + * (string): Value of the information item, if the item exists. + The empty string, if the item does not exist. + + See `lsb_release command output`_ for details about these information + items. + """ + return _distro.lsb_release_attr(attribute) + + +def distro_release_attr(attribute: str) -> str: + """ + Return a single named information item from the distro release file + data source of the current OS distribution. + + Parameters: + + * ``attribute`` (string): Key of the information item. + + Returns: + + * (string): Value of the information item, if the item exists. + The empty string, if the item does not exist. + + See `distro release file`_ for details about these information items. + """ + return _distro.distro_release_attr(attribute) + + +def uname_attr(attribute: str) -> str: + """ + Return a single named information item from the distro release file + data source of the current OS distribution. + + Parameters: + + * ``attribute`` (string): Key of the information item. + + Returns: + + * (string): Value of the information item, if the item exists. + The empty string, if the item does not exist. + """ + return _distro.uname_attr(attribute) + + +try: + from functools import cached_property +except ImportError: + # Python < 3.8 + class cached_property: # type: ignore + """A version of @property which caches the value. On access, it calls the + underlying function and sets the value in `__dict__` so future accesses + will not re-call the property. + """ + + def __init__(self, f: Callable[[Any], Any]) -> None: + self._fname = f.__name__ + self._f = f + + def __get__(self, obj: Any, owner: Type[Any]) -> Any: + assert obj is not None, f"call {self._fname} on an instance" + ret = obj.__dict__[self._fname] = self._f(obj) + return ret + + +class LinuxDistribution: + """ + Provides information about a OS distribution. + + This package creates a private module-global instance of this class with + default initialization arguments, that is used by the + `consolidated accessor functions`_ and `single source accessor functions`_. + By using default initialization arguments, that module-global instance + returns data about the current OS distribution (i.e. the distro this + package runs on). + + Normally, it is not necessary to create additional instances of this class. + However, in situations where control is needed over the exact data sources + that are used, instances of this class can be created with a specific + distro release file, or a specific os-release file, or without invoking the + lsb_release command. + """ + + def __init__( + self, + include_lsb: Optional[bool] = None, + os_release_file: str = "", + distro_release_file: str = "", + include_uname: Optional[bool] = None, + root_dir: Optional[str] = None, + include_oslevel: Optional[bool] = None, + ) -> None: + """ + The initialization method of this class gathers information from the + available data sources, and stores that in private instance attributes. + Subsequent access to the information items uses these private instance + attributes, so that the data sources are read only once. + + Parameters: + + * ``include_lsb`` (bool): Controls whether the + `lsb_release command output`_ is included as a data source. + + If the lsb_release command is not available in the program execution + path, the data source for the lsb_release command will be empty. + + * ``os_release_file`` (string): The path name of the + `os-release file`_ that is to be used as a data source. + + An empty string (the default) will cause the default path name to + be used (see `os-release file`_ for details). + + If the specified or defaulted os-release file does not exist, the + data source for the os-release file will be empty. + + * ``distro_release_file`` (string): The path name of the + `distro release file`_ that is to be used as a data source. + + An empty string (the default) will cause a default search algorithm + to be used (see `distro release file`_ for details). + + If the specified distro release file does not exist, or if no default + distro release file can be found, the data source for the distro + release file will be empty. + + * ``include_uname`` (bool): Controls whether uname command output is + included as a data source. If the uname command is not available in + the program execution path the data source for the uname command will + be empty. + + * ``root_dir`` (string): The absolute path to the root directory to use + to find distro-related information files. Note that ``include_*`` + parameters must not be enabled in combination with ``root_dir``. + + * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command + output is included as a data source. If the oslevel command is not + available in the program execution path the data source will be + empty. + + Public instance attributes: + + * ``os_release_file`` (string): The path name of the + `os-release file`_ that is actually used as a data source. The + empty string if no distro release file is used as a data source. + + * ``distro_release_file`` (string): The path name of the + `distro release file`_ that is actually used as a data source. The + empty string if no distro release file is used as a data source. + + * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter. + This controls whether the lsb information will be loaded. + + * ``include_uname`` (bool): The result of the ``include_uname`` + parameter. This controls whether the uname information will + be loaded. + + * ``include_oslevel`` (bool): The result of the ``include_oslevel`` + parameter. This controls whether (AIX) oslevel information will be + loaded. + + * ``root_dir`` (string): The result of the ``root_dir`` parameter. + The absolute path to the root directory to use to find distro-related + information files. + + Raises: + + * :py:exc:`ValueError`: Initialization parameters combination is not + supported. + + * :py:exc:`OSError`: Some I/O issue with an os-release file or distro + release file. + + * :py:exc:`UnicodeError`: A data source has unexpected characters or + uses an unexpected encoding. + """ + self.root_dir = root_dir + self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR + self.usr_lib_dir = ( + os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR + ) + + if os_release_file: + self.os_release_file = os_release_file + else: + etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME) + usr_lib_os_release_file = os.path.join( + self.usr_lib_dir, _OS_RELEASE_BASENAME + ) + + # NOTE: The idea is to respect order **and** have it set + # at all times for API backwards compatibility. + if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile( + usr_lib_os_release_file + ): + self.os_release_file = etc_dir_os_release_file + else: + self.os_release_file = usr_lib_os_release_file + + self.distro_release_file = distro_release_file or "" # updated later + + is_root_dir_defined = root_dir is not None + if is_root_dir_defined and (include_lsb or include_uname or include_oslevel): + raise ValueError( + "Including subprocess data sources from specific root_dir is disallowed" + " to prevent false information" + ) + self.include_lsb = ( + include_lsb if include_lsb is not None else not is_root_dir_defined + ) + self.include_uname = ( + include_uname if include_uname is not None else not is_root_dir_defined + ) + self.include_oslevel = ( + include_oslevel if include_oslevel is not None else not is_root_dir_defined + ) + + def __repr__(self) -> str: + """Return repr of all info""" + return ( + "LinuxDistribution(" + "os_release_file={self.os_release_file!r}, " + "distro_release_file={self.distro_release_file!r}, " + "include_lsb={self.include_lsb!r}, " + "include_uname={self.include_uname!r}, " + "include_oslevel={self.include_oslevel!r}, " + "root_dir={self.root_dir!r}, " + "_os_release_info={self._os_release_info!r}, " + "_lsb_release_info={self._lsb_release_info!r}, " + "_distro_release_info={self._distro_release_info!r}, " + "_uname_info={self._uname_info!r}, " + "_oslevel_info={self._oslevel_info!r})".format(self=self) + ) + + def linux_distribution( + self, full_distribution_name: bool = True + ) -> Tuple[str, str, str]: + """ + Return information about the OS distribution that is compatible + with Python's :func:`platform.linux_distribution`, supporting a subset + of its parameters. + + For details, see :func:`distro.linux_distribution`. + """ + return ( + self.name() if full_distribution_name else self.id(), + self.version(), + self._os_release_info.get("release_codename") or self.codename(), + ) + + def id(self) -> str: + """Return the distro ID of the OS distribution, as a string. + + For details, see :func:`distro.id`. + """ + + def normalize(distro_id: str, table: Dict[str, str]) -> str: + distro_id = distro_id.lower().replace(" ", "_") + return table.get(distro_id, distro_id) + + distro_id = self.os_release_attr("id") + if distro_id: + return normalize(distro_id, NORMALIZED_OS_ID) + + distro_id = self.lsb_release_attr("distributor_id") + if distro_id: + return normalize(distro_id, NORMALIZED_LSB_ID) + + distro_id = self.distro_release_attr("id") + if distro_id: + return normalize(distro_id, NORMALIZED_DISTRO_ID) + + distro_id = self.uname_attr("id") + if distro_id: + return normalize(distro_id, NORMALIZED_DISTRO_ID) + + return "" + + def name(self, pretty: bool = False) -> str: + """ + Return the name of the OS distribution, as a string. + + For details, see :func:`distro.name`. + """ + name = ( + self.os_release_attr("name") + or self.lsb_release_attr("distributor_id") + or self.distro_release_attr("name") + or self.uname_attr("name") + ) + if pretty: + name = self.os_release_attr("pretty_name") or self.lsb_release_attr( + "description" + ) + if not name: + name = self.distro_release_attr("name") or self.uname_attr("name") + version = self.version(pretty=True) + if version: + name = f"{name} {version}" + return name or "" + + def version(self, pretty: bool = False, best: bool = False) -> str: + """ + Return the version of the OS distribution, as a string. + + For details, see :func:`distro.version`. + """ + versions = [ + self.os_release_attr("version_id"), + self.lsb_release_attr("release"), + self.distro_release_attr("version_id"), + self._parse_distro_release_content(self.os_release_attr("pretty_name")).get( + "version_id", "" + ), + self._parse_distro_release_content( + self.lsb_release_attr("description") + ).get("version_id", ""), + self.uname_attr("release"), + ] + if self.uname_attr("id").startswith("aix"): + # On AIX platforms, prefer oslevel command output. + versions.insert(0, self.oslevel_info()) + elif self.id() == "debian" or "debian" in self.like().split(): + # On Debian-like, add debian_version file content to candidates list. + versions.append(self._debian_version) + version = "" + if best: + # This algorithm uses the last version in priority order that has + # the best precision. If the versions are not in conflict, that + # does not matter; otherwise, using the last one instead of the + # first one might be considered a surprise. + for v in versions: + if v.count(".") > version.count(".") or version == "": + version = v + else: + for v in versions: + if v != "": + version = v + break + if pretty and version and self.codename(): + version = f"{version} ({self.codename()})" + return version + + def version_parts(self, best: bool = False) -> Tuple[str, str, str]: + """ + Return the version of the OS distribution, as a tuple of version + numbers. + + For details, see :func:`distro.version_parts`. + """ + version_str = self.version(best=best) + if version_str: + version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?") + matches = version_regex.match(version_str) + if matches: + major, minor, build_number = matches.groups() + return major, minor or "", build_number or "" + return "", "", "" + + def major_version(self, best: bool = False) -> str: + """ + Return the major version number of the current distribution. + + For details, see :func:`distro.major_version`. + """ + return self.version_parts(best)[0] + + def minor_version(self, best: bool = False) -> str: + """ + Return the minor version number of the current distribution. + + For details, see :func:`distro.minor_version`. + """ + return self.version_parts(best)[1] + + def build_number(self, best: bool = False) -> str: + """ + Return the build number of the current distribution. + + For details, see :func:`distro.build_number`. + """ + return self.version_parts(best)[2] + + def like(self) -> str: + """ + Return the IDs of distributions that are like the OS distribution. + + For details, see :func:`distro.like`. + """ + return self.os_release_attr("id_like") or "" + + def codename(self) -> str: + """ + Return the codename of the OS distribution. + + For details, see :func:`distro.codename`. + """ + try: + # Handle os_release specially since distros might purposefully set + # this to empty string to have no codename + return self._os_release_info["codename"] + except KeyError: + return ( + self.lsb_release_attr("codename") + or self.distro_release_attr("codename") + or "" + ) + + def info(self, pretty: bool = False, best: bool = False) -> InfoDict: + """ + Return certain machine-readable information about the OS + distribution. + + For details, see :func:`distro.info`. + """ + return InfoDict( + id=self.id(), + version=self.version(pretty, best), + version_parts=VersionDict( + major=self.major_version(best), + minor=self.minor_version(best), + build_number=self.build_number(best), + ), + like=self.like(), + codename=self.codename(), + ) + + def os_release_info(self) -> Dict[str, str]: + """ + Return a dictionary containing key-value pairs for the information + items from the os-release file data source of the OS distribution. + + For details, see :func:`distro.os_release_info`. + """ + return self._os_release_info + + def lsb_release_info(self) -> Dict[str, str]: + """ + Return a dictionary containing key-value pairs for the information + items from the lsb_release command data source of the OS + distribution. + + For details, see :func:`distro.lsb_release_info`. + """ + return self._lsb_release_info + + def distro_release_info(self) -> Dict[str, str]: + """ + Return a dictionary containing key-value pairs for the information + items from the distro release file data source of the OS + distribution. + + For details, see :func:`distro.distro_release_info`. + """ + return self._distro_release_info + + def uname_info(self) -> Dict[str, str]: + """ + Return a dictionary containing key-value pairs for the information + items from the uname command data source of the OS distribution. + + For details, see :func:`distro.uname_info`. + """ + return self._uname_info + + def oslevel_info(self) -> str: + """ + Return AIX' oslevel command output. + """ + return self._oslevel_info + + def os_release_attr(self, attribute: str) -> str: + """ + Return a single named information item from the os-release file data + source of the OS distribution. + + For details, see :func:`distro.os_release_attr`. + """ + return self._os_release_info.get(attribute, "") + + def lsb_release_attr(self, attribute: str) -> str: + """ + Return a single named information item from the lsb_release command + output data source of the OS distribution. + + For details, see :func:`distro.lsb_release_attr`. + """ + return self._lsb_release_info.get(attribute, "") + + def distro_release_attr(self, attribute: str) -> str: + """ + Return a single named information item from the distro release file + data source of the OS distribution. + + For details, see :func:`distro.distro_release_attr`. + """ + return self._distro_release_info.get(attribute, "") + + def uname_attr(self, attribute: str) -> str: + """ + Return a single named information item from the uname command + output data source of the OS distribution. + + For details, see :func:`distro.uname_attr`. + """ + return self._uname_info.get(attribute, "") + + @cached_property + def _os_release_info(self) -> Dict[str, str]: + """ + Get the information items from the specified os-release file. + + Returns: + A dictionary containing all information items. + """ + if os.path.isfile(self.os_release_file): + with open(self.os_release_file, encoding="utf-8") as release_file: + return self._parse_os_release_content(release_file) + return {} + + @staticmethod + def _parse_os_release_content(lines: TextIO) -> Dict[str, str]: + """ + Parse the lines of an os-release file. + + Parameters: + + * lines: Iterable through the lines in the os-release file. + Each line must be a unicode string or a UTF-8 encoded byte + string. + + Returns: + A dictionary containing all information items. + """ + props = {} + lexer = shlex.shlex(lines, posix=True) + lexer.whitespace_split = True + + tokens = list(lexer) + for token in tokens: + # At this point, all shell-like parsing has been done (i.e. + # comments processed, quotes and backslash escape sequences + # processed, multi-line values assembled, trailing newlines + # stripped, etc.), so the tokens are now either: + # * variable assignments: var=value + # * commands or their arguments (not allowed in os-release) + # Ignore any tokens that are not variable assignments + if "=" in token: + k, v = token.split("=", 1) + props[k.lower()] = v + + if "version" in props: + # extract release codename (if any) from version attribute + match = re.search(r"\((\D+)\)|,\s*(\D+)", props["version"]) + if match: + release_codename = match.group(1) or match.group(2) + props["codename"] = props["release_codename"] = release_codename + + if "version_codename" in props: + # os-release added a version_codename field. Use that in + # preference to anything else Note that some distros purposefully + # do not have code names. They should be setting + # version_codename="" + props["codename"] = props["version_codename"] + elif "ubuntu_codename" in props: + # Same as above but a non-standard field name used on older Ubuntus + props["codename"] = props["ubuntu_codename"] + + return props + + @cached_property + def _lsb_release_info(self) -> Dict[str, str]: + """ + Get the information items from the lsb_release command output. + + Returns: + A dictionary containing all information items. + """ + if not self.include_lsb: + return {} + try: + cmd = ("lsb_release", "-a") + stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL) + # Command not found or lsb_release returned error + except (OSError, subprocess.CalledProcessError): + return {} + content = self._to_str(stdout).splitlines() + return self._parse_lsb_release_content(content) + + @staticmethod + def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]: + """ + Parse the output of the lsb_release command. + + Parameters: + + * lines: Iterable through the lines of the lsb_release output. + Each line must be a unicode string or a UTF-8 encoded byte + string. + + Returns: + A dictionary containing all information items. + """ + props = {} + for line in lines: + kv = line.strip("\n").split(":", 1) + if len(kv) != 2: + # Ignore lines without colon. + continue + k, v = kv + props.update({k.replace(" ", "_").lower(): v.strip()}) + return props + + @cached_property + def _uname_info(self) -> Dict[str, str]: + if not self.include_uname: + return {} + try: + cmd = ("uname", "-rs") + stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL) + except OSError: + return {} + content = self._to_str(stdout).splitlines() + return self._parse_uname_content(content) + + @cached_property + def _oslevel_info(self) -> str: + if not self.include_oslevel: + return "" + try: + stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL) + except (OSError, subprocess.CalledProcessError): + return "" + return self._to_str(stdout).strip() + + @cached_property + def _debian_version(self) -> str: + try: + with open( + os.path.join(self.etc_dir, "debian_version"), encoding="ascii" + ) as fp: + return fp.readline().rstrip() + except FileNotFoundError: + return "" + + @staticmethod + def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]: + if not lines: + return {} + props = {} + match = re.search(r"^([^\s]+)\s+([\d\.]+)", lines[0].strip()) + if match: + name, version = match.groups() + + # This is to prevent the Linux kernel version from + # appearing as the 'best' version on otherwise + # identifiable distributions. + if name == "Linux": + return {} + props["id"] = name.lower() + props["name"] = name + props["release"] = version + return props + + @staticmethod + def _to_str(bytestring: bytes) -> str: + encoding = sys.getfilesystemencoding() + return bytestring.decode(encoding) + + @cached_property + def _distro_release_info(self) -> Dict[str, str]: + """ + Get the information items from the specified distro release file. + + Returns: + A dictionary containing all information items. + """ + if self.distro_release_file: + # If it was specified, we use it and parse what we can, even if + # its file name or content does not match the expected pattern. + distro_info = self._parse_distro_release_file(self.distro_release_file) + basename = os.path.basename(self.distro_release_file) + # The file name pattern for user-specified distro release files + # is somewhat more tolerant (compared to when searching for the + # file), because we want to use what was specified as best as + # possible. + match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename) + else: + try: + basenames = [ + basename + for basename in os.listdir(self.etc_dir) + if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES + and os.path.isfile(os.path.join(self.etc_dir, basename)) + ] + # We sort for repeatability in cases where there are multiple + # distro specific files; e.g. CentOS, Oracle, Enterprise all + # containing `redhat-release` on top of their own. + basenames.sort() + except OSError: + # This may occur when /etc is not readable but we can't be + # sure about the *-release files. Check common entries of + # /etc for information. If they turn out to not be there the + # error is handled in `_parse_distro_release_file()`. + basenames = _DISTRO_RELEASE_BASENAMES + for basename in basenames: + match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename) + if match is None: + continue + filepath = os.path.join(self.etc_dir, basename) + distro_info = self._parse_distro_release_file(filepath) + # The name is always present if the pattern matches. + if "name" not in distro_info: + continue + self.distro_release_file = filepath + break + else: # the loop didn't "break": no candidate. + return {} + + if match is not None: + distro_info["id"] = match.group(1) + + # CloudLinux < 7: manually enrich info with proper id. + if "cloudlinux" in distro_info.get("name", "").lower(): + distro_info["id"] = "cloudlinux" + + return distro_info + + def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]: + """ + Parse a distro release file. + + Parameters: + + * filepath: Path name of the distro release file. + + Returns: + A dictionary containing all information items. + """ + try: + with open(filepath, encoding="utf-8") as fp: + # Only parse the first line. For instance, on SLES there + # are multiple lines. We don't want them... + return self._parse_distro_release_content(fp.readline()) + except OSError: + # Ignore not being able to read a specific, seemingly version + # related file. + # See https://github.com/python-distro/distro/issues/162 + return {} + + @staticmethod + def _parse_distro_release_content(line: str) -> Dict[str, str]: + """ + Parse a line from a distro release file. + + Parameters: + * line: Line from the distro release file. Must be a unicode string + or a UTF-8 encoded byte string. + + Returns: + A dictionary containing all information items. + """ + matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1]) + distro_info = {} + if matches: + # regexp ensures non-None + distro_info["name"] = matches.group(3)[::-1] + if matches.group(2): + distro_info["version_id"] = matches.group(2)[::-1] + if matches.group(1): + distro_info["codename"] = matches.group(1)[::-1] + elif line: + distro_info["name"] = line.strip() + return distro_info + + +_distro = LinuxDistribution() + + +def main() -> None: + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + logger.addHandler(logging.StreamHandler(sys.stdout)) + + parser = argparse.ArgumentParser(description="OS distro info tool") + parser.add_argument( + "--json", "-j", help="Output in machine readable format", action="store_true" + ) + + parser.add_argument( + "--root-dir", + "-r", + type=str, + dest="root_dir", + help="Path to the root filesystem directory (defaults to /)", + ) + + args = parser.parse_args() + + if args.root_dir: + dist = LinuxDistribution( + include_lsb=False, + include_uname=False, + include_oslevel=False, + root_dir=args.root_dir, + ) + else: + dist = _distro + + if args.json: + logger.info(json.dumps(dist.info(), indent=4, sort_keys=True)) + else: + logger.info("Name: %s", dist.name(pretty=True)) + distribution_version = dist.version(pretty=True) + logger.info("Version: %s", distribution_version) + distribution_codename = dist.codename() + logger.info("Codename: %s", distribution_codename) + + +if __name__ == "__main__": + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/distro/py.typed b/data/miniconda3/lib/python3.13/site-packages/distro/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/__init__.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d80ca29fba2334cb3978686f55037900aeeb19a3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/__init__.py @@ -0,0 +1,34 @@ +"""Parse docstrings as per Sphinx notation.""" + +from .common import ( + Docstring, + DocstringDeprecated, + DocstringMeta, + DocstringParam, + DocstringRaises, + DocstringReturns, + DocstringStyle, + ParseError, + RenderingStyle, +) +from .parser import compose, parse, parse_from_object +from .util import combine_docstrings + +Style = DocstringStyle # backwards compatibility + +__all__ = [ + "parse", + "parse_from_object", + "combine_docstrings", + "compose", + "ParseError", + "Docstring", + "DocstringMeta", + "DocstringParam", + "DocstringRaises", + "DocstringReturns", + "DocstringDeprecated", + "DocstringStyle", + "RenderingStyle", + "Style", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/attrdoc.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/attrdoc.py new file mode 100644 index 0000000000000000000000000000000000000000..de84a85d11747bb90d0650f041292d2d1f099e92 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/attrdoc.py @@ -0,0 +1,126 @@ +"""Attribute docstrings parsing. + +.. seealso:: https://peps.python.org/pep-0257/#what-is-a-docstring +""" + +import ast +import inspect +import textwrap +import typing as T +from types import ModuleType + +from .common import Docstring, DocstringParam + + +def ast_get_constant_value(node: ast.AST) -> T.Any: + """Return the constant's value if the given node is a constant.""" + return getattr(node, "value") + + +def ast_unparse(node: ast.AST) -> T.Optional[str]: + """Convert the AST node to source code as a string.""" + if hasattr(ast, "unparse"): + return ast.unparse(node) + # Support simple cases in Python < 3.9 + if isinstance(node, ast.Constant): + return str(ast_get_constant_value(node)) + if isinstance(node, ast.Name): + return node.id + return None + + +def ast_is_literal_str(node: ast.AST) -> bool: + """Return True if the given node is a literal string.""" + return ( + isinstance(node, ast.Expr) + and isinstance(node.value, ast.Constant) + and isinstance(ast_get_constant_value(node.value), str) + ) + + +def ast_get_attribute( + node: ast.AST, +) -> T.Optional[T.Tuple[str, T.Optional[str], T.Optional[str]]]: + """Return name, type and default if the given node is an attribute.""" + if isinstance(node, (ast.Assign, ast.AnnAssign)): + target = ( + node.targets[0] if isinstance(node, ast.Assign) else node.target + ) + if isinstance(target, ast.Name): + type_str = None + if isinstance(node, ast.AnnAssign): + type_str = ast_unparse(node.annotation) + default = None + if node.value: + default = ast_unparse(node.value) + return target.id, type_str, default + return None + + +class AttributeDocstrings(ast.NodeVisitor): + """An ast.NodeVisitor that collects attribute docstrings.""" + + attr_docs = None + prev_attr = None + + def visit(self, node): + if self.prev_attr and ast_is_literal_str(node): + attr_name, attr_type, attr_default = self.prev_attr + self.attr_docs[attr_name] = ( + ast_get_constant_value(node.value), + attr_type, + attr_default, + ) + self.prev_attr = ast_get_attribute(node) + if isinstance(node, (ast.ClassDef, ast.Module)): + self.generic_visit(node) + + def get_attr_docs( + self, component: T.Any + ) -> T.Dict[str, T.Tuple[str, T.Optional[str], T.Optional[str]]]: + """Get attribute docstrings from the given component. + + :param component: component to process (class or module) + :returns: for each attribute docstring, a tuple with (description, + type, default) + """ + self.attr_docs = {} + self.prev_attr = None + try: + source = textwrap.dedent(inspect.getsource(component)) + except OSError: + pass + else: + tree = ast.parse(source) + if inspect.ismodule(component): + self.visit(tree) + elif isinstance(tree, ast.Module) and isinstance( + tree.body[0], ast.ClassDef + ): + self.visit(tree.body[0]) + return self.attr_docs + + +def add_attribute_docstrings( + obj: T.Union[type, ModuleType], docstring: Docstring +) -> None: + """Add attribute docstrings found in the object's source code. + + :param obj: object from which to parse attribute docstrings + :param docstring: Docstring object where found attributes are added + :returns: list with names of added attributes + """ + params = set(p.arg_name for p in docstring.params) + for arg_name, (description, type_name, default) in ( + AttributeDocstrings().get_attr_docs(obj).items() + ): + if arg_name not in params: + param = DocstringParam( + args=["attribute", arg_name], + description=description, + arg_name=arg_name, + type_name=type_name, + is_optional=default is not None, + default=default, + ) + docstring.meta.append(param) diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/common.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/common.py new file mode 100644 index 0000000000000000000000000000000000000000..880e37864d59e460e52e5174a6d371c81ea54617 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/common.py @@ -0,0 +1,229 @@ +"""Common methods for parsing.""" + +import enum +import typing as T + +PARAM_KEYWORDS = { + "param", + "parameter", + "arg", + "argument", + "attribute", + "key", + "keyword", +} +RAISES_KEYWORDS = {"raises", "raise", "except", "exception"} +DEPRECATION_KEYWORDS = {"deprecation", "deprecated"} +RETURNS_KEYWORDS = {"return", "returns"} +YIELDS_KEYWORDS = {"yield", "yields"} +EXAMPLES_KEYWORDS = {"example", "examples"} + + +class ParseError(RuntimeError): + """Base class for all parsing related errors.""" + + +class DocstringStyle(enum.Enum): + """Docstring style.""" + + REST = 1 + GOOGLE = 2 + NUMPYDOC = 3 + EPYDOC = 4 + AUTO = 255 + + +class RenderingStyle(enum.Enum): + """Rendering style when unparsing parsed docstrings.""" + + COMPACT = 1 + CLEAN = 2 + EXPANDED = 3 + + +class DocstringMeta: + """Docstring meta information. + + Symbolizes lines in form of + + :param arg: description + :raises ValueError: if something happens + """ + + def __init__( + self, args: T.List[str], description: T.Optional[str] + ) -> None: + """Initialize self. + + :param args: list of arguments. The exact content of this variable is + dependent on the kind of docstring; it's used to distinguish + between custom docstring meta information items. + :param description: associated docstring description. + """ + self.args = args + self.description = description + + +class DocstringParam(DocstringMeta): + """DocstringMeta symbolizing :param metadata.""" + + def __init__( + self, + args: T.List[str], + description: T.Optional[str], + arg_name: str, + type_name: T.Optional[str], + is_optional: T.Optional[bool], + default: T.Optional[str], + ) -> None: + """Initialize self.""" + super().__init__(args, description) + self.arg_name = arg_name + self.type_name = type_name + self.is_optional = is_optional + self.default = default + + +class DocstringReturns(DocstringMeta): + """DocstringMeta symbolizing :returns or :yields metadata.""" + + def __init__( + self, + args: T.List[str], + description: T.Optional[str], + type_name: T.Optional[str], + is_generator: bool, + return_name: T.Optional[str] = None, + ) -> None: + """Initialize self.""" + super().__init__(args, description) + self.type_name = type_name + self.is_generator = is_generator + self.return_name = return_name + + +class DocstringRaises(DocstringMeta): + """DocstringMeta symbolizing :raises metadata.""" + + def __init__( + self, + args: T.List[str], + description: T.Optional[str], + type_name: T.Optional[str], + ) -> None: + """Initialize self.""" + super().__init__(args, description) + self.type_name = type_name + self.description = description + + +class DocstringDeprecated(DocstringMeta): + """DocstringMeta symbolizing deprecation metadata.""" + + def __init__( + self, + args: T.List[str], + description: T.Optional[str], + version: T.Optional[str], + ) -> None: + """Initialize self.""" + super().__init__(args, description) + self.version = version + self.description = description + + +class DocstringExample(DocstringMeta): + """DocstringMeta symbolizing example metadata.""" + + def __init__( + self, + args: T.List[str], + snippet: T.Optional[str], + description: T.Optional[str], + ) -> None: + """Initialize self.""" + super().__init__(args, description) + self.snippet = snippet + self.description = description + + +class Docstring: + """Docstring object representation.""" + + def __init__( + self, + style=None, # type: T.Optional[DocstringStyle] + ) -> None: + """Initialize self.""" + self.short_description = None # type: T.Optional[str] + self.long_description = None # type: T.Optional[str] + self.blank_after_short_description = False + self.blank_after_long_description = False + self.meta = [] # type: T.List[DocstringMeta] + self.style = style # type: T.Optional[DocstringStyle] + + @property + def description(self) -> T.Optional[str]: + """Return the full description of the function + + Returns None if the docstring did not include any description + """ + ret = [] + if self.short_description: + ret.append(self.short_description) + if self.blank_after_short_description: + ret.append("") + if self.long_description: + ret.append(self.long_description) + + if not ret: + return None + + return "\n".join(ret) + + @property + def params(self) -> T.List[DocstringParam]: + """Return a list of information on function params.""" + return [item for item in self.meta if isinstance(item, DocstringParam)] + + @property + def raises(self) -> T.List[DocstringRaises]: + """Return a list of information on the exceptions that the function + may raise. + """ + return [ + item for item in self.meta if isinstance(item, DocstringRaises) + ] + + @property + def returns(self) -> T.Optional[DocstringReturns]: + """Return a single information on function return. + + Takes the first return information. + """ + for item in self.meta: + if isinstance(item, DocstringReturns): + return item + return None + + @property + def many_returns(self) -> T.List[DocstringReturns]: + """Return a list of information on function return.""" + return [ + item for item in self.meta if isinstance(item, DocstringReturns) + ] + + @property + def deprecation(self) -> T.Optional[DocstringDeprecated]: + """Return a single information on function deprecation notes.""" + for item in self.meta: + if isinstance(item, DocstringDeprecated): + return item + return None + + @property + def examples(self) -> T.List[DocstringExample]: + """Return a list of information on function examples.""" + return [ + item for item in self.meta if isinstance(item, DocstringExample) + ] diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/epydoc.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/epydoc.py new file mode 100644 index 0000000000000000000000000000000000000000..4d4dde67d308f390a1ac973b77f89c285e6119ad --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/epydoc.py @@ -0,0 +1,269 @@ +"""Epyoc-style docstring parsing. + +.. seealso:: http://epydoc.sourceforge.net/manual-fields.html +""" + +import inspect +import re +import typing as T + +from .common import ( + Docstring, + DocstringMeta, + DocstringParam, + DocstringRaises, + DocstringReturns, + DocstringStyle, + ParseError, + RenderingStyle, +) + + +def _clean_str(string: str) -> T.Optional[str]: + string = string.strip() + if len(string) > 0: + return string + return None + + +def parse(text: str) -> Docstring: + """Parse the epydoc-style docstring into its components. + + :returns: parsed docstring + """ + ret = Docstring(style=DocstringStyle.EPYDOC) + if not text: + return ret + + text = inspect.cleandoc(text) + match = re.search("^@", text, flags=re.M) + if match: + desc_chunk = text[: match.start()] + meta_chunk = text[match.start() :] + else: + desc_chunk = text + meta_chunk = "" + + parts = desc_chunk.split("\n", 1) + ret.short_description = parts[0] or None + if len(parts) > 1: + long_desc_chunk = parts[1] or "" + ret.blank_after_short_description = long_desc_chunk.startswith("\n") + ret.blank_after_long_description = long_desc_chunk.endswith("\n\n") + ret.long_description = long_desc_chunk.strip() or None + + param_pattern = re.compile( + r"(param|keyword|type)(\s+[_A-z][_A-z0-9]*\??):" + ) + raise_pattern = re.compile(r"(raise)(\s+[_A-z][_A-z0-9]*\??)?:") + return_pattern = re.compile(r"(return|rtype|yield|ytype):") + meta_pattern = re.compile( + r"([_A-z][_A-z0-9]+)((\s+[_A-z][_A-z0-9]*\??)*):" + ) + + # tokenize + stream: T.List[T.Tuple[str, str, T.List[str], str]] = [] + for match in re.finditer( + r"(^@.*?)(?=^@|\Z)", meta_chunk, flags=re.S | re.M + ): + chunk = match.group(0) + if not chunk: + continue + + param_match = re.search(param_pattern, chunk) + raise_match = re.search(raise_pattern, chunk) + return_match = re.search(return_pattern, chunk) + meta_match = re.search(meta_pattern, chunk) + + match = param_match or raise_match or return_match or meta_match + if not match: + raise ParseError(f'Error parsing meta information near "{chunk}".') + + desc_chunk = chunk[match.end() :] + if param_match: + base = "param" + key: str = match.group(1) + args = [match.group(2).strip()] + elif raise_match: + base = "raise" + key: str = match.group(1) + args = [] if match.group(2) is None else [match.group(2).strip()] + elif return_match: + base = "return" + key: str = match.group(1) + args = [] + else: + base = "meta" + key: str = match.group(1) + token = _clean_str(match.group(2).strip()) + args = [] if token is None else re.split(r"\s+", token) + + # Make sure we didn't match some existing keyword in an incorrect + # way here: + if key in [ + "param", + "keyword", + "type", + "return", + "rtype", + "yield", + "ytype", + ]: + raise ParseError( + f'Error parsing meta information near "{chunk}".' + ) + + desc = desc_chunk.strip() + if "\n" in desc: + first_line, rest = desc.split("\n", 1) + desc = first_line + "\n" + inspect.cleandoc(rest) + stream.append((base, key, args, desc)) + + # Combine type_name, arg_name, and description information + params: T.Dict[str, T.Dict[str, T.Any]] = {} + for base, key, args, desc in stream: + if base not in ["param", "return"]: + continue # nothing to do + + (arg_name,) = args or ("return",) + info = params.setdefault(arg_name, {}) + info_key = "type_name" if "type" in key else "description" + info[info_key] = desc + + if base == "return": + is_generator = key in {"ytype", "yield"} + if info.setdefault("is_generator", is_generator) != is_generator: + raise ParseError( + f'Error parsing meta information for "{arg_name}".' + ) + + is_done: T.Dict[str, bool] = {} + for base, key, args, desc in stream: + if base == "param" and not is_done.get(args[0], False): + (arg_name,) = args + info = params[arg_name] + type_name = info.get("type_name") + + if type_name and type_name.endswith("?"): + is_optional = True + type_name = type_name[:-1] + else: + is_optional = False + + match = re.match(r".*defaults to (.+)", desc, flags=re.DOTALL) + default = match.group(1).rstrip(".") if match else None + + meta_item = DocstringParam( + args=[key, arg_name], + description=info.get("description"), + arg_name=arg_name, + type_name=type_name, + is_optional=is_optional, + default=default, + ) + is_done[arg_name] = True + elif base == "return" and not is_done.get("return", False): + info = params["return"] + meta_item = DocstringReturns( + args=[key], + description=info.get("description"), + type_name=info.get("type_name"), + is_generator=info.get("is_generator", False), + ) + is_done["return"] = True + elif base == "raise": + (type_name,) = args or (None,) + meta_item = DocstringRaises( + args=[key] + args, + description=desc, + type_name=type_name, + ) + elif base == "meta": + meta_item = DocstringMeta( + args=[key] + args, + description=desc, + ) + else: + (key, *_) = args or ("return",) + assert is_done.get(key, False) + continue # don't append + + ret.meta.append(meta_item) + + return ret + + +def compose( + docstring: Docstring, + rendering_style: RenderingStyle = RenderingStyle.COMPACT, + indent: str = " ", +) -> str: + """Render a parsed docstring into docstring text. + + :param docstring: parsed docstring representation + :param rendering_style: the style to render docstrings + :param indent: the characters used as indentation in the docstring string + :returns: docstring text + """ + + def process_desc(desc: T.Optional[str], is_type: bool) -> str: + if not desc: + return "" + + if rendering_style == RenderingStyle.EXPANDED or ( + rendering_style == RenderingStyle.CLEAN and not is_type + ): + (first, *rest) = desc.splitlines() + return "\n".join( + ["\n" + indent + first] + [indent + line for line in rest] + ) + + (first, *rest) = desc.splitlines() + return "\n".join([" " + first] + [indent + line for line in rest]) + + parts: T.List[str] = [] + if docstring.short_description: + parts.append(docstring.short_description) + if docstring.blank_after_short_description: + parts.append("") + if docstring.long_description: + parts.append(docstring.long_description) + if docstring.blank_after_long_description: + parts.append("") + + for meta in docstring.meta: + if isinstance(meta, DocstringParam): + if meta.type_name: + type_name = ( + f"{meta.type_name}?" + if meta.is_optional + else meta.type_name + ) + text = f"@type {meta.arg_name}:" + text += process_desc(type_name, True) + parts.append(text) + text = f"@param {meta.arg_name}:" + process_desc( + meta.description, False + ) + parts.append(text) + elif isinstance(meta, DocstringReturns): + (arg_key, type_key) = ( + ("yield", "ytype") + if meta.is_generator + else ("return", "rtype") + ) + if meta.type_name: + text = f"@{type_key}:" + process_desc(meta.type_name, True) + parts.append(text) + if meta.description: + text = f"@{arg_key}:" + process_desc(meta.description, False) + parts.append(text) + elif isinstance(meta, DocstringRaises): + text = f"@raise {meta.type_name}:" if meta.type_name else "@raise:" + text += process_desc(meta.description, False) + parts.append(text) + else: + text = f'@{" ".join(meta.args)}:' + text += process_desc(meta.description, False) + parts.append(text) + return "\n".join(parts) diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/google.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/google.py new file mode 100644 index 0000000000000000000000000000000000000000..aa4284e28a4a43758c7b6a650d38749dbedddf2a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/google.py @@ -0,0 +1,414 @@ +"""Google-style docstring parsing.""" + +import inspect +import re +import typing as T +from collections import OrderedDict, namedtuple +from enum import IntEnum + +from .common import ( + EXAMPLES_KEYWORDS, + PARAM_KEYWORDS, + RAISES_KEYWORDS, + RETURNS_KEYWORDS, + YIELDS_KEYWORDS, + Docstring, + DocstringExample, + DocstringMeta, + DocstringParam, + DocstringRaises, + DocstringReturns, + DocstringStyle, + ParseError, + RenderingStyle, +) + + +class SectionType(IntEnum): + """Types of sections.""" + + SINGULAR = 0 + """For sections like examples.""" + + MULTIPLE = 1 + """For sections like params.""" + + SINGULAR_OR_MULTIPLE = 2 + """For sections like returns or yields.""" + + +class Section(namedtuple("SectionBase", "title key type")): + """A docstring section.""" + + +GOOGLE_TYPED_ARG_REGEX = re.compile(r"\s*(.+?)\s*\(\s*(.*[^\s]+)\s*\)") +GOOGLE_ARG_DESC_REGEX = re.compile(r".*\. Defaults to (.+)\.") +MULTIPLE_PATTERN = re.compile(r"(\s*[^:\s]+:)|([^:]*\]:.*)") + +DEFAULT_SECTIONS = [ + Section("Arguments", "param", SectionType.MULTIPLE), + Section("Args", "param", SectionType.MULTIPLE), + Section("Parameters", "param", SectionType.MULTIPLE), + Section("Params", "param", SectionType.MULTIPLE), + Section("Raises", "raises", SectionType.MULTIPLE), + Section("Exceptions", "raises", SectionType.MULTIPLE), + Section("Except", "raises", SectionType.MULTIPLE), + Section("Attributes", "attribute", SectionType.MULTIPLE), + Section("Example", "examples", SectionType.SINGULAR), + Section("Examples", "examples", SectionType.SINGULAR), + Section("Returns", "returns", SectionType.SINGULAR_OR_MULTIPLE), + Section("Yields", "yields", SectionType.SINGULAR_OR_MULTIPLE), +] + + +class GoogleParser: + """Parser for Google-style docstrings.""" + + def __init__( + self, sections: T.Optional[T.List[Section]] = None, title_colon=True + ): + """Setup sections. + + :param sections: Recognized sections or None to defaults. + :param title_colon: require colon after section title. + """ + if not sections: + sections = DEFAULT_SECTIONS + self.sections = {s.title: s for s in sections} + self.title_colon = title_colon + self._setup() + + def _setup(self): + if self.title_colon: + colon = ":" + else: + colon = "" + self.titles_re = re.compile( + "^(" + + "|".join(f"({t})" for t in self.sections) + + ")" + + colon + + "[ \t\r\f\v]*$", + flags=re.M, + ) + + def _build_meta(self, text: str, title: str) -> DocstringMeta: + """Build docstring element. + + :param text: docstring element text + :param title: title of section containing element + :return: + """ + + section = self.sections[title] + + if ( + section.type == SectionType.SINGULAR_OR_MULTIPLE + and not MULTIPLE_PATTERN.match(text) + ) or section.type == SectionType.SINGULAR: + return self._build_single_meta(section, text) + + if ":" not in text: + raise ParseError(f"Expected a colon in {text!r}.") + + # Split spec and description + before, desc = text.split(":", 1) + + if before and "\n" in before: + # If there is a newline in the first line, clean it up + first_line, rest = before.split("\n", 1) + before = first_line + inspect.cleandoc(rest) + + if desc: + desc = desc[1:] if desc[0] == " " else desc + if "\n" in desc: + first_line, rest = desc.split("\n", 1) + desc = first_line + "\n" + inspect.cleandoc(rest) + desc = desc.strip("\n") + + return self._build_multi_meta(section, before, desc) + + @staticmethod + def _build_single_meta(section: Section, desc: str) -> DocstringMeta: + if section.key in RETURNS_KEYWORDS | YIELDS_KEYWORDS: + return DocstringReturns( + args=[section.key], + description=desc, + type_name=None, + is_generator=section.key in YIELDS_KEYWORDS, + ) + if section.key in RAISES_KEYWORDS: + return DocstringRaises( + args=[section.key], description=desc, type_name=None + ) + if section.key in EXAMPLES_KEYWORDS: + return DocstringExample( + args=[section.key], snippet=None, description=desc + ) + if section.key in PARAM_KEYWORDS: + raise ParseError("Expected paramenter name.") + return DocstringMeta(args=[section.key], description=desc) + + @staticmethod + def _build_multi_meta( + section: Section, before: str, desc: str + ) -> DocstringMeta: + if section.key in PARAM_KEYWORDS: + match = GOOGLE_TYPED_ARG_REGEX.match(before) + if match: + arg_name, type_name = match.group(1, 2) + if type_name.endswith(", optional"): + is_optional = True + type_name = type_name[:-10] + elif type_name.endswith("?"): + is_optional = True + type_name = type_name[:-1] + else: + is_optional = False + else: + arg_name, type_name = before, None + is_optional = None + + match = GOOGLE_ARG_DESC_REGEX.match(desc) + default = match.group(1) if match else None + + return DocstringParam( + args=[section.key, before], + description=desc, + arg_name=arg_name, + type_name=type_name, + is_optional=is_optional, + default=default, + ) + if section.key in RETURNS_KEYWORDS | YIELDS_KEYWORDS: + return DocstringReturns( + args=[section.key, before], + description=desc, + type_name=before, + is_generator=section.key in YIELDS_KEYWORDS, + ) + if section.key in RAISES_KEYWORDS: + return DocstringRaises( + args=[section.key, before], description=desc, type_name=before + ) + return DocstringMeta(args=[section.key, before], description=desc) + + def add_section(self, section: Section): + """Add or replace a section. + + :param section: The new section. + """ + + self.sections[section.title] = section + self._setup() + + def parse(self, text: str) -> Docstring: + """Parse the Google-style docstring into its components. + + :returns: parsed docstring + """ + ret = Docstring(style=DocstringStyle.GOOGLE) + if not text: + return ret + + # Clean according to PEP-0257 + text = inspect.cleandoc(text) + + # Find first title and split on its position + match = self.titles_re.search(text) + if match: + desc_chunk = text[: match.start()] + meta_chunk = text[match.start() :] + else: + desc_chunk = text + meta_chunk = "" + + # Break description into short and long parts + parts = desc_chunk.split("\n", 1) + ret.short_description = parts[0] or None + if len(parts) > 1: + long_desc_chunk = parts[1] or "" + ret.blank_after_short_description = long_desc_chunk.startswith( + "\n" + ) + ret.blank_after_long_description = long_desc_chunk.endswith("\n\n") + ret.long_description = long_desc_chunk.strip() or None + + # Split by sections determined by titles + matches = list(self.titles_re.finditer(meta_chunk)) + if not matches: + return ret + splits = [] + for j in range(len(matches) - 1): + splits.append((matches[j].end(), matches[j + 1].start())) + splits.append((matches[-1].end(), len(meta_chunk))) + + chunks = OrderedDict() # type: T.Mapping[str,str] + for j, (start, end) in enumerate(splits): + title = matches[j].group(1) + if title not in self.sections: + continue + + # Clear Any Unknown Meta + # Ref: https://github.com/rr-/docstring_parser/issues/29 + meta_details = meta_chunk[start:end] + unknown_meta = re.search(r"\n\S", meta_details) + if unknown_meta is not None: + meta_details = meta_details[: unknown_meta.start()] + + chunks[title] = meta_details.strip("\n") + if not chunks: + return ret + + # Add elements from each chunk + for title, chunk in chunks.items(): + # Determine indent + indent_match = re.search(r"^\s*", chunk) + if not indent_match: + raise ParseError(f'Can\'t infer indent from "{chunk}"') + indent = indent_match.group() + + # Check for singular elements + if self.sections[title].type in [ + SectionType.SINGULAR, + SectionType.SINGULAR_OR_MULTIPLE, + ]: + part = inspect.cleandoc(chunk) + ret.meta.append(self._build_meta(part, title)) + continue + + # Split based on lines which have exactly that indent + _re = "^" + indent + r"(?=\S)" + c_matches = list(re.finditer(_re, chunk, flags=re.M)) + if not c_matches: + raise ParseError(f'No specification for "{title}": "{chunk}"') + c_splits = [] + for j in range(len(c_matches) - 1): + c_splits.append((c_matches[j].end(), c_matches[j + 1].start())) + c_splits.append((c_matches[-1].end(), len(chunk))) + for j, (start, end) in enumerate(c_splits): + part = chunk[start:end].strip("\n") + ret.meta.append(self._build_meta(part, title)) + + return ret + + +def parse(text: str) -> Docstring: + """Parse the Google-style docstring into its components. + + :returns: parsed docstring + """ + return GoogleParser().parse(text) + + +def compose( + docstring: Docstring, + rendering_style: RenderingStyle = RenderingStyle.COMPACT, + indent: str = " ", +) -> str: + """Render a parsed docstring into docstring text. + + :param docstring: parsed docstring representation + :param rendering_style: the style to render docstrings + :param indent: the characters used as indentation in the docstring string + :returns: docstring text + """ + + def process_one( + one: T.Union[DocstringParam, DocstringReturns, DocstringRaises], + ): + head = "" + + if isinstance(one, DocstringParam): + head += one.arg_name or "" + elif isinstance(one, DocstringReturns): + head += one.return_name or "" + + if isinstance(one, DocstringParam) and one.is_optional: + optional = ( + "?" + if rendering_style == RenderingStyle.COMPACT + else ", optional" + ) + else: + optional = "" + + if one.type_name and head: + head += f" ({one.type_name}{optional}):" + elif one.type_name: + head += f"{one.type_name}{optional}:" + else: + head += ":" + head = indent + head + + if one.description and rendering_style == RenderingStyle.EXPANDED: + body = f"\n{indent}{indent}".join( + [head] + one.description.splitlines() + ) + parts.append(body) + elif one.description: + (first, *rest) = one.description.splitlines() + body = f"\n{indent}{indent}".join([head + " " + first] + rest) + parts.append(body) + else: + parts.append(head) + + def process_sect(name: str, args: T.List[T.Any]): + if args: + parts.append(name) + for arg in args: + process_one(arg) + parts.append("") + + parts: T.List[str] = [] + if docstring.short_description: + parts.append(docstring.short_description) + if docstring.blank_after_short_description: + parts.append("") + + if docstring.long_description: + parts.append(docstring.long_description) + if docstring.blank_after_long_description: + parts.append("") + + process_sect( + "Args:", [p for p in docstring.params or [] if p.args[0] == "param"] + ) + + process_sect( + "Attributes:", + [p for p in docstring.params or [] if p.args[0] == "attribute"], + ) + + process_sect( + "Returns:", + [p for p in docstring.many_returns or [] if not p.is_generator], + ) + + process_sect( + "Yields:", [p for p in docstring.many_returns or [] if p.is_generator] + ) + + process_sect("Raises:", docstring.raises or []) + + if docstring.returns and not docstring.many_returns: + ret = docstring.returns + parts.append("Yields:" if ret else "Returns:") + parts.append("-" * len(parts[-1])) + process_one(ret) + + for meta in docstring.meta: + if isinstance( + meta, (DocstringParam, DocstringReturns, DocstringRaises) + ): + continue # Already handled + parts.append(meta.args[0].replace("_", "").title() + ":") + if meta.description: + lines = [indent + l for l in meta.description.splitlines()] + parts.append("\n".join(lines)) + parts.append("") + + while parts and not parts[-1]: + parts.pop() + + return "\n".join(parts) diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/numpydoc.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/numpydoc.py new file mode 100644 index 0000000000000000000000000000000000000000..836e7766d8faf25e72ec264c4397227fab8d1ffc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/numpydoc.py @@ -0,0 +1,532 @@ +"""Numpydoc-style docstring parsing. + +:see: https://numpydoc.readthedocs.io/en/latest/format.html +""" + +import inspect +import itertools +import re +import typing as T +from textwrap import dedent + +from .common import ( + Docstring, + DocstringDeprecated, + DocstringExample, + DocstringMeta, + DocstringParam, + DocstringRaises, + DocstringReturns, + DocstringStyle, + RenderingStyle, +) + + +def _pairwise(iterable: T.Iterable, end=None) -> T.Iterable: + left, right = itertools.tee(iterable) + next(right, None) + return itertools.zip_longest(left, right, fillvalue=end) + + +def _clean_str(string: str) -> T.Optional[str]: + string = string.strip() + if len(string) > 0: + return string + return None + + +KV_REGEX = re.compile(r"^[^\s].*$", flags=re.M) +PARAM_KEY_REGEX = re.compile(r"^(?P.*?)(?:\s*:\s*(?P.*?))?$") +PARAM_OPTIONAL_REGEX = re.compile(r"(?P.*?)(?:, optional|\(optional\))$") + +# numpydoc format has no formal grammar for this, +# but we can make some educated guesses... +PARAM_DEFAULT_REGEX = re.compile( + r"(?[\w\-\.]*\w)" +) + +RETURN_KEY_REGEX = re.compile(r"^(?:(?P.*?)\s*:\s*)?(?P.*?)$") + + +class Section: + """Numpydoc section parser. + + :param title: section title. For most sections, this is a heading like + "Parameters" which appears on its own line, underlined by + en-dashes ('-') on the following line. + :param key: meta key string. In the parsed ``DocstringMeta`` instance this + will be the first element of the ``args`` attribute list. + """ + + def __init__(self, title: str, key: str) -> None: + self.title = title + self.key = key + + @property + def title_pattern(self) -> str: + """Regular expression pattern matching this section's header. + + This pattern will match this instance's ``title`` attribute in + an anonymous group. + """ + dashes = "-" * len(self.title) + return rf"^({self.title})\s*?\n{dashes}\s*$" + + def parse(self, text: str) -> T.Iterable[DocstringMeta]: + """Parse ``DocstringMeta`` objects from the body of this section. + + :param text: section body text. Should be cleaned with + ``inspect.cleandoc`` before parsing. + """ + yield DocstringMeta([self.key], description=_clean_str(text)) + + +class _KVSection(Section): + """Base parser for numpydoc sections with key-value syntax. + + E.g. sections that look like this: + key + value + key2 : type + values can also span... + ... multiple lines + """ + + def _parse_item(self, key: str, value: str) -> DocstringMeta: + pass + + def parse(self, text: str) -> T.Iterable[DocstringMeta]: + for match, next_match in _pairwise(KV_REGEX.finditer(text)): + start = match.end() + end = next_match.start() if next_match is not None else None + value = text[start:end] + yield self._parse_item( + key=match.group(), value=inspect.cleandoc(value) + ) + + +class _SphinxSection(Section): + """Base parser for numpydoc sections with sphinx-style syntax. + + E.g. sections that look like this: + .. title:: something + possibly over multiple lines + """ + + @property + def title_pattern(self) -> str: + return rf"^\.\.\s*({self.title})\s*::" + + +class ParamSection(_KVSection): + """Parser for numpydoc parameter sections. + + E.g. any section that looks like this: + arg_name + arg_description + arg_2 : type, optional + descriptions can also span... + ... multiple lines + """ + + def _parse_item(self, key: str, value: str) -> DocstringParam: + match = PARAM_KEY_REGEX.match(key) + arg_name = type_name = is_optional = None + if match is not None: + arg_name = match.group("name") + type_name = match.group("type") + if type_name is not None: + optional_match = PARAM_OPTIONAL_REGEX.match(type_name) + if optional_match is not None: + type_name = optional_match.group("type") + is_optional = True + else: + is_optional = False + + default = None + if len(value) > 0: + default_match = PARAM_DEFAULT_REGEX.search(value) + if default_match is not None: + default = default_match.group("value") + + return DocstringParam( + args=[self.key, arg_name], + description=_clean_str(value), + arg_name=arg_name, + type_name=type_name, + is_optional=is_optional, + default=default, + ) + + +class RaisesSection(_KVSection): + """Parser for numpydoc raises sections. + + E.g. any section that looks like this: + ValueError + A description of what might raise ValueError + """ + + def _parse_item(self, key: str, value: str) -> DocstringRaises: + return DocstringRaises( + args=[self.key, key], + description=_clean_str(value), + type_name=key if len(key) > 0 else None, + ) + + +class ReturnsSection(_KVSection): + """Parser for numpydoc returns sections. + + E.g. any section that looks like this: + return_name : type + A description of this returned value + another_type + Return names are optional, types are required + """ + + is_generator = False + + def _parse_item(self, key: str, value: str) -> DocstringReturns: + match = RETURN_KEY_REGEX.match(key) + if match is not None: + return_name = match.group("name") + type_name = match.group("type") + else: + return_name = None + type_name = None + + return DocstringReturns( + args=[self.key], + description=_clean_str(value), + type_name=type_name, + is_generator=self.is_generator, + return_name=return_name, + ) + + +class YieldsSection(ReturnsSection): + """Parser for numpydoc generator "yields" sections.""" + + is_generator = True + + +class DeprecationSection(_SphinxSection): + """Parser for numpydoc "deprecation warning" sections.""" + + def parse(self, text: str) -> T.Iterable[DocstringDeprecated]: + version, desc, *_ = text.split(sep="\n", maxsplit=1) + [None, None] + + if desc is not None: + desc = _clean_str(inspect.cleandoc(desc)) + + yield DocstringDeprecated( + args=[self.key], description=desc, version=_clean_str(version) + ) + + +class ExamplesSection(Section): + """Parser for numpydoc examples sections. + + E.g. any section that looks like this: + >>> import numpy.matlib + >>> np.matlib.empty((2, 2)) # filled with random data + matrix([[ 6.76425276e-320, 9.79033856e-307], # random + [ 7.39337286e-309, 3.22135945e-309]]) + >>> np.matlib.empty((2, 2), dtype=int) + matrix([[ 6600475, 0], # random + [ 6586976, 22740995]]) + """ + + def parse(self, text: str) -> T.Iterable[DocstringMeta]: + """Parse ``DocstringExample`` objects from the body of this section. + + :param text: section body text. Should be cleaned with + ``inspect.cleandoc`` before parsing. + """ + lines = dedent(text).strip().splitlines() + while lines: + snippet_lines = [] + description_lines = [] + while lines: + if not lines[0].startswith(">>>"): + break + snippet_lines.append(lines.pop(0)) + while lines: + if lines[0].startswith(">>>"): + break + description_lines.append(lines.pop(0)) + yield DocstringExample( + [self.key], + snippet="\n".join(snippet_lines) if snippet_lines else None, + description="\n".join(description_lines), + ) + + +DEFAULT_SECTIONS = [ + ParamSection("Parameters", "param"), + ParamSection("Params", "param"), + ParamSection("Arguments", "param"), + ParamSection("Args", "param"), + ParamSection("Other Parameters", "other_param"), + ParamSection("Other Params", "other_param"), + ParamSection("Other Arguments", "other_param"), + ParamSection("Other Args", "other_param"), + ParamSection("Receives", "receives"), + ParamSection("Receive", "receives"), + RaisesSection("Raises", "raises"), + RaisesSection("Raise", "raises"), + RaisesSection("Warns", "warns"), + RaisesSection("Warn", "warns"), + ParamSection("Attributes", "attribute"), + ParamSection("Attribute", "attribute"), + ReturnsSection("Returns", "returns"), + ReturnsSection("Return", "returns"), + YieldsSection("Yields", "yields"), + YieldsSection("Yield", "yields"), + ExamplesSection("Examples", "examples"), + ExamplesSection("Example", "examples"), + Section("Warnings", "warnings"), + Section("Warning", "warnings"), + Section("See Also", "see_also"), + Section("Related", "see_also"), + Section("Notes", "notes"), + Section("Note", "notes"), + Section("References", "references"), + Section("Reference", "references"), + DeprecationSection("deprecated", "deprecation"), +] + + +class NumpydocParser: + """Parser for numpydoc-style docstrings.""" + + def __init__(self, sections: T.Optional[T.Dict[str, Section]] = None): + """Setup sections. + + :param sections: Recognized sections or None to defaults. + """ + sections = sections or DEFAULT_SECTIONS + self.sections = {s.title: s for s in sections} + self._setup() + + def _setup(self): + self.titles_re = re.compile( + r"|".join(s.title_pattern for s in self.sections.values()), + flags=re.M, + ) + + def add_section(self, section: Section): + """Add or replace a section. + + :param section: The new section. + """ + + self.sections[section.title] = section + self._setup() + + def parse(self, text: str) -> Docstring: + """Parse the numpy-style docstring into its components. + + :returns: parsed docstring + """ + ret = Docstring(style=DocstringStyle.NUMPYDOC) + if not text: + return ret + + # Clean according to PEP-0257 + text = inspect.cleandoc(text) + + # Find first title and split on its position + match = self.titles_re.search(text) + if match: + desc_chunk = text[: match.start()] + meta_chunk = text[match.start() :] + else: + desc_chunk = text + meta_chunk = "" + + # Break description into short and long parts + parts = desc_chunk.split("\n", 1) + ret.short_description = parts[0] or None + if len(parts) > 1: + long_desc_chunk = parts[1] or "" + ret.blank_after_short_description = long_desc_chunk.startswith( + "\n" + ) + ret.blank_after_long_description = long_desc_chunk.endswith("\n\n") + ret.long_description = long_desc_chunk.strip() or None + + for match, nextmatch in _pairwise(self.titles_re.finditer(meta_chunk)): + title = next(g for g in match.groups() if g is not None) + factory = self.sections[title] + + # section chunk starts after the header, + # ends at the start of the next header + start = match.end() + end = nextmatch.start() if nextmatch is not None else None + ret.meta.extend(factory.parse(meta_chunk[start:end])) + + return ret + + +def parse(text: str) -> Docstring: + """Parse the numpy-style docstring into its components. + + :returns: parsed docstring + """ + return NumpydocParser().parse(text) + + +def compose( + # pylint: disable=W0613 + docstring: Docstring, + rendering_style: RenderingStyle = RenderingStyle.COMPACT, + indent: str = " ", +) -> str: + """Render a parsed docstring into docstring text. + + :param docstring: parsed docstring representation + :param rendering_style: the style to render docstrings + :param indent: the characters used as indentation in the docstring string + :returns: docstring text + """ + + def process_one( + one: T.Union[DocstringParam, DocstringReturns, DocstringRaises], + ): + if isinstance(one, DocstringParam): + head = one.arg_name + elif isinstance(one, DocstringReturns): + head = one.return_name + else: + head = None + + if one.type_name and head: + head += f" : {one.type_name}" + elif one.type_name: + head = one.type_name + elif not head: + head = "" + + if isinstance(one, DocstringParam) and one.is_optional: + head += ", optional" + + if one.description: + body = f"\n{indent}".join([head] + one.description.splitlines()) + parts.append(body) + else: + parts.append(head) + + def process_sect(name: str, args: T.List[T.Any]): + if args: + parts.append("") + parts.append(name) + parts.append("-" * len(parts[-1])) + for arg in args: + process_one(arg) + + parts: T.List[str] = [] + if docstring.short_description: + parts.append(docstring.short_description) + if docstring.blank_after_short_description: + parts.append("") + + if docstring.deprecation: + first = ".. deprecated::" + if docstring.deprecation.version: + first += f" {docstring.deprecation.version}" + if docstring.deprecation.description: + rest = docstring.deprecation.description.splitlines() + else: + rest = [] + sep = f"\n{indent}" + parts.append(sep.join([first] + rest)) + + if docstring.long_description: + parts.append(docstring.long_description) + if docstring.blank_after_long_description: + parts.append("") + + process_sect( + "Parameters", + [item for item in docstring.params or [] if item.args[0] == "param"], + ) + + process_sect( + "Attributes", + [ + item + for item in docstring.params or [] + if item.args[0] == "attribute" + ], + ) + + process_sect( + "Returns", + [ + item + for item in docstring.many_returns or [] + if not item.is_generator + ], + ) + + process_sect( + "Yields", + [item for item in docstring.many_returns or [] if item.is_generator], + ) + + if docstring.returns and not docstring.many_returns: + ret = docstring.returns + parts.append("Yields" if ret else "Returns") + parts.append("-" * len(parts[-1])) + process_one(ret) + + process_sect( + "Receives", + [ + item + for item in docstring.params or [] + if item.args[0] == "receives" + ], + ) + + process_sect( + "Other Parameters", + [ + item + for item in docstring.params or [] + if item.args[0] == "other_param" + ], + ) + + process_sect( + "Raises", + [item for item in docstring.raises or [] if item.args[0] == "raises"], + ) + + process_sect( + "Warns", + [item for item in docstring.raises or [] if item.args[0] == "warns"], + ) + + for meta in docstring.meta: + if isinstance( + meta, + ( + DocstringDeprecated, + DocstringParam, + DocstringReturns, + DocstringRaises, + ), + ): + continue # Already handled + + parts.append("") + parts.append(meta.args[0].replace("_", "").title()) + parts.append("-" * len(meta.args[0])) + + if meta.description: + parts.append(meta.description) + + return "\n".join(parts) diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/parser.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..2710e6330da4180d2e20890692f79812fb771024 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/parser.py @@ -0,0 +1,98 @@ +"""The main parsing routine.""" + +import inspect +import typing as T + +from docstring_parser import epydoc, google, numpydoc, rest +from docstring_parser.attrdoc import add_attribute_docstrings +from docstring_parser.common import ( + Docstring, + DocstringStyle, + ParseError, + RenderingStyle, +) + +_STYLE_MAP = { + DocstringStyle.REST: rest, + DocstringStyle.GOOGLE: google, + DocstringStyle.NUMPYDOC: numpydoc, + DocstringStyle.EPYDOC: epydoc, +} + + +def parse(text: str, style: DocstringStyle = DocstringStyle.AUTO) -> Docstring: + """Parse the docstring into its components. + + :param text: docstring text to parse + :param style: docstring style + :returns: parsed docstring representation + """ + if style != DocstringStyle.AUTO: + return _STYLE_MAP[style].parse(text) + + exc: T.Optional[Exception] = None + rets = [] + for module in _STYLE_MAP.values(): + try: + ret = module.parse(text) + except ParseError as ex: + exc = ex + else: + rets.append(ret) + + if not rets: + raise exc + + return sorted(rets, key=lambda d: len(d.meta), reverse=True)[0] + + +def parse_from_object( + obj: T.Any, + style: DocstringStyle = DocstringStyle.AUTO, +) -> Docstring: + """Parse the object's docstring(s) into its components. + + The object can be anything that has a ``__doc__`` attribute. In contrast to + the ``parse`` function, ``parse_from_object`` is able to parse attribute + docstrings which are defined in the source code instead of ``__doc__``. + + Currently only attribute docstrings defined at class and module levels are + supported. Attribute docstrings defined in ``__init__`` methods are not + supported. + + When given a class, only the attribute docstrings of that class are parsed, + not its inherited classes. This is a design decision. Separate calls to + this function should be performed to get attribute docstrings of parent + classes. + + :param obj: object from which to parse the docstring(s) + :param style: docstring style + :returns: parsed docstring representation + """ + docstring = parse(obj.__doc__, style=style) + + if inspect.isclass(obj) or inspect.ismodule(obj): + add_attribute_docstrings(obj, docstring) + + return docstring + + +def compose( + docstring: Docstring, + style: DocstringStyle = DocstringStyle.AUTO, + rendering_style: RenderingStyle = RenderingStyle.COMPACT, + indent: str = " ", +) -> str: + """Render a parsed docstring into docstring text. + + :param docstring: parsed docstring representation + :param style: docstring style to render + :param indent: the characters used as indentation in the docstring string + :returns: docstring text + """ + module = _STYLE_MAP[ + docstring.style if style == DocstringStyle.AUTO else style + ] + return module.compose( + docstring, rendering_style=rendering_style, indent=indent + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/py.typed b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..1242d43277017748bbbf3d0a104ec4cf78245822 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/rest.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..b707df87895c0517aa395d586c512ea35a75281f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/rest.py @@ -0,0 +1,259 @@ +"""ReST-style docstring parsing.""" + +import inspect +import re +import typing as T + +from .common import ( + DEPRECATION_KEYWORDS, + PARAM_KEYWORDS, + RAISES_KEYWORDS, + RETURNS_KEYWORDS, + YIELDS_KEYWORDS, + Docstring, + DocstringDeprecated, + DocstringMeta, + DocstringParam, + DocstringRaises, + DocstringReturns, + DocstringStyle, + ParseError, + RenderingStyle, +) + + +def _build_meta(args: T.List[str], desc: str) -> DocstringMeta: + key = args[0] + + if key in PARAM_KEYWORDS: + if len(args) == 3: + key, type_name, arg_name = args + if type_name.endswith("?"): + is_optional = True + type_name = type_name[:-1] + else: + is_optional = False + elif len(args) == 2: + key, arg_name = args + type_name = None + is_optional = None + else: + raise ParseError( + f"Expected one or two arguments for a {key} keyword." + ) + + match = re.match(r".*defaults to (.+)", desc, flags=re.DOTALL) + default = match.group(1).rstrip(".") if match else None + + return DocstringParam( + args=args, + description=desc, + arg_name=arg_name, + type_name=type_name, + is_optional=is_optional, + default=default, + ) + + if key in RETURNS_KEYWORDS | YIELDS_KEYWORDS: + if len(args) == 2: + type_name = args[1] + elif len(args) == 1: + type_name = None + else: + raise ParseError( + f"Expected one or no arguments for a {key} keyword." + ) + + return DocstringReturns( + args=args, + description=desc, + type_name=type_name, + is_generator=key in YIELDS_KEYWORDS, + ) + + if key in DEPRECATION_KEYWORDS: + match = re.search( + r"^(?Pv?((?:\d+)(?:\.[0-9a-z\.]+))) (?P.+)", + desc, + flags=re.I, + ) + return DocstringDeprecated( + args=args, + version=match.group("version") if match else None, + description=match.group("desc") if match else desc, + ) + + if key in RAISES_KEYWORDS: + if len(args) == 2: + type_name = args[1] + elif len(args) == 1: + type_name = None + else: + raise ParseError( + f"Expected one or no arguments for a {key} keyword." + ) + return DocstringRaises( + args=args, description=desc, type_name=type_name + ) + + return DocstringMeta(args=args, description=desc) + + +def parse(text: str) -> Docstring: + """Parse the ReST-style docstring into its components. + + :returns: parsed docstring + """ + ret = Docstring(style=DocstringStyle.REST) + if not text: + return ret + + text = inspect.cleandoc(text) + match = re.search("^:", text, flags=re.M) + if match: + desc_chunk = text[: match.start()] + meta_chunk = text[match.start() :] + else: + desc_chunk = text + meta_chunk = "" + + parts = desc_chunk.split("\n", 1) + ret.short_description = parts[0] or None + if len(parts) > 1: + long_desc_chunk = parts[1] or "" + ret.blank_after_short_description = long_desc_chunk.startswith("\n") + ret.blank_after_long_description = long_desc_chunk.endswith("\n\n") + ret.long_description = long_desc_chunk.strip() or None + + types = {} + rtypes = {} + for match in re.finditer( + r"(^:.*?)(?=^:|\Z)", meta_chunk, flags=re.S | re.M + ): + chunk = match.group(0) + if not chunk: + continue + try: + args_chunk, desc_chunk = chunk.lstrip(":").split(":", 1) + except ValueError as ex: + raise ParseError( + f'Error parsing meta information near "{chunk}".' + ) from ex + args = args_chunk.split() + desc = desc_chunk.strip() + + if "\n" in desc: + first_line, rest = desc.split("\n", 1) + desc = first_line + "\n" + inspect.cleandoc(rest) + + # Add special handling for :type a: typename + if len(args) == 2 and args[0] == "type": + types[args[1]] = desc + elif len(args) in [1, 2] and args[0] == "rtype": + rtypes[None if len(args) == 1 else args[1]] = desc + else: + ret.meta.append(_build_meta(args, desc)) + + for meta in ret.meta: + if isinstance(meta, DocstringParam): + meta.type_name = meta.type_name or types.get(meta.arg_name) + elif isinstance(meta, DocstringReturns): + meta.type_name = meta.type_name or rtypes.get(meta.return_name) + + if not any(isinstance(m, DocstringReturns) for m in ret.meta) and rtypes: + for return_name, type_name in rtypes.items(): + ret.meta.append( + DocstringReturns( + args=[], + type_name=type_name, + description=None, + is_generator=False, + return_name=return_name, + ) + ) + + return ret + + +def compose( + docstring: Docstring, + rendering_style: RenderingStyle = RenderingStyle.COMPACT, + indent: str = " ", +) -> str: + """Render a parsed docstring into docstring text. + + :param docstring: parsed docstring representation + :param rendering_style: the style to render docstrings + :param indent: the characters used as indentation in the docstring string + :returns: docstring text + """ + + def process_desc(desc: T.Optional[str]) -> str: + if not desc: + return "" + + if rendering_style == RenderingStyle.CLEAN: + (first, *rest) = desc.splitlines() + return "\n".join([" " + first] + [indent + line for line in rest]) + + if rendering_style == RenderingStyle.EXPANDED: + (first, *rest) = desc.splitlines() + return "\n".join( + ["\n" + indent + first] + [indent + line for line in rest] + ) + + return " " + desc + + parts: T.List[str] = [] + if docstring.short_description: + parts.append(docstring.short_description) + if docstring.blank_after_short_description: + parts.append("") + if docstring.long_description: + parts.append(docstring.long_description) + if docstring.blank_after_long_description: + parts.append("") + + for meta in docstring.meta: + if isinstance(meta, DocstringParam): + if meta.type_name: + type_text = ( + f" {meta.type_name}? " + if meta.is_optional + else f" {meta.type_name} " + ) + else: + type_text = " " + if rendering_style == RenderingStyle.EXPANDED: + text = f":param {meta.arg_name}:" + text += process_desc(meta.description) + parts.append(text) + if type_text[:-1]: + parts.append(f":type {meta.arg_name}:{type_text[:-1]}") + else: + text = f":param{type_text}{meta.arg_name}:" + text += process_desc(meta.description) + parts.append(text) + elif isinstance(meta, DocstringReturns): + type_text = f" {meta.type_name}" if meta.type_name else "" + key = "yields" if meta.is_generator else "returns" + + if rendering_style == RenderingStyle.EXPANDED: + if meta.description: + text = f":{key}:" + text += process_desc(meta.description) + parts.append(text) + if type_text: + parts.append(f":rtype:{type_text}") + else: + text = f":{key}{type_text}:" + text += process_desc(meta.description) + parts.append(text) + elif isinstance(meta, DocstringRaises): + type_text = f" {meta.type_name} " if meta.type_name else "" + text = f":raises{type_text}:" + process_desc(meta.description) + parts.append(text) + else: + text = f':{" ".join(meta.args)}:' + process_desc(meta.description) + parts.append(text) + return "\n".join(parts) diff --git a/data/miniconda3/lib/python3.13/site-packages/docstring_parser/util.py b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/util.py new file mode 100644 index 0000000000000000000000000000000000000000..c5be2f5728d40522b23a02a72b1db8ce0da82cb4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/docstring_parser/util.py @@ -0,0 +1,145 @@ +"""Utility functions for working with docstrings.""" + +import typing as T +from collections import ChainMap +from inspect import Signature +from itertools import chain + +from .common import ( + DocstringMeta, + DocstringParam, + DocstringReturns, + DocstringStyle, + RenderingStyle, +) +from .parser import compose, parse + +_Func = T.Callable[..., T.Any] + +assert DocstringReturns # used in docstring + + +def combine_docstrings( + *others: _Func, + exclude: T.Iterable[T.Type[DocstringMeta]] = (), + style: DocstringStyle = DocstringStyle.AUTO, + rendering_style: RenderingStyle = RenderingStyle.COMPACT, +) -> _Func: + """A function decorator that parses the docstrings from `others`, + programmatically combines them with the parsed docstring of the decorated + function, and replaces the docstring of the decorated function with the + composed result. Only parameters that are part of the decorated functions + signature are included in the combined docstring. When multiple sources for + a parameter or docstring metadata exists then the decorator will first + default to the wrapped function's value (when available) and otherwise use + the rightmost definition from ``others``. + + The following example illustrates its usage: + + >>> def fun1(a, b, c, d): + ... '''short_description: fun1 + ... + ... :param a: fun1 + ... :param b: fun1 + ... :return: fun1 + ... ''' + >>> def fun2(b, c, d, e): + ... '''short_description: fun2 + ... + ... long_description: fun2 + ... + ... :param b: fun2 + ... :param c: fun2 + ... :param e: fun2 + ... ''' + >>> @combine_docstrings(fun1, fun2) + >>> def decorated(a, b, c, d, e, f): + ... ''' + ... :param e: decorated + ... :param f: decorated + ... ''' + >>> print(decorated.__doc__) + short_description: fun2 + + long_description: fun2 + + :param a: fun1 + :param b: fun1 + :param c: fun2 + :param e: fun2 + :param f: decorated + :returns: fun1 + >>> @combine_docstrings(fun1, fun2, exclude=[DocstringReturns]) + >>> def decorated(a, b, c, d, e, f): pass + >>> print(decorated.__doc__) + short_description: fun2 + + long_description: fun2 + + :param a: fun1 + :param b: fun1 + :param c: fun2 + :param e: fun2 + + :param others: callables from which to parse docstrings. + :param exclude: an iterable of ``DocstringMeta`` subclasses to exclude when + combining docstrings. + :param style: style composed docstring. The default will infer the style + from the decorated function. + :param rendering_style: The rendering style used to compose a docstring. + :return: the decorated function with a modified docstring. + """ + + def wrapper(func: _Func) -> _Func: + sig = Signature.from_callable(func) + + comb_doc = parse(func.__doc__ or "") + docs = [parse(other.__doc__ or "") for other in others] + [comb_doc] + params = dict( + ChainMap( + *( + {param.arg_name: param for param in doc.params} + for doc in docs + ) + ) + ) + + for doc in reversed(docs): + if not doc.short_description: + continue + comb_doc.short_description = doc.short_description + comb_doc.blank_after_short_description = ( + doc.blank_after_short_description + ) + break + + for doc in reversed(docs): + if not doc.long_description: + continue + comb_doc.long_description = doc.long_description + comb_doc.blank_after_long_description = ( + doc.blank_after_long_description + ) + break + + combined = {} + for doc in docs: + metas = {} + for meta in doc.meta: + meta_type = type(meta) + if meta_type in exclude: + continue + metas.setdefault(meta_type, []).append(meta) + for meta_type, meta in metas.items(): + combined[meta_type] = meta + + combined[DocstringParam] = [ + params[name] for name in sig.parameters if name in params + ] + comb_doc.meta = list(chain(*combined.values())) + func.__doc__ = compose( + comb_doc, style=style, rendering_style=rendering_style + ) + return func + + return wrapper diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/__init__.py b/data/miniconda3/lib/python3.13/site-packages/dotenv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f4c631ba11786bceebd22591f91bd378d8b232c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/__init__.py @@ -0,0 +1,49 @@ +from typing import Any, Optional + +from .main import (dotenv_values, find_dotenv, get_key, load_dotenv, set_key, + unset_key) + + +def load_ipython_extension(ipython: Any) -> None: + from .ipython import load_ipython_extension + load_ipython_extension(ipython) + + +def get_cli_string( + path: Optional[str] = None, + action: Optional[str] = None, + key: Optional[str] = None, + value: Optional[str] = None, + quote: Optional[str] = None, +): + """Returns a string suitable for running as a shell script. + + Useful for converting a arguments passed to a fabric task + to be passed to a `local` or `run` command. + """ + command = ['dotenv'] + if quote: + command.append(f'-q {quote}') + if path: + command.append(f'-f {path}') + if action: + command.append(action) + if key: + command.append(key) + if value: + if ' ' in value: + command.append(f'"{value}"') + else: + command.append(value) + + return ' '.join(command).strip() + + +__all__ = ['get_cli_string', + 'load_dotenv', + 'dotenv_values', + 'get_key', + 'set_key', + 'unset_key', + 'find_dotenv', + 'load_ipython_extension'] diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/__main__.py b/data/miniconda3/lib/python3.13/site-packages/dotenv/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..3977f55a8b1e94e67bab364885e502e6c89e3bc5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/__main__.py @@ -0,0 +1,6 @@ +"""Entry point for cli, enables execution with `python -m dotenv`""" + +from .cli import cli + +if __name__ == "__main__": + cli() diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/cli.py b/data/miniconda3/lib/python3.13/site-packages/dotenv/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..33ae148531288a108d78abeea4532c1663ec7432 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/cli.py @@ -0,0 +1,190 @@ +import json +import os +import shlex +import sys +from contextlib import contextmanager +from typing import Any, Dict, IO, Iterator, List, Optional + +try: + import click +except ImportError: + sys.stderr.write('It seems python-dotenv is not installed with cli option. \n' + 'Run pip install "python-dotenv[cli]" to fix this.') + sys.exit(1) + +from .main import dotenv_values, set_key, unset_key +from .version import __version__ + + +def enumerate_env() -> Optional[str]: + """ + Return a path for the ${pwd}/.env file. + + If pwd does not exist, return None. + """ + try: + cwd = os.getcwd() + except FileNotFoundError: + return None + path = os.path.join(cwd, '.env') + return path + + +@click.group() +@click.option('-f', '--file', default=enumerate_env(), + type=click.Path(file_okay=True), + help="Location of the .env file, defaults to .env file in current working directory.") +@click.option('-q', '--quote', default='always', + type=click.Choice(['always', 'never', 'auto']), + help="Whether to quote or not the variable values. Default mode is always. This does not affect parsing.") +@click.option('-e', '--export', default=False, + type=click.BOOL, + help="Whether to write the dot file as an executable bash script.") +@click.version_option(version=__version__) +@click.pass_context +def cli(ctx: click.Context, file: Any, quote: Any, export: Any) -> None: + """This script is used to set, get or unset values from a .env file.""" + ctx.obj = {'QUOTE': quote, 'EXPORT': export, 'FILE': file} + + +@contextmanager +def stream_file(path: os.PathLike) -> Iterator[IO[str]]: + """ + Open a file and yield the corresponding (decoded) stream. + + Exits with error code 2 if the file cannot be opened. + """ + + try: + with open(path) as stream: + yield stream + except OSError as exc: + print(f"Error opening env file: {exc}", file=sys.stderr) + exit(2) + + +@cli.command() +@click.pass_context +@click.option('--format', default='simple', + type=click.Choice(['simple', 'json', 'shell', 'export']), + help="The format in which to display the list. Default format is simple, " + "which displays name=value without quotes.") +def list(ctx: click.Context, format: bool) -> None: + """Display all the stored key/value.""" + file = ctx.obj['FILE'] + + with stream_file(file) as stream: + values = dotenv_values(stream=stream) + + if format == 'json': + click.echo(json.dumps(values, indent=2, sort_keys=True)) + else: + prefix = 'export ' if format == 'export' else '' + for k in sorted(values): + v = values[k] + if v is not None: + if format in ('export', 'shell'): + v = shlex.quote(v) + click.echo(f'{prefix}{k}={v}') + + +@cli.command() +@click.pass_context +@click.argument('key', required=True) +@click.argument('value', required=True) +def set(ctx: click.Context, key: Any, value: Any) -> None: + """Store the given key/value.""" + file = ctx.obj['FILE'] + quote = ctx.obj['QUOTE'] + export = ctx.obj['EXPORT'] + success, key, value = set_key(file, key, value, quote, export) + if success: + click.echo(f'{key}={value}') + else: + exit(1) + + +@cli.command() +@click.pass_context +@click.argument('key', required=True) +def get(ctx: click.Context, key: Any) -> None: + """Retrieve the value for the given key.""" + file = ctx.obj['FILE'] + + with stream_file(file) as stream: + values = dotenv_values(stream=stream) + + stored_value = values.get(key) + if stored_value: + click.echo(stored_value) + else: + exit(1) + + +@cli.command() +@click.pass_context +@click.argument('key', required=True) +def unset(ctx: click.Context, key: Any) -> None: + """Removes the given key.""" + file = ctx.obj['FILE'] + quote = ctx.obj['QUOTE'] + success, key = unset_key(file, key, quote) + if success: + click.echo(f"Successfully removed {key}") + else: + exit(1) + + +@cli.command(context_settings={'ignore_unknown_options': True}) +@click.pass_context +@click.option( + "--override/--no-override", + default=True, + help="Override variables from the environment file with those from the .env file.", +) +@click.argument('commandline', nargs=-1, type=click.UNPROCESSED) +def run(ctx: click.Context, override: bool, commandline: List[str]) -> None: + """Run command with environment variables present.""" + file = ctx.obj['FILE'] + if not os.path.isfile(file): + raise click.BadParameter( + f'Invalid value for \'-f\' "{file}" does not exist.', + ctx=ctx + ) + dotenv_as_dict = { + k: v + for (k, v) in dotenv_values(file).items() + if v is not None and (override or k not in os.environ) + } + + if not commandline: + click.echo('No command given.') + exit(1) + run_command(commandline, dotenv_as_dict) + + +def run_command(command: List[str], env: Dict[str, str]) -> None: + """Replace the current process with the specified command. + + Replaces the current process with the specified command and the variables from `env` + added in the current environment variables. + + Parameters + ---------- + command: List[str] + The command and it's parameters + env: Dict + The additional environment variables + + Returns + ------- + None + This function does not return any value. It replaces the current process with the new one. + + """ + # copy the current environment variables and add the vales from + # `env` + cmd_env = os.environ.copy() + cmd_env.update(env) + + os.execvpe(command[0], args=command, env=cmd_env) diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/ipython.py b/data/miniconda3/lib/python3.13/site-packages/dotenv/ipython.py new file mode 100644 index 0000000000000000000000000000000000000000..7df727cd0ba5eb481a9e2568ffdd063bfce90314 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/ipython.py @@ -0,0 +1,39 @@ +from IPython.core.magic import Magics, line_magic, magics_class # type: ignore +from IPython.core.magic_arguments import (argument, magic_arguments, # type: ignore + parse_argstring) # type: ignore + +from .main import find_dotenv, load_dotenv + + +@magics_class +class IPythonDotEnv(Magics): + + @magic_arguments() + @argument( + '-o', '--override', action='store_true', + help="Indicate to override existing variables" + ) + @argument( + '-v', '--verbose', action='store_true', + help="Indicate function calls to be verbose" + ) + @argument('dotenv_path', nargs='?', type=str, default='.env', + help='Search in increasingly higher folders for the `dotenv_path`') + @line_magic + def dotenv(self, line): + args = parse_argstring(self.dotenv, line) + # Locate the .env file + dotenv_path = args.dotenv_path + try: + dotenv_path = find_dotenv(dotenv_path, True, True) + except IOError: + print("cannot find .env file") + return + + # Load the .env file + load_dotenv(dotenv_path, verbose=args.verbose, override=args.override) + + +def load_ipython_extension(ipython): + """Register the %dotenv magic.""" + ipython.register_magics(IPythonDotEnv) diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/main.py b/data/miniconda3/lib/python3.13/site-packages/dotenv/main.py new file mode 100644 index 0000000000000000000000000000000000000000..1848d602bb7f886df48868827679d5f3eba71939 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/main.py @@ -0,0 +1,398 @@ +import io +import logging +import os +import pathlib +import shutil +import sys +import tempfile +from collections import OrderedDict +from contextlib import contextmanager +from typing import IO, Dict, Iterable, Iterator, Mapping, Optional, Tuple, Union + +from .parser import Binding, parse_stream +from .variables import parse_variables + +# A type alias for a string path to be used for the paths in this file. +# These paths may flow to `open()` and `shutil.move()`; `shutil.move()` +# only accepts string paths, not byte paths or file descriptors. See +# https://github.com/python/typeshed/pull/6832. +StrPath = Union[str, "os.PathLike[str]"] + +logger = logging.getLogger(__name__) + + +def with_warn_for_invalid_lines(mappings: Iterator[Binding]) -> Iterator[Binding]: + for mapping in mappings: + if mapping.error: + logger.warning( + "python-dotenv could not parse statement starting at line %s", + mapping.original.line, + ) + yield mapping + + +class DotEnv: + def __init__( + self, + dotenv_path: Optional[StrPath], + stream: Optional[IO[str]] = None, + verbose: bool = False, + encoding: Optional[str] = None, + interpolate: bool = True, + override: bool = True, + ) -> None: + self.dotenv_path: Optional[StrPath] = dotenv_path + self.stream: Optional[IO[str]] = stream + self._dict: Optional[Dict[str, Optional[str]]] = None + self.verbose: bool = verbose + self.encoding: Optional[str] = encoding + self.interpolate: bool = interpolate + self.override: bool = override + + @contextmanager + def _get_stream(self) -> Iterator[IO[str]]: + if self.dotenv_path and os.path.isfile(self.dotenv_path): + with open(self.dotenv_path, encoding=self.encoding) as stream: + yield stream + elif self.stream is not None: + yield self.stream + else: + if self.verbose: + logger.info( + "python-dotenv could not find configuration file %s.", + self.dotenv_path or ".env", + ) + yield io.StringIO("") + + def dict(self) -> Dict[str, Optional[str]]: + """Return dotenv as dict""" + if self._dict: + return self._dict + + raw_values = self.parse() + + if self.interpolate: + self._dict = OrderedDict( + resolve_variables(raw_values, override=self.override) + ) + else: + self._dict = OrderedDict(raw_values) + + return self._dict + + def parse(self) -> Iterator[Tuple[str, Optional[str]]]: + with self._get_stream() as stream: + for mapping in with_warn_for_invalid_lines(parse_stream(stream)): + if mapping.key is not None: + yield mapping.key, mapping.value + + def set_as_environment_variables(self) -> bool: + """ + Load the current dotenv as system environment variable. + """ + if not self.dict(): + return False + + for k, v in self.dict().items(): + if k in os.environ and not self.override: + continue + if v is not None: + os.environ[k] = v + + return True + + def get(self, key: str) -> Optional[str]: + """ """ + data = self.dict() + + if key in data: + return data[key] + + if self.verbose: + logger.warning("Key %s not found in %s.", key, self.dotenv_path) + + return None + + +def get_key( + dotenv_path: StrPath, + key_to_get: str, + encoding: Optional[str] = "utf-8", +) -> Optional[str]: + """ + Get the value of a given key from the given .env. + + Returns `None` if the key isn't found or doesn't have a value. + """ + return DotEnv(dotenv_path, verbose=True, encoding=encoding).get(key_to_get) + + +@contextmanager +def rewrite( + path: StrPath, + encoding: Optional[str], +) -> Iterator[Tuple[IO[str], IO[str]]]: + pathlib.Path(path).touch() + + with tempfile.NamedTemporaryFile(mode="w", encoding=encoding, delete=False) as dest: + error = None + try: + with open(path, encoding=encoding) as source: + yield (source, dest) + except BaseException as err: + error = err + + if error is None: + shutil.move(dest.name, path) + else: + os.unlink(dest.name) + raise error from None + + +def set_key( + dotenv_path: StrPath, + key_to_set: str, + value_to_set: str, + quote_mode: str = "always", + export: bool = False, + encoding: Optional[str] = "utf-8", +) -> Tuple[Optional[bool], str, str]: + """ + Adds or Updates a key/value to the given .env + + If the .env path given doesn't exist, fails instead of risking creating + an orphan .env somewhere in the filesystem + """ + if quote_mode not in ("always", "auto", "never"): + raise ValueError(f"Unknown quote_mode: {quote_mode}") + + quote = quote_mode == "always" or ( + quote_mode == "auto" and not value_to_set.isalnum() + ) + + if quote: + value_out = "'{}'".format(value_to_set.replace("'", "\\'")) + else: + value_out = value_to_set + if export: + line_out = f"export {key_to_set}={value_out}\n" + else: + line_out = f"{key_to_set}={value_out}\n" + + with rewrite(dotenv_path, encoding=encoding) as (source, dest): + replaced = False + missing_newline = False + for mapping in with_warn_for_invalid_lines(parse_stream(source)): + if mapping.key == key_to_set: + dest.write(line_out) + replaced = True + else: + dest.write(mapping.original.string) + missing_newline = not mapping.original.string.endswith("\n") + if not replaced: + if missing_newline: + dest.write("\n") + dest.write(line_out) + + return True, key_to_set, value_to_set + + +def unset_key( + dotenv_path: StrPath, + key_to_unset: str, + quote_mode: str = "always", + encoding: Optional[str] = "utf-8", +) -> Tuple[Optional[bool], str]: + """ + Removes a given key from the given `.env` file. + + If the .env path given doesn't exist, fails. + If the given key doesn't exist in the .env, fails. + """ + if not os.path.exists(dotenv_path): + logger.warning("Can't delete from %s - it doesn't exist.", dotenv_path) + return None, key_to_unset + + removed = False + with rewrite(dotenv_path, encoding=encoding) as (source, dest): + for mapping in with_warn_for_invalid_lines(parse_stream(source)): + if mapping.key == key_to_unset: + removed = True + else: + dest.write(mapping.original.string) + + if not removed: + logger.warning( + "Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path + ) + return None, key_to_unset + + return removed, key_to_unset + + +def resolve_variables( + values: Iterable[Tuple[str, Optional[str]]], + override: bool, +) -> Mapping[str, Optional[str]]: + new_values: Dict[str, Optional[str]] = {} + + for name, value in values: + if value is None: + result = None + else: + atoms = parse_variables(value) + env: Dict[str, Optional[str]] = {} + if override: + env.update(os.environ) # type: ignore + env.update(new_values) + else: + env.update(new_values) + env.update(os.environ) # type: ignore + result = "".join(atom.resolve(env) for atom in atoms) + + new_values[name] = result + + return new_values + + +def _walk_to_root(path: str) -> Iterator[str]: + """ + Yield directories starting from the given directory up to the root + """ + if not os.path.exists(path): + raise IOError("Starting path not found") + + if os.path.isfile(path): + path = os.path.dirname(path) + + last_dir = None + current_dir = os.path.abspath(path) + while last_dir != current_dir: + yield current_dir + parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir)) + last_dir, current_dir = current_dir, parent_dir + + +def find_dotenv( + filename: str = ".env", + raise_error_if_not_found: bool = False, + usecwd: bool = False, +) -> str: + """ + Search in increasingly higher folders for the given file + + Returns path to the file if found, or an empty string otherwise + """ + + def _is_interactive(): + """Decide whether this is running in a REPL or IPython notebook""" + try: + main = __import__("__main__", None, None, fromlist=["__file__"]) + except ModuleNotFoundError: + return False + return not hasattr(main, "__file__") + + def _is_debugger(): + return sys.gettrace() is not None + + if usecwd or _is_interactive() or _is_debugger() or getattr(sys, "frozen", False): + # Should work without __file__, e.g. in REPL or IPython notebook. + path = os.getcwd() + else: + # will work for .py files + frame = sys._getframe() + current_file = __file__ + + while frame.f_code.co_filename == current_file or not os.path.exists( + frame.f_code.co_filename + ): + assert frame.f_back is not None + frame = frame.f_back + frame_filename = frame.f_code.co_filename + path = os.path.dirname(os.path.abspath(frame_filename)) + + for dirname in _walk_to_root(path): + check_path = os.path.join(dirname, filename) + if os.path.isfile(check_path): + return check_path + + if raise_error_if_not_found: + raise IOError("File not found") + + return "" + + +def load_dotenv( + dotenv_path: Optional[StrPath] = None, + stream: Optional[IO[str]] = None, + verbose: bool = False, + override: bool = False, + interpolate: bool = True, + encoding: Optional[str] = "utf-8", +) -> bool: + """Parse a .env file and then load all the variables found as environment variables. + + Parameters: + dotenv_path: Absolute or relative path to .env file. + stream: Text stream (such as `io.StringIO`) with .env content, used if + `dotenv_path` is `None`. + verbose: Whether to output a warning the .env file is missing. + override: Whether to override the system environment variables with the variables + from the `.env` file. + encoding: Encoding to be used to read the file. + Returns: + Bool: True if at least one environment variable is set else False + + If both `dotenv_path` and `stream` are `None`, `find_dotenv()` is used to find the + .env file with it's default parameters. If you need to change the default parameters + of `find_dotenv()`, you can explicitly call `find_dotenv()` and pass the result + to this function as `dotenv_path`. + """ + if dotenv_path is None and stream is None: + dotenv_path = find_dotenv() + + dotenv = DotEnv( + dotenv_path=dotenv_path, + stream=stream, + verbose=verbose, + interpolate=interpolate, + override=override, + encoding=encoding, + ) + return dotenv.set_as_environment_variables() + + +def dotenv_values( + dotenv_path: Optional[StrPath] = None, + stream: Optional[IO[str]] = None, + verbose: bool = False, + interpolate: bool = True, + encoding: Optional[str] = "utf-8", +) -> Dict[str, Optional[str]]: + """ + Parse a .env file and return its content as a dict. + + The returned dict will have `None` values for keys without values in the .env file. + For example, `foo=bar` results in `{"foo": "bar"}` whereas `foo` alone results in + `{"foo": None}` + + Parameters: + dotenv_path: Absolute or relative path to the .env file. + stream: `StringIO` object with .env content, used if `dotenv_path` is `None`. + verbose: Whether to output a warning if the .env file is missing. + encoding: Encoding to be used to read the file. + + If both `dotenv_path` and `stream` are `None`, `find_dotenv()` is used to find the + .env file. + """ + if dotenv_path is None and stream is None: + dotenv_path = find_dotenv() + + return DotEnv( + dotenv_path=dotenv_path, + stream=stream, + verbose=verbose, + interpolate=interpolate, + override=True, + encoding=encoding, + ).dict() diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/parser.py b/data/miniconda3/lib/python3.13/site-packages/dotenv/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..735f14a3b425a3ee7d81e6e4aa5a2b04202925c4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/parser.py @@ -0,0 +1,175 @@ +import codecs +import re +from typing import (IO, Iterator, Match, NamedTuple, Optional, # noqa:F401 + Pattern, Sequence, Tuple) + + +def make_regex(string: str, extra_flags: int = 0) -> Pattern[str]: + return re.compile(string, re.UNICODE | extra_flags) + + +_newline = make_regex(r"(\r\n|\n|\r)") +_multiline_whitespace = make_regex(r"\s*", extra_flags=re.MULTILINE) +_whitespace = make_regex(r"[^\S\r\n]*") +_export = make_regex(r"(?:export[^\S\r\n]+)?") +_single_quoted_key = make_regex(r"'([^']+)'") +_unquoted_key = make_regex(r"([^=\#\s]+)") +_equal_sign = make_regex(r"(=[^\S\r\n]*)") +_single_quoted_value = make_regex(r"'((?:\\'|[^'])*)'") +_double_quoted_value = make_regex(r'"((?:\\"|[^"])*)"') +_unquoted_value = make_regex(r"([^\r\n]*)") +_comment = make_regex(r"(?:[^\S\r\n]*#[^\r\n]*)?") +_end_of_line = make_regex(r"[^\S\r\n]*(?:\r\n|\n|\r|$)") +_rest_of_line = make_regex(r"[^\r\n]*(?:\r|\n|\r\n)?") +_double_quote_escapes = make_regex(r"\\[\\'\"abfnrtv]") +_single_quote_escapes = make_regex(r"\\[\\']") + + +class Original(NamedTuple): + string: str + line: int + + +class Binding(NamedTuple): + key: Optional[str] + value: Optional[str] + original: Original + error: bool + + +class Position: + def __init__(self, chars: int, line: int) -> None: + self.chars = chars + self.line = line + + @classmethod + def start(cls) -> "Position": + return cls(chars=0, line=1) + + def set(self, other: "Position") -> None: + self.chars = other.chars + self.line = other.line + + def advance(self, string: str) -> None: + self.chars += len(string) + self.line += len(re.findall(_newline, string)) + + +class Error(Exception): + pass + + +class Reader: + def __init__(self, stream: IO[str]) -> None: + self.string = stream.read() + self.position = Position.start() + self.mark = Position.start() + + def has_next(self) -> bool: + return self.position.chars < len(self.string) + + def set_mark(self) -> None: + self.mark.set(self.position) + + def get_marked(self) -> Original: + return Original( + string=self.string[self.mark.chars:self.position.chars], + line=self.mark.line, + ) + + def peek(self, count: int) -> str: + return self.string[self.position.chars:self.position.chars + count] + + def read(self, count: int) -> str: + result = self.string[self.position.chars:self.position.chars + count] + if len(result) < count: + raise Error("read: End of string") + self.position.advance(result) + return result + + def read_regex(self, regex: Pattern[str]) -> Sequence[str]: + match = regex.match(self.string, self.position.chars) + if match is None: + raise Error("read_regex: Pattern not found") + self.position.advance(self.string[match.start():match.end()]) + return match.groups() + + +def decode_escapes(regex: Pattern[str], string: str) -> str: + def decode_match(match: Match[str]) -> str: + return codecs.decode(match.group(0), 'unicode-escape') # type: ignore + + return regex.sub(decode_match, string) + + +def parse_key(reader: Reader) -> Optional[str]: + char = reader.peek(1) + if char == "#": + return None + elif char == "'": + (key,) = reader.read_regex(_single_quoted_key) + else: + (key,) = reader.read_regex(_unquoted_key) + return key + + +def parse_unquoted_value(reader: Reader) -> str: + (part,) = reader.read_regex(_unquoted_value) + return re.sub(r"\s+#.*", "", part).rstrip() + + +def parse_value(reader: Reader) -> str: + char = reader.peek(1) + if char == u"'": + (value,) = reader.read_regex(_single_quoted_value) + return decode_escapes(_single_quote_escapes, value) + elif char == u'"': + (value,) = reader.read_regex(_double_quoted_value) + return decode_escapes(_double_quote_escapes, value) + elif char in (u"", u"\n", u"\r"): + return u"" + else: + return parse_unquoted_value(reader) + + +def parse_binding(reader: Reader) -> Binding: + reader.set_mark() + try: + reader.read_regex(_multiline_whitespace) + if not reader.has_next(): + return Binding( + key=None, + value=None, + original=reader.get_marked(), + error=False, + ) + reader.read_regex(_export) + key = parse_key(reader) + reader.read_regex(_whitespace) + if reader.peek(1) == "=": + reader.read_regex(_equal_sign) + value: Optional[str] = parse_value(reader) + else: + value = None + reader.read_regex(_comment) + reader.read_regex(_end_of_line) + return Binding( + key=key, + value=value, + original=reader.get_marked(), + error=False, + ) + except Error: + reader.read_regex(_rest_of_line) + return Binding( + key=None, + value=None, + original=reader.get_marked(), + error=True, + ) + + +def parse_stream(stream: IO[str]) -> Iterator[Binding]: + reader = Reader(stream) + while reader.has_next(): + yield parse_binding(reader) diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/py.typed b/data/miniconda3/lib/python3.13/site-packages/dotenv/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..7632ecf77545c5e5501cb3fc5719df0761104ca2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561 diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/variables.py b/data/miniconda3/lib/python3.13/site-packages/dotenv/variables.py new file mode 100644 index 0000000000000000000000000000000000000000..667f2f26ff2182ecdfc5b809ba97a6cf1d1be13a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/variables.py @@ -0,0 +1,86 @@ +import re +from abc import ABCMeta, abstractmethod +from typing import Iterator, Mapping, Optional, Pattern + +_posix_variable: Pattern[str] = re.compile( + r""" + \$\{ + (?P[^\}:]*) + (?::- + (?P[^\}]*) + )? + \} + """, + re.VERBOSE, +) + + +class Atom(metaclass=ABCMeta): + def __ne__(self, other: object) -> bool: + result = self.__eq__(other) + if result is NotImplemented: + return NotImplemented + return not result + + @abstractmethod + def resolve(self, env: Mapping[str, Optional[str]]) -> str: ... + + +class Literal(Atom): + def __init__(self, value: str) -> None: + self.value = value + + def __repr__(self) -> str: + return f"Literal(value={self.value})" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, self.__class__): + return NotImplemented + return self.value == other.value + + def __hash__(self) -> int: + return hash((self.__class__, self.value)) + + def resolve(self, env: Mapping[str, Optional[str]]) -> str: + return self.value + + +class Variable(Atom): + def __init__(self, name: str, default: Optional[str]) -> None: + self.name = name + self.default = default + + def __repr__(self) -> str: + return f"Variable(name={self.name}, default={self.default})" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, self.__class__): + return NotImplemented + return (self.name, self.default) == (other.name, other.default) + + def __hash__(self) -> int: + return hash((self.__class__, self.name, self.default)) + + def resolve(self, env: Mapping[str, Optional[str]]) -> str: + default = self.default if self.default is not None else "" + result = env.get(self.name, default) + return result if result is not None else "" + + +def parse_variables(value: str) -> Iterator[Atom]: + cursor = 0 + + for match in _posix_variable.finditer(value): + (start, end) = match.span() + name = match["name"] + default = match["default"] + + if start > cursor: + yield Literal(value=value[cursor:start]) + + yield Variable(name=name, default=default) + cursor = end + + length = len(value) + if cursor < length: + yield Literal(value=value[cursor:length]) diff --git a/data/miniconda3/lib/python3.13/site-packages/dotenv/version.py b/data/miniconda3/lib/python3.13/site-packages/dotenv/version.py new file mode 100644 index 0000000000000000000000000000000000000000..6849410aae0a8010e76d5f0a44ced13d750b0989 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/dotenv/version.py @@ -0,0 +1 @@ +__version__ = "1.1.0" diff --git a/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8d1678a09089ba2585d09a28776ff0576df330b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/METADATA @@ -0,0 +1,178 @@ +Metadata-Version: 2.4 +Name: google-auth +Version: 2.49.2 +Summary: Google Authentication Library +Home-page: https://github.com/googleapis/google-auth-library-python +Author: Google Cloud Platform +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Keywords: google auth oauth client +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +License-File: LICENSE +Requires-Dist: pyasn1-modules>=0.2.1 +Requires-Dist: cryptography>=38.0.3 +Provides-Extra: cryptography +Requires-Dist: cryptography>=38.0.3; extra == "cryptography" +Provides-Extra: aiohttp +Requires-Dist: aiohttp<4.0.0,>=3.6.2; extra == "aiohttp" +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "aiohttp" +Provides-Extra: enterprise-cert +Requires-Dist: pyopenssl; extra == "enterprise-cert" +Provides-Extra: pyopenssl +Requires-Dist: pyopenssl>=20.0.0; extra == "pyopenssl" +Provides-Extra: pyjwt +Requires-Dist: pyjwt>=2.0; extra == "pyjwt" +Provides-Extra: reauth +Requires-Dist: pyu2f>=0.1.5; extra == "reauth" +Provides-Extra: requests +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "requests" +Provides-Extra: testing +Requires-Dist: grpcio; extra == "testing" +Requires-Dist: flask; extra == "testing" +Requires-Dist: freezegun; extra == "testing" +Requires-Dist: pyjwt>=2.0; extra == "testing" +Requires-Dist: pytest; extra == "testing" +Requires-Dist: pytest-cov; extra == "testing" +Requires-Dist: pytest-localserver; extra == "testing" +Requires-Dist: pyopenssl>=20.0.0; extra == "testing" +Requires-Dist: pyu2f>=0.1.5; extra == "testing" +Requires-Dist: responses; extra == "testing" +Requires-Dist: urllib3; extra == "testing" +Requires-Dist: packaging; extra == "testing" +Requires-Dist: aiohttp<4.0.0,>=3.6.2; extra == "testing" +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "testing" +Requires-Dist: aioresponses; extra == "testing" +Requires-Dist: pytest-asyncio; extra == "testing" +Requires-Dist: pyopenssl<24.3.0; extra == "testing" +Requires-Dist: aiohttp<3.10.0; extra == "testing" +Provides-Extra: urllib3 +Requires-Dist: urllib3; extra == "urllib3" +Requires-Dist: packaging; extra == "urllib3" +Provides-Extra: rsa +Requires-Dist: rsa<5,>=3.1.4; extra == "rsa" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +Google Auth Python Library +========================== + +|pypi| + +This library simplifies using Google's various server-to-server authentication +mechanisms to access Google APIs. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-auth.svg + :target: https://pypi.python.org/pypi/google-auth + +Installing +---------- + +You can install using `pip`_:: + + $ pip install google-auth + +.. _pip: https://pip.pypa.io/en/stable/ + +For more information on setting up your Python development environment, please refer to `Python Development Environment Setup Guide`_ for Google Cloud Platform. + +.. _`Python Development Environment Setup Guide`: https://cloud.google.com/python/docs/setup + +Extras +------ + +google-auth has few extras that you can install. For example:: + + $ pip install google-auth[pyopenssl] + +Note that the extras pyopenssl and enterprise_cert should not be used together because they use conflicting versions of `cryptography`_. + +.. _`cryptography`: https://cryptography.io/en/latest/ + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Python >= 3.8 + +**NOTE**: +Python 3.8 and Python 3.9 were marked as `unsupported`_ by the python community in +October 2024 and October 2025, respectively. +We recommend that all developers upgrade to Python 3.10 and newer as soon as +they can. Support for end-of-life Python runtimes will be removed from this +library in future updates. +Previous releases that support end-of-life Python versions will continue to be available +for download, but future releases will only target supported versions. + +.. _unsupported: https://devguide.python.org/versions/#unsupported-versions + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Python == 2.7: The last version of this library with support for Python 2.7 + was `google.auth == 1.34.0`. + +- Python 3.5: The last version of this library with support for Python 3.5 + was `google.auth == 1.23.0`. + +- Python 3.6: The last version of this library with support for Python 3.6 + was `google.auth == 2.22.0`. + +- Python 3.7: The last version of this library with support for Python 3.7 + was `google.auth == 2.45.0`. + + +Documentation +------------- + +Google Auth Python Library has usage and reference documentation at https://googleapis.dev/python/google-auth/latest/index.html. + +Current Maintainers +------------------- +- googleapis-auth@google.com + +Authors +------- + +- `@theacodes `_ (Thea Flowers) +- `@dhermes `_ (Danny Hermes) +- `@lukesneeringer `_ (Luke Sneeringer) +- `@busunkim96 `_ (Bu Sun Kim) + +Contributing +------------ + +Contributions to this library are always welcome and highly encouraged. + +See `CONTRIBUTING.rst`_ for more information on how to get started. + +.. _CONTRIBUTING.rst: https://github.com/googleapis/google-auth-library-python/blob/main/CONTRIBUTING.rst + +License +------- + +Apache 2.0 - See `the LICENSE`_ for more information. + +.. _the LICENSE: https://github.com/googleapis/google-auth-library-python/blob/main/LICENSE diff --git a/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..633bdeb6043b920d4d86554650a7e043e4004d49 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/RECORD @@ -0,0 +1,164 @@ +google/auth/__init__.py,sha256=RwqMRE-y6_W0DUtW8QIEjjqnNXVPXKj721EyFqiLuX4,1942 +google/auth/__pycache__/__init__.cpython-313.pyc,, +google/auth/__pycache__/_agent_identity_utils.cpython-313.pyc,, +google/auth/__pycache__/_cache.cpython-313.pyc,, +google/auth/__pycache__/_cloud_sdk.cpython-313.pyc,, +google/auth/__pycache__/_constants.cpython-313.pyc,, +google/auth/__pycache__/_credentials_async.cpython-313.pyc,, +google/auth/__pycache__/_credentials_base.cpython-313.pyc,, +google/auth/__pycache__/_default.cpython-313.pyc,, +google/auth/__pycache__/_default_async.cpython-313.pyc,, +google/auth/__pycache__/_exponential_backoff.cpython-313.pyc,, +google/auth/__pycache__/_helpers.cpython-313.pyc,, +google/auth/__pycache__/_jwt_async.cpython-313.pyc,, +google/auth/__pycache__/_oauth2client.cpython-313.pyc,, +google/auth/__pycache__/_refresh_worker.cpython-313.pyc,, +google/auth/__pycache__/_service_account_info.cpython-313.pyc,, +google/auth/__pycache__/api_key.cpython-313.pyc,, +google/auth/__pycache__/app_engine.cpython-313.pyc,, +google/auth/__pycache__/aws.cpython-313.pyc,, +google/auth/__pycache__/credentials.cpython-313.pyc,, +google/auth/__pycache__/downscoped.cpython-313.pyc,, +google/auth/__pycache__/environment_vars.cpython-313.pyc,, +google/auth/__pycache__/exceptions.cpython-313.pyc,, +google/auth/__pycache__/external_account.cpython-313.pyc,, +google/auth/__pycache__/external_account_authorized_user.cpython-313.pyc,, +google/auth/__pycache__/iam.cpython-313.pyc,, +google/auth/__pycache__/identity_pool.cpython-313.pyc,, +google/auth/__pycache__/impersonated_credentials.cpython-313.pyc,, +google/auth/__pycache__/jwt.cpython-313.pyc,, +google/auth/__pycache__/metrics.cpython-313.pyc,, +google/auth/__pycache__/pluggable.cpython-313.pyc,, +google/auth/__pycache__/version.cpython-313.pyc,, +google/auth/_agent_identity_utils.py,sha256=91ZHrF7BnB5OyxuQtqBDwrMmlBrVjP4kchmvaEF09Aw,9519 +google/auth/_cache.py,sha256=9xbqdkwFa-9W5tzb2WM_bNzFwZ6hKazMcsPugqHuAyA,1863 +google/auth/_cloud_sdk.py,sha256=pwX6vZhYqEpu3vkSNxJ2MI5wMT5t-xX7273QqCtWFZk,5211 +google/auth/_constants.py,sha256=fP9ktmfDQGKEGMdsNvp_r9Uxb18D83cehNhlXDSI2Eo,538 +google/auth/_credentials_async.py,sha256=bHB28wMULOIEMmYqKEOU06A4co7uIXPcnfVC_TaA6KY,6802 +google/auth/_credentials_base.py,sha256=KxdCZyoFyvrfWhJbNnuYkpUhxs0bmbxYvcH8-xp5hUs,2692 +google/auth/_default.py,sha256=FqwhclHCgKNZz1p-lMREv6mY9lKTn2le6CPxckGitxk,31271 +google/auth/_default_async.py,sha256=ZkU8jig_lEb_IpsYT8DBzNPLRGgfYNb_QbL0S3lpjks,11848 +google/auth/_exponential_backoff.py,sha256=qxA9ek80rBkoARx0Egl2b1MlYU0D-pQNVqgCmUh-lgU,5372 +google/auth/_helpers.py,sha256=HFjm7BvOpBD4K4ClwWmcmbCIfegvhB2THnHULsyX1DQ,18550 +google/auth/_jwt_async.py,sha256=5mGab5CkdnBMkQkS4mtNkwFkktp1jBw6G1sYQk8bYKY,5972 +google/auth/_oauth2client.py,sha256=9pBShk1ekwkPNoD5WoQJNQHHD3luNfzpBVoQJo8n1rc,5875 +google/auth/_refresh_worker.py,sha256=zT2jj-PjPtjF3Bqg_n4t1CdL32yBVEUhPKZQwoNu-Xg,3379 +google/auth/_service_account_info.py,sha256=EdOEZql9_mG2cJ54KmL3Q5jO3C3wcadwlCObg4gKjus,2813 +google/auth/aio/__init__.py,sha256=e3ToAxXNHhqJLBgW8B66650xdqrTCZDLcwP2p5DhCPM,869 +google/auth/aio/__pycache__/__init__.cpython-313.pyc,, +google/auth/aio/__pycache__/_helpers.cpython-313.pyc,, +google/auth/aio/__pycache__/credentials.cpython-313.pyc,, +google/auth/aio/_helpers.py,sha256=glCa_-GYxDrcPBFt80LBhMz_V7vLjxAEEWfOZB8lwT0,2334 +google/auth/aio/credentials.py,sha256=lXY0_SJ9c36Mzp47fN4a8JT5HfNzFQtIIwsZEwzoDR4,5273 +google/auth/aio/transport/__init__.py,sha256=8dQWHpube1IeWw02q6AvMRTM5V_2iN4y3UMLenbmUUQ,4692 +google/auth/aio/transport/__pycache__/__init__.cpython-313.pyc,, +google/auth/aio/transport/__pycache__/aiohttp.cpython-313.pyc,, +google/auth/aio/transport/__pycache__/mtls.cpython-313.pyc,, +google/auth/aio/transport/__pycache__/sessions.cpython-313.pyc,, +google/auth/aio/transport/aiohttp.py,sha256=Gweuf3GcNG1_1_GmPpZvcFRXMYvE3MgSPT7XDZSlSAc,7552 +google/auth/aio/transport/mtls.py,sha256=Xpd57h-DHmgjv8dQdjsqxj-ftr_pfhWAWY5_gYJKgPw,6801 +google/auth/aio/transport/sessions.py,sha256=Xrhnl9cLP5egcoQuG8ensQBmCu454j7k1mlpDNLYPzc,23961 +google/auth/api_key.py,sha256=PeieTYceHJIFCo0zQo1EA9NEDL_Ie6S78qmD-6Ig17s,2583 +google/auth/app_engine.py,sha256=mQ7NrKQYd3LiZ7F_ttlqs9Tjf4EEtJNHTPfpixCycW0,6096 +google/auth/aws.py,sha256=aVSDOH2pnECuEYjxn_pHGu8447xyB3P9sAiCQem4ePo,34573 +google/auth/compute_engine/__init__.py,sha256=BqeTka-oyHFATkys3SGKRlOyWQ8mVV0vVaP2hOwV4Qw,910 +google/auth/compute_engine/__pycache__/__init__.cpython-313.pyc,, +google/auth/compute_engine/__pycache__/_metadata.cpython-313.pyc,, +google/auth/compute_engine/__pycache__/_mtls.cpython-313.pyc,, +google/auth/compute_engine/__pycache__/credentials.cpython-313.pyc,, +google/auth/compute_engine/_metadata.py,sha256=g44MLHIWkwM2g59-YEWsbSASJCfLRR6JdJO1H9xDciw,17859 +google/auth/compute_engine/_mtls.py,sha256=-XLR9-Vp8KROuDjAY4GmoakphtYYYtBOtholhNMF2iU,5737 +google/auth/compute_engine/credentials.py,sha256=tDn4jURLomLuePleRgXI7ThmPh467h_SBHBzS0ITGTg,21806 +google/auth/credentials.py,sha256=7exONBHgRiL6vVF-rSVP6wEoIrtUy8uWz6Pij-WRL3c,24350 +google/auth/crypt/__init__.py,sha256=ukDmKrdUmHqGc5rDLcoel_TKXdV5wX05r5Gqi9hnWBE,3144 +google/auth/crypt/__pycache__/__init__.cpython-313.pyc,, +google/auth/crypt/__pycache__/_cryptography_rsa.cpython-313.pyc,, +google/auth/crypt/__pycache__/_helpers.cpython-313.pyc,, +google/auth/crypt/__pycache__/_python_rsa.cpython-313.pyc,, +google/auth/crypt/__pycache__/base.cpython-313.pyc,, +google/auth/crypt/__pycache__/es.cpython-313.pyc,, +google/auth/crypt/__pycache__/es256.cpython-313.pyc,, +google/auth/crypt/__pycache__/rsa.cpython-313.pyc,, +google/auth/crypt/_cryptography_rsa.py,sha256=o2QTRkfDRLtEBiq-fbpbTWypvxaxUDwzlx2NpXG9o0w,5158 +google/auth/crypt/_helpers.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google/auth/crypt/_python_rsa.py,sha256=Exqz9OgDm-3JHHd636gnAdXdcH6pjDWBNJz21uDRnUE,6747 +google/auth/crypt/base.py,sha256=3CJrnQsppR6h-WnTRqSrt1hPEQVkHcwNIVJ_B5M00hY,4190 +google/auth/crypt/es.py,sha256=3eHSDU_lh95pMYE3eIGErGHPETqsRCHeK2VtQnqVPk8,8019 +google/auth/crypt/es256.py,sha256=cFaDuQRdXx3f_aVy-HH0VQ6G49VNSAhB04jnbjyxHNI,1454 +google/auth/crypt/rsa.py,sha256=coLr0FFyuDAmDaoXefpriH_naAJbmgwFORUDVYGdBYU,4770 +google/auth/downscoped.py,sha256=KmmC8lbBWUFUsIYt1VpcbTXs3yYJYXteH19qdZQgobA,21793 +google/auth/environment_vars.py,sha256=elIkXWjxdlOsf-CQid8UFcXcAIHtg17wi6otcveYCsQ,5163 +google/auth/exceptions.py,sha256=8oEeB_1UirJIyBoglQRpCFjCOcxcTaLr6EpBrrxjeEs,3193 +google/auth/external_account.py,sha256=JQJnl0xSXfi-BuxP67QtkjcG5fLSb-Paxl9l7sL5OC4,30226 +google/auth/external_account_authorized_user.py,sha256=ANMUc39Hvj_Po3vg2hCWc9GLAckVNFy_s8-IB0BHYmc,17322 +google/auth/iam.py,sha256=6WvKmo8sXVIm0_Tma_OICtuO-H8RzJMBw6qGGsRbOE8,5058 +google/auth/identity_pool.py,sha256=D2eJ742K_SLNAuffWkT25k0Tt7R8RyEGX32bPOPPh7g,24742 +google/auth/impersonated_credentials.py,sha256=34E71Tl28LPXZmsJd8zxn-9tBu2OZpVgj-3NUsT7Tdc,27564 +google/auth/jwt.py,sha256=CxVlg9VxMbgdSaT7_4hISDNkL9eBVNi4jCmpFJXiOJM,31178 +google/auth/metrics.py,sha256=usjITvTFmO0YogJJDi31_hgl2kgENuKMfgWy6LTGhxg,5616 +google/auth/pluggable.py,sha256=N9lxIiiegT6DIv3poc5B3B-6OlVmFRZr-AmNO6Xzid4,18371 +google/auth/py.typed,sha256=l05_LTgi3oy-einKBrw66s6aavgzG2o-SekKPOY3ayM,74 +google/auth/transport/__init__.py,sha256=vTdWUDBCXWF6wk3Xzu7L5I1lbtGYTxONi-IKYOmDdFM,3654 +google/auth/transport/__pycache__/__init__.cpython-313.pyc,, +google/auth/transport/__pycache__/_aiohttp_requests.cpython-313.pyc,, +google/auth/transport/__pycache__/_custom_tls_signer.cpython-313.pyc,, +google/auth/transport/__pycache__/_http_client.cpython-313.pyc,, +google/auth/transport/__pycache__/_mtls_helper.cpython-313.pyc,, +google/auth/transport/__pycache__/_requests_base.cpython-313.pyc,, +google/auth/transport/__pycache__/grpc.cpython-313.pyc,, +google/auth/transport/__pycache__/mtls.cpython-313.pyc,, +google/auth/transport/__pycache__/requests.cpython-313.pyc,, +google/auth/transport/__pycache__/urllib3.cpython-313.pyc,, +google/auth/transport/_aiohttp_requests.py,sha256=aJNNT09VISGPwcGS8DVR8G1l_DeOvnlJ2Z7kcAjXs14,14819 +google/auth/transport/_custom_tls_signer.py,sha256=ilLlKFNognkvOWcnlYAWmUIUo9YhSrTSAKLa05zQ8Do,9989 +google/auth/transport/_http_client.py,sha256=_lE2TaQOb2hZq5OrblNAYbpZzLX18LGXSyaNJuXHJ2w,3798 +google/auth/transport/_mtls_helper.py,sha256=PcYF7siMNiHMce_tXZa_oAgMaON3mBkJqqF5SqVXhm0,19684 +google/auth/transport/_requests_base.py,sha256=4y0tTMR_hPGeAmBSyCU6_moh99ZxJZ4CF79E2s-t7TA,1657 +google/auth/transport/grpc.py,sha256=cRYju1kWZ2YE5IlagRMh9trAW8J5kmmIrBmyZW7IGik,13742 +google/auth/transport/mtls.py,sha256=dfOH5kaz4R9pNdm5l-cRQc1PfpGldpS3FBwdSF72KfY,5163 +google/auth/transport/requests.py,sha256=--9PLv4Jaiz1HiIzl_tVKJ0Z1k-3XPQ3HBsXVBaIf4U,24332 +google/auth/transport/urllib3.py,sha256=bmYdTtBa3Yni5Q1pvpqbuHwF70g0gz7RfNsR6hDFz7g,18349 +google/auth/version.py,sha256=AmB79UFwRD_sYP8u_CC2yo_pGElSkIzUzQEVWJkv894,598 +google/oauth2/__init__.py,sha256=dfKTOzsmsiXlGbG1_LMpHfb-thZoCXCeiGiZr1PxoTk,1499 +google/oauth2/__pycache__/__init__.cpython-313.pyc,, +google/oauth2/__pycache__/_client.cpython-313.pyc,, +google/oauth2/__pycache__/_client_async.cpython-313.pyc,, +google/oauth2/__pycache__/_credentials_async.cpython-313.pyc,, +google/oauth2/__pycache__/_id_token_async.cpython-313.pyc,, +google/oauth2/__pycache__/_reauth_async.cpython-313.pyc,, +google/oauth2/__pycache__/_service_account_async.cpython-313.pyc,, +google/oauth2/__pycache__/challenges.cpython-313.pyc,, +google/oauth2/__pycache__/credentials.cpython-313.pyc,, +google/oauth2/__pycache__/gdch_credentials.cpython-313.pyc,, +google/oauth2/__pycache__/id_token.cpython-313.pyc,, +google/oauth2/__pycache__/reauth.cpython-313.pyc,, +google/oauth2/__pycache__/service_account.cpython-313.pyc,, +google/oauth2/__pycache__/sts.cpython-313.pyc,, +google/oauth2/__pycache__/utils.cpython-313.pyc,, +google/oauth2/__pycache__/webauthn_handler.cpython-313.pyc,, +google/oauth2/__pycache__/webauthn_handler_factory.cpython-313.pyc,, +google/oauth2/__pycache__/webauthn_types.cpython-313.pyc,, +google/oauth2/_client.py,sha256=w_o0uFvNlxf7o79k19_TVnGlu4zT7F58v8IIjexH_Yc,21920 +google/oauth2/_client_async.py,sha256=nXLgAI5KVPRR6w7-5cjB8jc5V59hd-gpPu9OR7mElCw,10170 +google/oauth2/_credentials_async.py,sha256=hUrucQkcYuYlyCdHMci8tzaVncnjQlFc2sAfNu5Dt8k,4474 +google/oauth2/_id_token_async.py,sha256=ot4_u-rhA22TufWOAR5Mpaua7Q2aAtN4q_kJmj-YnII,10171 +google/oauth2/_reauth_async.py,sha256=XK63x1CCWTBX4TG_mwc1WnRmB3vG0JRZ5F-dNfxodcs,11715 +google/oauth2/_service_account_async.py,sha256=5-HBGWoHhbWpCRbd34YiopQepEsEf8gSiuMlSm5hN84,5131 +google/oauth2/challenges.py,sha256=Pdy8IpwGJstz890Ctz_xZvhUwIlTvKibSnmHNbRBZd0,10405 +google/oauth2/credentials.py,sha256=3AoCDHqBE34fz3urYHxFFcysLqkCb3SMbFgm9OQDvI0,25040 +google/oauth2/gdch_credentials.py,sha256=CY6iPnPuc2OCIe1Zujwg1Mu9QSl1iGJqGOy6TkUleHw,9007 +google/oauth2/id_token.py,sha256=sCPdYw6LxcLgDqUvKygmdcrIGzZFGGXoARRYI-BzZ_U,13710 +google/oauth2/py.typed,sha256=I0muXRRdbdpJoZ_VyheisiTTYcmjTAitQpNvuuh6fMw,76 +google/oauth2/reauth.py,sha256=CkkDpv79_8SsQDromAyI3sa2lS3V_M7bSZqWFZj30nw,12878 +google/oauth2/service_account.py,sha256=2ea9RZvtN_zDvNacvnQy23mhckDz-uNrpk5xUEUN4V4,33525 +google/oauth2/sts.py,sha256=df-lzhe8cBKr2O-tWZTaWdgYonKm1J9HI5Cz_AfW1hU,7728 +google/oauth2/utils.py,sha256=4crAdpKbDtobpQfXJc3uF6Zm6F3IzffvRSo-9h_515w,6315 +google/oauth2/webauthn_handler.py,sha256=lg_5mHowRJ0kx2hluMYhcdiFctHZyi8CFc9fT8CkQwA,2743 +google/oauth2/webauthn_handler_factory.py,sha256=soE5cokZ3pLNbBo1HC6F1N-N-I-ir-DGlD0trGPCpBs,429 +google/oauth2/webauthn_types.py,sha256=IHdqUe-EWOU-CmyLnHLniqc7vGHZ8HpavB0dcjn7Zl8,5386 +google_auth-2.49.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_auth-2.49.2.dist-info/METADATA,sha256=x-7ZZKM8tNeJo-uwmAcNKyMWqONaO-3J-0JTk0Be0OE,6191 +google_auth-2.49.2.dist-info/RECORD,, +google_auth-2.49.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +google_auth-2.49.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +google_auth-2.49.2.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_auth-2.49.2.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..6f852417d9ce2e2dcafe85488e94c8021dd2c059 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/METADATA @@ -0,0 +1,2042 @@ +Metadata-Version: 2.4 +Name: google-genai +Version: 1.72.0 +Summary: GenAI Python SDK +Author-email: Google LLC +License-Expression: Apache-2.0 +Project-URL: Homepage, https://github.com/googleapis/python-genai +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Internet +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: anyio<5.0.0,>=4.8.0 +Requires-Dist: google-auth[requests]<3.0.0,>=2.48.1 +Requires-Dist: httpx<1.0.0,>=0.28.1 +Requires-Dist: pydantic<3.0.0,>=2.9.0 +Requires-Dist: requests<3.0.0,>=2.28.1 +Requires-Dist: tenacity<9.2.0,>=8.2.3 +Requires-Dist: websockets<17.0,>=13.0.0 +Requires-Dist: typing-extensions<5.0.0,>=4.14.0 +Requires-Dist: distro<2,>=1.7.0 +Requires-Dist: sniffio +Provides-Extra: aiohttp +Requires-Dist: aiohttp<4.0.0,>=3.10.11; extra == "aiohttp" +Provides-Extra: local-tokenizer +Requires-Dist: sentencepiece>=0.2.0; extra == "local-tokenizer" +Requires-Dist: protobuf; extra == "local-tokenizer" +Provides-Extra: pyopenssl +Requires-Dist: pyopenssl; extra == "pyopenssl" +Dynamic: license-file + +# Google Gen AI SDK + +[![PyPI version](https://img.shields.io/pypi/v/google-genai.svg)](https://pypi.org/project/google-genai/) +![Python support](https://img.shields.io/pypi/pyversions/google-genai) +[![PyPI - Downloads](https://img.shields.io/pypi/dw/google-genai)](https://pypistats.org/packages/google-genai) + +-------- +**Documentation:** https://googleapis.github.io/python-genai/ + +----- + +Google Gen AI Python SDK provides an interface for developers to integrate +Google's generative models into their Python applications. It supports the +[Gemini Developer API](https://ai.google.dev/gemini-api/docs) and +[Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) +APIs. + +## Code Generation + +Generative models are often unaware of recent API and SDK updates and may suggest outdated or legacy code. + +We recommend using our Code Generation instructions [`codegen_instructions.md`](https://raw.githubusercontent.com/googleapis/python-genai/refs/heads/main/codegen_instructions.md) when generating Google Gen AI SDK code to guide your model towards using the more recent SDK features. Copy and paste the instructions into your development environment to provide the model with the necessary context. + +## Installation + +```sh +pip install google-genai +``` + +With `uv`: + +```sh +uv pip install google-genai +``` + +## Imports + +```python +from google import genai +from google.genai import types +``` + +## Create a client + +Please run one of the following code blocks to create a client for +different services ([Gemini Developer API](https://ai.google.dev/gemini-api/docs) or [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview)). + +```python +from google import genai + +# Only run this block for Gemini Developer API +client = genai.Client(api_key='GEMINI_API_KEY') +``` + +```python +from google import genai + +# Only run this block for Vertex AI API +client = genai.Client( + vertexai=True, project='your-project-id', location='us-central1' +) +``` + +## Using types + +All API methods support Pydantic types and dictionaries, which you can access +from `google.genai.types`. You can import the types module with the following: + +```python +from google.genai import types +``` + +Below is an example `generate_content()` call using types from the types module: + +```python +response = client.models.generate_content( + model='gemini-2.5-flash', + contents=types.Part.from_text(text='Why is the sky blue?'), + config=types.GenerateContentConfig( + temperature=0, + top_p=0.95, + top_k=20, + ), +) +``` + +Alternatively, you can accomplish the same request using dictionaries instead of +types: + +```python +response = client.models.generate_content( + model='gemini-2.5-flash', + contents={'text': 'Why is the sky blue?'}, + config={ + 'temperature': 0, + 'top_p': 0.95, + 'top_k': 20, + }, +) +``` + +**(Optional) Using environment variables:** + +You can create a client by configuring the necessary environment variables. +Configuration setup instructions depends on whether you're using the Gemini +Developer API or the Gemini API in Vertex AI. + +**Gemini Developer API:** Set the `GEMINI_API_KEY` or `GOOGLE_API_KEY`. +It will automatically be picked up by the client. It's recommended that you +set only one of those variables, but if both are set, `GOOGLE_API_KEY` takes +precedence. + +```bash +export GEMINI_API_KEY='your-api-key' +``` + +**Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`, +`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, as shown below: + +```bash +export GOOGLE_GENAI_USE_VERTEXAI=true +export GOOGLE_CLOUD_PROJECT='your-project-id' +export GOOGLE_CLOUD_LOCATION='us-central1' +``` + +```python +from google import genai + +client = genai.Client() +``` + +## Close a client + +Explicitly close the sync client to ensure that resources, such as the +underlying HTTP connections, are properly cleaned up and closed. + +```python +from google.genai import Client + +client = Client() +response_1 = client.models.generate_content( + model=MODEL_ID, + contents='Hello', +) +response_2 = client.models.generate_content( + model=MODEL_ID, + contents='Ask a question', +) +# Close the sync client to release resources. +client.close() +``` + +To explicitly close the async client: + +```python +from google.genai import Client + +aclient = Client( + vertexai=True, project='my-project-id', location='us-central1' +).aio +response_1 = await aclient.models.generate_content( + model=MODEL_ID, + contents='Hello', +) +response_2 = await aclient.models.generate_content( + model=MODEL_ID, + contents='Ask a question', +) +# Close the async client to release resources. +await aclient.aclose() +``` + +## Client context managers + +By using the sync client context manager, it will close the underlying +sync client when exiting the with block and avoid httpx "client has been closed" error like [issues#1763](https://github.com/googleapis/python-genai/issues/1763). + +```python +from google.genai import Client + +with Client() as client: + response_1 = client.models.generate_content( + model=MODEL_ID, + contents='Hello', + ) + response_2 = client.models.generate_content( + model=MODEL_ID, + contents='Ask a question', + ) +``` + +By using the async client context manager, it will close the underlying + async client when exiting the with block. + +```python +from google.genai import Client + +async with Client().aio as aclient: + response_1 = await aclient.models.generate_content( + model=MODEL_ID, + contents='Hello', + ) + response_2 = await aclient.models.generate_content( + model=MODEL_ID, + contents='Ask a question', + ) +``` + +### API Selection + +By default, the SDK uses the beta API endpoints provided by Google to support +preview features in the APIs. The stable API endpoints can be selected by +setting the API version to `v1`. + +To set the API version use `http_options`. For example, to set the API version +to `v1` for Vertex AI: + +```python +from google import genai +from google.genai import types + +client = genai.Client( + vertexai=True, + project='your-project-id', + location='us-central1', + http_options=types.HttpOptions(api_version='v1') +) +``` + +To set the API version to `v1alpha` for the Gemini Developer API: + +```python +from google import genai +from google.genai import types + +client = genai.Client( + api_key='GEMINI_API_KEY', + http_options=types.HttpOptions(api_version='v1alpha') +) +``` + +### Faster async client option: Aiohttp + +By default we use httpx for both sync and async client implementations. In order +to have faster performance, you may install `google-genai[aiohttp]`. In Gen AI +SDK we configure `trust_env=True` to match with the default behavior of httpx. +Additional args of `aiohttp.ClientSession.request()` ([see `_RequestOptions` args](https://github.com/aio-libs/aiohttp/blob/v3.12.13/aiohttp/client.py#L170)) can be passed +through the following way: + +```python +http_options = types.HttpOptions( + async_client_args={'cookies': ..., 'ssl': ...}, +) + +client=Client(..., http_options=http_options) +``` + +### Proxy + +Both httpx and aiohttp libraries use `urllib.request.getproxies` from +environment variables. Before client initialization, you may set proxy (and +optional `SSL_CERT_FILE`) by setting the environment variables: + +```bash +export HTTPS_PROXY='http://username:password@proxy_uri:port' +export SSL_CERT_FILE='client.pem' +``` + +If you need `socks5` proxy, httpx [supports](https://www.python-httpx.org/advanced/proxies/#socks) `socks5` proxy if you pass it via +args to `httpx.Client()`. You may install `httpx[socks]` to use it. +Then, you can pass it through the following way: + +```python +http_options = types.HttpOptions( + client_args={'proxy': 'socks5://user:pass@host:port'}, + async_client_args={'proxy': 'socks5://user:pass@host:port'}, +) + +client=Client(..., http_options=http_options) +``` + +### Custom base url + +In some cases you might need a custom base url (for example, API gateway proxy +server) and bypass some authentication checks for project, location, or API key. +You may pass the custom base url like this: + +```python +client = Client( + vertexai=True, + http_options=types.HttpOptionsDict( + base_url='https://test-api-gateway-proxy.com', + base_url_resource_scope=types.ResourceScope.COLLECTION, + ), +) + +response = client.models.generate_content( + model='gemini-3-pro-preview', contents='Why is the sky blue?' +) +``` + +If `base_url_resource_scope=types.ResourceScope.COLLECTION`, the resource name +will not include api version, project, or location. + +Expected request url will be: +https://test-api-gateway-proxy.com/publishers/google/models/gemini-3-pro-preview + + +## Types + +Parameter types can be specified as either dictionaries(`TypedDict`) or +[Pydantic Models](https://pydantic.readthedocs.io/en/stable/model.html). +Pydantic model types are available in the `types` module. + +## Models + +The `client.models` module exposes model inferencing and model getters. +See the 'Create a client' section above to initialize a client. + +### Generate Content + +#### with text content input (text output) + +```python +response = client.models.generate_content( + model='gemini-2.5-flash', contents='Why is the sky blue?' +) +print(response.text) +``` + +#### with text content input (image output) + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.5-flash-image', + contents='A cartoon infographic for flying sneakers', + config=types.GenerateContentConfig( + response_modalities=["IMAGE"], + image_config=types.ImageConfig( + aspect_ratio="9:16", + ), + ), +) + +for part in response.parts: + if part.inline_data: + generated_image = part.as_image() + generated_image.show() +``` + +#### with uploaded file (Gemini Developer API only) + +Download the file in console. + +```sh +!wget -q https://storage.googleapis.com/generativeai-downloads/data/a11.txt +``` + +python code. + +```python +file = client.files.upload(file='a11.txt') +response = client.models.generate_content( + model='gemini-2.5-flash', + contents=['Could you summarize this file?', file] +) +print(response.text) +``` + +#### How to structure `contents` argument for `generate_content` + +The SDK always converts the inputs to the `contents` argument into +`list[types.Content]`. +The following shows some common ways to provide your inputs. + +##### Provide a `list[types.Content]` + +This is the canonical way to provide contents, SDK will not do any conversion. + +##### Provide a `types.Content` instance + +```python +from google.genai import types + +contents = types.Content( + role='user', + parts=[types.Part.from_text(text='Why is the sky blue?')] +) +``` + +SDK converts this to + +```python +[ + types.Content( + role='user', + parts=[types.Part.from_text(text='Why is the sky blue?')] + ) +] +``` + +##### Provide a string + +```python +contents='Why is the sky blue?' +``` + +The SDK will assume this is a text part, and it converts this into the following: + +```python +[ + types.UserContent( + parts=[ + types.Part.from_text(text='Why is the sky blue?') + ] + ) +] +``` + +Where a `types.UserContent` is a subclass of `types.Content`, it sets the +`role` field to be `user`. + +##### Provide a list of strings + +```python +contents=['Why is the sky blue?', 'Why is the cloud white?'] +``` + +The SDK assumes these are 2 text parts, it converts this into a single content, +like the following: + +```python +[ + types.UserContent( + parts=[ + types.Part.from_text(text='Why is the sky blue?'), + types.Part.from_text(text='Why is the cloud white?'), + ] + ) +] +``` + +Where a `types.UserContent` is a subclass of `types.Content`, the +`role` field in `types.UserContent` is fixed to be `user`. + +##### Provide a function call part + +```python +from google.genai import types + +contents = types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'Boston'} +) +``` + +The SDK converts a function call part to a content with a `model` role: + +```python +[ + types.ModelContent( + parts=[ + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'Boston'} + ) + ] + ) +] +``` + +Where a `types.ModelContent` is a subclass of `types.Content`, the +`role` field in `types.ModelContent` is fixed to be `model`. + +##### Provide a list of function call parts + +```python +from google.genai import types + +contents = [ + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'Boston'} + ), + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'New York'} + ), +] +``` + +The SDK converts a list of function call parts to a content with a `model` role: + +```python +[ + types.ModelContent( + parts=[ + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'Boston'} + ), + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'New York'} + ) + ] + ) +] +``` + +Where a `types.ModelContent` is a subclass of `types.Content`, the +`role` field in `types.ModelContent` is fixed to be `model`. + +##### Provide a non function call part + +```python +from google.genai import types + +contents = types.Part.from_uri( + file_uri: 'gs://generativeai-downloads/images/scones.jpg', + mime_type: 'image/jpeg', +) +``` + +The SDK converts all non function call parts into a content with a `user` role. + +```python +[ + types.UserContent(parts=[ + types.Part.from_uri( + file_uri: 'gs://generativeai-downloads/images/scones.jpg', + mime_type: 'image/jpeg', + ) + ]) +] +``` + +##### Provide a list of non function call parts + +```python +from google.genai import types + +contents = [ + types.Part.from_text('What is this image about?'), + types.Part.from_uri( + file_uri: 'gs://generativeai-downloads/images/scones.jpg', + mime_type: 'image/jpeg', + ) +] +``` + +The SDK will convert the list of parts into a content with a `user` role + +```python +[ + types.UserContent( + parts=[ + types.Part.from_text('What is this image about?'), + types.Part.from_uri( + file_uri: 'gs://generativeai-downloads/images/scones.jpg', + mime_type: 'image/jpeg', + ) + ] + ) +] +``` + +##### Mix types in contents + +You can also provide a list of `types.ContentUnion`. The SDK leaves items of +`types.Content` as is, it groups consecutive non function call parts into a +single `types.UserContent`, and it groups consecutive function call parts into +a single `types.ModelContent`. + +If you put a list within a list, the inner list can only contain +`types.PartUnion` items. The SDK will convert the inner list into a single +`types.UserContent`. + +### System Instructions and Other Configs + +The output of the model can be influenced by several optional settings +available in generate_content's config parameter. For example, increasing +`max_output_tokens` is essential for longer model responses. To make a model more +deterministic, lowering the `temperature` parameter reduces randomness, with +values near 0 minimizing variability. Capabilities and parameter defaults for +each model is shown in the +[Vertex AI docs](https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/2-5-flash) +and [Gemini API docs](https://ai.google.dev/gemini-api/docs/models) respectively. + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='high', + config=types.GenerateContentConfig( + system_instruction='I say high, you say low', + max_output_tokens=3, + temperature=0.3, + ), +) +print(response.text) +``` + +### List Base Models + +To retrieve tuned models, see [list tuned models](#list-tuned-models). + +```python +for model in client.models.list(): + print(model) +``` + +```python +pager = client.models.list(config={'page_size': 10}) +print(pager.page_size) +print(pager[0]) +pager.next_page() +print(pager[0]) +``` + +#### List Base Models (Asynchronous) + +```python +async for job in await client.aio.models.list(): + print(job) +``` + +```python +async_pager = await client.aio.models.list(config={'page_size': 10}) +print(async_pager.page_size) +print(async_pager[0]) +await async_pager.next_page() +print(async_pager[0]) +``` + +### Safety Settings + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='Say something bad.', + config=types.GenerateContentConfig( + safety_settings=[ + types.SafetySetting( + category='HARM_CATEGORY_HATE_SPEECH', + threshold='BLOCK_ONLY_HIGH', + ) + ] + ), +) +print(response.text) +``` + +### Function Calling + +#### Automatic Python function Support + +You can pass a Python function directly and it will be automatically +called and responded by default. + +```python +from google.genai import types + +def get_current_weather(location: str) -> str: + """Returns the current weather. + + Args: + location: The city and state, e.g. San Francisco, CA + """ + return 'sunny' + + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='What is the weather like in Boston?', + config=types.GenerateContentConfig(tools=[get_current_weather]), +) + +print(response.text) +``` + +#### Disabling automatic function calling + +If you pass in a python function as a tool directly, and do not want +automatic function calling, you can disable automatic function calling +as follows: + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='What is the weather like in Boston?', + config=types.GenerateContentConfig( + tools=[get_current_weather], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + ), +) +``` + +With automatic function calling disabled, you will get a list of function call +parts in the response: + +```python +function_calls: Optional[List[types.FunctionCall]] = response.function_calls +``` + +#### Manually declare and invoke a function for function calling + +If you don't want to use the automatic function support, you can manually +declare the function and invoke it. + +The following example shows how to declare a function and pass it as a tool. +Then you will receive a function call part in the response. + +```python +from google.genai import types + +function = types.FunctionDeclaration( + name='get_current_weather', + description='Get the current weather in a given location', + parameters_json_schema={ + 'type': 'object', + 'properties': { + 'location': { + 'type': 'string', + 'description': 'The city and state, e.g. San Francisco, CA', + } + }, + 'required': ['location'], + }, +) + +tool = types.Tool(function_declarations=[function]) + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='What is the weather like in Boston?', + config=types.GenerateContentConfig(tools=[tool]), +) + +print(response.function_calls[0]) +``` + +After you receive the function call part from the model, you can invoke the function +and get the function response. And then you can pass the function response to +the model. +The following example shows how to do it for a simple function invocation. + +```python +from google.genai import types + +user_prompt_content = types.Content( + role='user', + parts=[types.Part.from_text(text='What is the weather like in Boston?')], +) +function_call_part = response.function_calls[0] +function_call_content = response.candidates[0].content + + +try: + function_result = get_current_weather( + **function_call_part.function_call.args + ) + function_response = {'result': function_result} +except ( + Exception +) as e: # instead of raising the exception, you can let the model handle it + function_response = {'error': str(e)} + + +function_response_part = types.Part.from_function_response( + name=function_call_part.name, + response=function_response, +) +function_response_content = types.Content( + role='tool', parts=[function_response_part] +) + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + user_prompt_content, + function_call_content, + function_response_content, + ], + config=types.GenerateContentConfig( + tools=[tool], + ), +) + +print(response.text) +``` + +#### Function calling with `ANY` tools config mode + +If you configure function calling mode to be `ANY`, then the model will always +return function call parts. If you also pass a python function as a tool, by +default the SDK will perform automatic function calling until the remote calls exceed the +maximum remote call for automatic function calling (default to 10 times). + +If you'd like to disable automatic function calling in `ANY` mode: + +```python +from google.genai import types + +def get_current_weather(location: str) -> str: + """Returns the current weather. + + Args: + location: The city and state, e.g. San Francisco, CA + """ + return "sunny" + +response = client.models.generate_content( + model="gemini-2.5-flash", + contents="What is the weather like in Boston?", + config=types.GenerateContentConfig( + tools=[get_current_weather], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig(mode='ANY') + ), + ), +) +``` + +If you'd like to set `x` number of automatic function call turns, you can +configure the maximum remote calls to be `x + 1`. +Assuming you prefer `1` turn for automatic function calling. + +```python +from google.genai import types + +def get_current_weather(location: str) -> str: + """Returns the current weather. + + Args: + location: The city and state, e.g. San Francisco, CA + """ + return "sunny" + +response = client.models.generate_content( + model="gemini-2.5-flash", + contents="What is the weather like in Boston?", + config=types.GenerateContentConfig( + tools=[get_current_weather], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + maximum_remote_calls=2 + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig(mode='ANY') + ), + ), +) +``` + +#### Model Context Protocol (MCP) support (experimental) + +Built-in [MCP](https://modelcontextprotocol.io/introduction) support is an +experimental feature. You can pass a local MCP server as a tool directly. + +```python +import os +import asyncio +from datetime import datetime +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client +from google import genai + +client = genai.Client() + +# Create server parameters for stdio connection +server_params = StdioServerParameters( + command="npx", # Executable + args=["-y", "@philschmid/weather-mcp"], # MCP Server + env=None, # Optional environment variables +) + +async def run(): + async with stdio_client(server_params) as (read, write): + async with ClientSession(read, write) as session: + # Prompt to get the weather for the current day in London. + prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?" + + # Initialize the connection between client and server + await session.initialize() + + # Send request to the model with MCP function declarations + response = await client.aio.models.generate_content( + model="gemini-2.5-flash", + contents=prompt, + config=genai.types.GenerateContentConfig( + temperature=0, + tools=[session], # uses the session, will automatically call the tool using automatic function calling + ), + ) + print(response.text) + +# Start the asyncio event loop and run the main function +asyncio.run(run()) +``` + +### JSON Response Schema + +However you define your schema, don't duplicate it in your input prompt, +including by giving examples of expected JSON output. If you do, the generated +output might be lower in quality. + +#### JSON Schema support + +Schemas can be provided as standard JSON schema. + +```python +user_profile = { + 'properties': { + 'age': { + 'anyOf': [ + {'maximum': 20, 'minimum': 0, 'type': 'integer'}, + {'type': 'null'}, + ], + 'title': 'Age', + }, + 'username': { + 'description': "User's unique name", + 'title': 'Username', + 'type': 'string', + }, + }, + 'required': ['username', 'age'], + 'title': 'User Schema', + 'type': 'object', +} + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='Give me a random user profile.', + config={ + 'response_mime_type': 'application/json', + 'response_json_schema': user_profile + }, +) +print(response.text) +``` + +#### Pydantic Model Schema support + +Schemas can be provided as Pydantic Models. + +```python +from pydantic import BaseModel +from google.genai import types + + +class CountryInfo(BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='Give me information for the United States.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_json_schema=CountryInfo.model_json_schema(), + ), +) +print(response.text) +``` + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='Give me information for the United States.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_json_schema={ + 'required': [ + 'name', + 'population', + 'capital', + 'continent', + 'gdp', + 'official_language', + 'total_area_sq_mi', + ], + 'properties': { + 'name': {'type': 'STRING'}, + 'population': {'type': 'INTEGER'}, + 'capital': {'type': 'STRING'}, + 'continent': {'type': 'STRING'}, + 'gdp': {'type': 'INTEGER'}, + 'official_language': {'type': 'STRING'}, + 'total_area_sq_mi': {'type': 'INTEGER'}, + }, + 'type': 'OBJECT', + }, + ), +) +print(response.text) +``` + +### Generate Content (Synchronous Streaming) + +Generate content in a streaming format so that the model outputs streams back +to you, rather than being returned as one chunk. + +#### Streaming for text content + +```python +for chunk in client.models.generate_content_stream( + model='gemini-2.5-flash', contents='Tell me a story in 300 words.' +): + print(chunk.text, end='') +``` + +#### Streaming for image content + +If your image is stored in [Google Cloud Storage](https://cloud.google.com/storage), +you can use the `from_uri` class method to create a `Part` object. + +```python +from google.genai import types + +for chunk in client.models.generate_content_stream( + model='gemini-2.5-flash', + contents=[ + 'What is this image about?', + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ), + ], +): + print(chunk.text, end='') +``` + +If your image is stored in your local file system, you can read it in as bytes +data and use the `from_bytes` class method to create a `Part` object. + +```python +from google.genai import types + +YOUR_IMAGE_PATH = 'your_image_path' +YOUR_IMAGE_MIME_TYPE = 'your_image_mime_type' +with open(YOUR_IMAGE_PATH, 'rb') as f: + image_bytes = f.read() + +for chunk in client.models.generate_content_stream( + model='gemini-2.5-flash', + contents=[ + 'What is this image about?', + types.Part.from_bytes(data=image_bytes, mime_type=YOUR_IMAGE_MIME_TYPE), + ], +): + print(chunk.text, end='') +``` + +### Generate Content (Asynchronous Non Streaming) + +`client.aio` exposes all the analogous [`async` methods](https://docs.python.org/3/library/asyncio.html) +that are available on `client`. Note that it applies to all the modules. + +For example, `client.aio.models.generate_content` is the `async` version +of `client.models.generate_content` + +```python +response = await client.aio.models.generate_content( + model='gemini-2.5-flash', contents='Tell me a story in 300 words.' +) + +print(response.text) +``` + +### Generate Content (Asynchronous Streaming) + +```python +async for chunk in await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', contents='Tell me a story in 300 words.' +): + print(chunk.text, end='') +``` + +### Count Tokens and Compute Tokens + +```python +response = client.models.count_tokens( + model='gemini-2.5-flash', + contents='why is the sky blue?', +) +print(response) +``` + +#### Compute Tokens + +Compute tokens is only supported in Vertex AI. + +```python +response = client.models.compute_tokens( + model='gemini-2.5-flash', + contents='why is the sky blue?', +) +print(response) +``` + +##### Async + +```python +response = await client.aio.models.count_tokens( + model='gemini-2.5-flash', + contents='why is the sky blue?', +) +print(response) +``` + +#### Local Count Tokens + +```python +tokenizer = genai.LocalTokenizer(model_name='gemini-2.5-flash') +result = tokenizer.count_tokens("What is your name?") +``` + +#### Local Compute Tokens + +```python +tokenizer = genai.LocalTokenizer(model_name='gemini-2.5-flash') +result = tokenizer.compute_tokens("What is your name?") +``` + +### Embed Content + +```python +response = client.models.embed_content( + model='gemini-embedding-001', + contents='why is the sky blue?', +) +print(response) +``` + +```python +from google.genai import types + +response = client.models.embed_content( + model='gemini-embedding-001', + contents=['why is the sky blue?', 'What is your age?'], + config=types.EmbedContentConfig(output_dimensionality=10), +) + +print(response) +``` + +### Imagen + +#### Generate Images + +```python +from google.genai import types + +response1 = client.models.generate_images( + model='imagen-4.0-generate-001', + prompt='An umbrella in the foreground, and a rainy night sky in the background', + config=types.GenerateImagesConfig( + number_of_images=1, + include_rai_reason=True, + output_mime_type='image/jpeg', + ), +) +response1.generated_images[0].image.show() +``` + +#### Upscale Image + +Upscale image is only supported in Vertex AI. + +```python +from google.genai import types + +response2 = client.models.upscale_image( + model='imagen-4.0-upscale-preview', + image=response1.generated_images[0].image, + upscale_factor='x2', + config=types.UpscaleImageConfig( + include_rai_reason=True, + output_mime_type='image/jpeg', + ), +) +response2.generated_images[0].image.show() +``` + +#### Edit Image + +Edit image uses a separate model from generate and upscale. + +Edit image is only supported in Vertex AI. + +```python +# Edit the generated image from above +from google.genai import types +from google.genai.types import RawReferenceImage, MaskReferenceImage + +raw_ref_image = RawReferenceImage( + reference_id=1, + reference_image=response1.generated_images[0].image, +) + +# Model computes a mask of the background +mask_ref_image = MaskReferenceImage( + reference_id=2, + config=types.MaskReferenceConfig( + mask_mode='MASK_MODE_BACKGROUND', + mask_dilation=0, + ), +) + +response3 = client.models.edit_image( + model='imagen-3.0-capability-001', + prompt='Sunlight and clear sky', + reference_images=[raw_ref_image, mask_ref_image], + config=types.EditImageConfig( + edit_mode='EDIT_MODE_INPAINT_INSERTION', + number_of_images=1, + include_rai_reason=True, + output_mime_type='image/jpeg', + ), +) +response3.generated_images[0].image.show() +``` + +### Veo + +Support for generating videos is considered public preview + +#### Generate Videos (Text to Video) + +```python +from google.genai import types + +# Create operation +operation = client.models.generate_videos( + model='veo-3.1-generate-preview', + prompt='A neon hologram of a cat driving at top speed', + config=types.GenerateVideosConfig( + number_of_videos=1, + duration_seconds=5, + enhance_prompt=True, + ), +) + +# Poll operation +while not operation.done: + time.sleep(20) + operation = client.operations.get(operation) + +video = operation.response.generated_videos[0].video +video.show() +``` + +#### Generate Videos (Image to Video) + +```python +from google.genai import types + +# Read local image (uses mimetypes.guess_type to infer mime type) +image = types.Image.from_file("local/path/file.png") + +# Create operation +operation = client.models.generate_videos( + model='veo-3.1-generate-preview', + # Prompt is optional if image is provided + prompt='Night sky', + image=image, + config=types.GenerateVideosConfig( + number_of_videos=1, + duration_seconds=5, + enhance_prompt=True, + # Can also pass an Image into last_frame for frame interpolation + ), +) + +# Poll operation +while not operation.done: + time.sleep(20) + operation = client.operations.get(operation) + +video = operation.response.generated_videos[0].video +video.show() +``` + +#### Generate Videos (Video to Video) + +Currently, only Gemini Developer API supports video extension on Veo 3.1 for +previously generated videos. Vertex supports video extension on Veo 2.0. + +```python +from google.genai import types + +# Read local video (uses mimetypes.guess_type to infer mime type) +video = types.Video.from_file("local/path/video.mp4") + +# Create operation +operation = client.models.generate_videos( + model='veo-3.1-generate-preview', + # Prompt is optional if Video is provided + prompt='Night sky', + # Input video must be in GCS for Vertex or a URI for Gemini + video=types.Video( + uri="gs://bucket-name/inputs/videos/cat_driving.mp4", + ), + config=types.GenerateVideosConfig( + number_of_videos=1, + duration_seconds=5, + enhance_prompt=True, + ), +) + +# Poll operation +while not operation.done: + time.sleep(20) + operation = client.operations.get(operation) + +video = operation.response.generated_videos[0].video +video.show() +``` + +## Chats + +Create a chat session to start a multi-turn conversations with the model. Then, +use `chat.send_message` function multiple times within the same chat session so +that it can reflect on its previous responses (i.e., engage in an ongoing + conversation). See the 'Create a client' section above to initialize a client. + +### Send Message (Synchronous Non-Streaming) + +```python +chat = client.chats.create(model='gemini-2.5-flash') +response = chat.send_message('tell me a story') +print(response.text) +response = chat.send_message('summarize the story you told me in 1 sentence') +print(response.text) +``` + +### Send Message (Synchronous Streaming) + +```python +chat = client.chats.create(model='gemini-2.5-flash') +for chunk in chat.send_message_stream('tell me a story'): + print(chunk.text) +``` + +### Send Message (Asynchronous Non-Streaming) + +```python +chat = client.aio.chats.create(model='gemini-2.5-flash') +response = await chat.send_message('tell me a story') +print(response.text) +``` + +### Send Message (Asynchronous Streaming) + +```python +chat = client.aio.chats.create(model='gemini-2.5-flash') +async for chunk in await chat.send_message_stream('tell me a story'): + print(chunk.text) +``` + +## Files + +Files are only supported in Gemini Developer API. See the 'Create a client' +section above to initialize a client. + +```sh +!gcloud storage cp gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf . +!gcloud storage cp gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf . +``` + +### Upload + +```python +file1 = client.files.upload(file='2312.11805v3.pdf') +file2 = client.files.upload(file='2403.05530.pdf') + +print(file1) +print(file2) +``` + +### Get + +```python +file1 = client.files.upload(file='2312.11805v3.pdf') +file_info = client.files.get(name=file1.name) +``` + +### Delete + +```python +file3 = client.files.upload(file='2312.11805v3.pdf') + +client.files.delete(name=file3.name) +``` + +## Caches + +`client.caches` contains the control plane APIs for cached content. See the +'Create a client' section above to initialize a client. + +### Create + +```python +from google.genai import types + +if client.vertexai: + file_uris = [ + 'gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf', + 'gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf', + ] +else: + file_uris = [file1.uri, file2.uri] + +cached_content = client.caches.create( + model='gemini-2.5-flash', + config=types.CreateCachedContentConfig( + contents=[ + types.Content( + role='user', + parts=[ + types.Part.from_uri( + file_uri=file_uris[0], mime_type='application/pdf' + ), + types.Part.from_uri( + file_uri=file_uris[1], + mime_type='application/pdf', + ), + ], + ) + ], + system_instruction='What is the sum of the two pdfs?', + display_name='test cache', + ttl='3600s', + ), +) +``` + +### Get + +```python +cached_content = client.caches.get(name=cached_content.name) +``` + +### Generate Content with Caches + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.5-flash', + contents='Summarize the pdfs', + config=types.GenerateContentConfig( + cached_content=cached_content.name, + ), +) +print(response.text) +``` + +## Interactions (Preview) + +> **Warning:** The Interactions API is in **Beta**. This is a preview of an experimental feature. Features and schemas are subject to **breaking changes**. + +The Interactions API is a unified interface for interacting with Gemini models and agents. It simplifies state management, tool orchestration, and long-running tasks. + +See the [documentation site](https://ai.google.dev/gemini-api/docs/interactions) for more details. + +### Basic Interaction + +```python +interaction = client.interactions.create( + model='gemini-2.5-flash', + input='Tell me a short joke about programming.' +) +print(interaction.outputs[-1].text) + +``` + +### Stateful Conversation + +The Interactions API supports server-side state management. You can continue a conversation by referencing the `previous_interaction_id`. + +```python +# 1. First turn +interaction1 = client.interactions.create( + model='gemini-2.5-flash', + input='Hi, my name is Amir.' +) +print(f"Model: {interaction1.outputs[-1].text}") + +# 2. Second turn (passing previous_interaction_id) +interaction2 = client.interactions.create( + model='gemini-2.5-flash', + input='What is my name?', + previous_interaction_id=interaction1.id +) +print(f"Model: {interaction2.outputs[-1].text}") + +``` + +### Agents (Deep Research) + +You can use specialized agents like `deep-research-pro-preview-12-2025` for complex tasks. + +```python +import time + +# 1. Start the Deep Research Agent +initial_interaction = client.interactions.create( + input='Research the history of the Google TPUs with a focus on 2025 and 2026.', + agent='deep-research-pro-preview-12-2025', + background=True +) +print(f"Research started. Interaction ID: {initial_interaction.id}") + +# 2. Poll for results +while True: + interaction = client.interactions.get(id=initial_interaction.id) + print(f"Status: {interaction.status}") + + if interaction.status == "completed": + print("\nFinal Report:\n", interaction.outputs[-1].text) + break + elif interaction.status in ["failed", "cancelled"]: + print(f"Failed with status: {interaction.status}") + break + + time.sleep(10) + +``` + +### Multimodal Input + +You can provide multimodal data (text, images, audio, etc.) in the input list. + +```python +import base64 + +# Assuming you have an image loaded as bytes +# base64_image = ... + +interaction = client.interactions.create( + model='gemini-2.5-flash', + input=[ + {'type': 'text', 'text': 'Describe the image.'}, + {'type': 'image', 'data': base64_image, 'mime_type': 'image/png'} + ] +) +print(interaction.outputs[-1].text) + +``` + +### Function Calling + +You can define custom functions for the model to use. The Interactions API handles the tool selection, and you provide the execution result back to the model. + +```python +# 1. Define the tool +def get_weather(location: str): + """Gets the weather for a given location.""" + return f"The weather in {location} is sunny." + +weather_tool = { + 'type': 'function', + 'name': 'get_weather', + 'description': 'Gets the weather for a given location.', + 'parameters': { + 'type': 'object', + 'properties': { + 'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'} + }, + 'required': ['location'] + } +} + +# 2. Send the request with tools +interaction = client.interactions.create( + model='gemini-2.5-flash', + input='What is the weather in Mountain View, CA?', + tools=[weather_tool] +) + +# 3. Handle the tool call +for output in interaction.outputs: + if output.type == 'function_call': + print(f"Tool Call: {output.name}({output.arguments})") + + # Execute your actual function here + result = get_weather(**output.arguments) + + # Send result back to the model + interaction = client.interactions.create( + model='gemini-2.5-flash', + previous_interaction_id=interaction.id, + input=[{ + 'type': 'function_result', + 'name': output.name, + 'call_id': output.id, + 'result': result + }] + ) + print(f"Response: {interaction.outputs[-1].text}") + +``` + +### Built-in Tools +You can also use Google's built-in tools, such as **Google Search** or **Code Execution**. + +#### Grounding with Google Search + +```python +interaction = client.interactions.create( + model='gemini-2.5-flash', + input='Who won the last Super Bowl?', + tools=[{'type': 'google_search'}] +) + +# Find the text output (not the GoogleSearchResultContent) +text_output = next((o for o in interaction.outputs if o.type == 'text'), None) +if text_output: + print(text_output.text) + +``` + +#### Code Execution + +```python +interaction = client.interactions.create( + model='gemini-2.5-flash', + input='Calculate the 50th Fibonacci number.', + tools=[{'type': 'code_execution'}] +) +print(interaction.outputs[-1].text) + +``` + +### Multimodal Output + +The Interactions API can generate multimodal outputs, such as images. You must specify the `response_modalities`. + +```python +import base64 + +interaction = client.interactions.create( + model='gemini-3-pro-image-preview', + input='Generate an image of a futuristic city.', + response_modalities=['IMAGE'] +) + +for output in interaction.outputs: + if output.type == 'image': + print(f"Generated image with mime_type: {output.mime_type}") + # Save the image + with open("generated_city.png", "wb") as f: + f.write(base64.b64decode(output.data)) + +``` + +## Tunings + +`client.tunings` contains tuning job APIs and supports supervised fine +tuning through `tune`. Only supported in Vertex AI. See the 'Create a client' +section above to initialize a client. + +### Tune + +- Vertex AI supports tuning from GCS source or from a [Vertex AI Multimodal Dataset](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/datasets) + +```python +from google.genai import types + +model = 'gemini-2.5-flash' +training_dataset = types.TuningDataset( + # or gcs_uri=my_vertex_multimodal_dataset + gcs_uri='gs://your-gcs-bucket/your-tuning-data.jsonl', +) +``` + +```python +from google.genai import types + +tuning_job = client.tunings.tune( + base_model=model, + training_dataset=training_dataset, + config=types.CreateTuningJobConfig( + epoch_count=1, tuned_model_display_name='test_dataset_examples model' + ), +) +print(tuning_job) +``` + +### Get Tuning Job + +```python +tuning_job = client.tunings.get(name=tuning_job.name) +print(tuning_job) +``` + +```python +import time + +completed_states = set( + [ + 'JOB_STATE_SUCCEEDED', + 'JOB_STATE_FAILED', + 'JOB_STATE_CANCELLED', + ] +) + +while tuning_job.state not in completed_states: + print(tuning_job.state) + tuning_job = client.tunings.get(name=tuning_job.name) + time.sleep(10) +``` + +#### Use Tuned Model + +```python +response = client.models.generate_content( + model=tuning_job.tuned_model.endpoint, + contents='why is the sky blue?', +) + +print(response.text) +``` + +### Get Tuned Model + +```python +tuned_model = client.models.get(model=tuning_job.tuned_model.model) +print(tuned_model) +``` + +### List Tuned Models + +To retrieve base models, see [list base models](#list-base-models). + +```python +for model in client.models.list(config={'page_size': 10, 'query_base': False}): + print(model) +``` + +```python +pager = client.models.list(config={'page_size': 10, 'query_base': False}) +print(pager.page_size) +print(pager[0]) +pager.next_page() +print(pager[0]) +``` + +#### Async + +```python +async for job in await client.aio.models.list(config={'page_size': 10, 'query_base': False}): + print(job) +``` + +```python +async_pager = await client.aio.models.list(config={'page_size': 10, 'query_base': False}) +print(async_pager.page_size) +print(async_pager[0]) +await async_pager.next_page() +print(async_pager[0]) +``` + +### Update Tuned Model + +```python +from google.genai import types + +model = pager[0] + +model = client.models.update( + model=model.name, + config=types.UpdateModelConfig( + display_name='my tuned model', description='my tuned model description' + ), +) + +print(model) +``` + + +### List Tuning Jobs + +```python +for job in client.tunings.list(config={'page_size': 10}): + print(job) +``` + +```python +pager = client.tunings.list(config={'page_size': 10}) +print(pager.page_size) +print(pager[0]) +pager.next_page() +print(pager[0]) +``` + +#### Async + +```python +async for job in await client.aio.tunings.list(config={'page_size': 10}): + print(job) +``` + +```python +async_pager = await client.aio.tunings.list(config={'page_size': 10}) +print(async_pager.page_size) +print(async_pager[0]) +await async_pager.next_page() +print(async_pager[0]) +``` + +## Batch Prediction + +Only supported in Vertex AI. See the 'Create a client' section above to +initialize a client. + +### Create + +Vertex AI: + +```python +# Specify model and source file only, destination and job display name will be auto-populated +job = client.batches.create( + model='gemini-2.5-flash', + src='bq://my-project.my-dataset.my-table', # or "gs://path/to/input/data" +) + +print(job) +``` + +Gemini Developer API: + +```python +# Create a batch job with inlined requests +batch_job = client.batches.create( + model="gemini-2.5-flash", + src=[{ + "contents": [{ + "parts": [{ + "text": "Hello!", + }], + "role": "user", + }], + "config": {"response_modalities": ["text"]}, + }], +) + +job +``` + +In order to create a batch job with file name. Need to upload a json file. +For example `myrequests.json`: + +```json +{"key":"request_1", "request": {"contents": [{"parts": [{"text": + "Explain how AI works in a few words"}]}], "generation_config": {"response_modalities": ["TEXT"]}}} +{"key":"request_2", "request": {"contents": [{"parts": [{"text": "Explain how Crypto works in a few words"}]}]}} +``` + +Then upload the file. + +```python +# Upload the file +file = client.files.upload( + file='myrequests.json', + config=types.UploadFileConfig(display_name='test-json') +) + +# Create a batch job with file name +batch_job = client.batches.create( + model="gemini-2.5-flash", + src="files/test-json", +) +``` + +```python +# Get a job by name +job = client.batches.get(name=job.name) + +job.state +``` + +```python +completed_states = set( + [ + 'JOB_STATE_SUCCEEDED', + 'JOB_STATE_FAILED', + 'JOB_STATE_CANCELLED', + 'JOB_STATE_PAUSED', + ] +) + +while job.state not in completed_states: + print(job.state) + job = client.batches.get(name=job.name) + time.sleep(30) + +job +``` + +### List + +```python +for job in client.batches.list(config=types.ListBatchJobsConfig(page_size=10)): + print(job) +``` + +```python +pager = client.batches.list(config=types.ListBatchJobsConfig(page_size=10)) +print(pager.page_size) +print(pager[0]) +pager.next_page() +print(pager[0]) +``` + +#### Async + +```python +async for job in await client.aio.batches.list( + config=types.ListBatchJobsConfig(page_size=10) +): + print(job) +``` + +```python +async_pager = await client.aio.batches.list( + config=types.ListBatchJobsConfig(page_size=10) +) +print(async_pager.page_size) +print(async_pager[0]) +await async_pager.next_page() +print(async_pager[0]) +``` + +### Delete + +```python +# Delete the job resource +delete_job = client.batches.delete(name=job.name) + +delete_job +``` + +## Error Handling + +To handle errors raised by the model service, the SDK provides this [`APIError`](https://github.com/googleapis/python-genai/blob/main/google/genai/errors.py) class. + +```python +from google.genai import errors + +try: + client.models.generate_content( + model="invalid-model-name", + contents="What is your name?", + ) +except errors.APIError as e: + print(e.code) # 404 + print(e.message) +``` + +## Extra Request Body + +The `extra_body` field in `HttpOptions` accepts a dictionary of additional JSON +properties to include in the request body. This can be used to access new or +experimental backend features that are not yet formally supported in the SDK. +The structure of the dictionary must match the backend API's request structure. + +- Vertex AI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest +- Gemini API backend API docs: https://ai.google.dev/api/rest + +```python +response = client.models.generate_content( + model="gemini-2.5-pro", + contents="What is the weather in Boston? and how about Sunnyvale?", + config=types.GenerateContentConfig( + tools=[get_current_weather], + http_options=types.HttpOptions(extra_body={'tool_config': {'function_calling_config': {'mode': 'COMPOSITIONAL'}}}), + ), +) +``` diff --git a/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6ff4daa13493d91b33b347b3d30366ddf66dc272 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/RECORD @@ -0,0 +1,726 @@ +google/genai/__init__.py,sha256=dIAk6AHhyy3b77cVKPvDyrZzkd9ibddrHZuieCq_eaA,756 +google/genai/__pycache__/__init__.cpython-313.pyc,, +google/genai/__pycache__/_adapters.cpython-313.pyc,, +google/genai/__pycache__/_api_client.cpython-313.pyc,, +google/genai/__pycache__/_api_module.cpython-313.pyc,, +google/genai/__pycache__/_automatic_function_calling_util.cpython-313.pyc,, +google/genai/__pycache__/_base_transformers.cpython-313.pyc,, +google/genai/__pycache__/_base_url.cpython-313.pyc,, +google/genai/__pycache__/_common.cpython-313.pyc,, +google/genai/__pycache__/_extra_utils.cpython-313.pyc,, +google/genai/__pycache__/_live_converters.cpython-313.pyc,, +google/genai/__pycache__/_local_tokenizer_loader.cpython-313.pyc,, +google/genai/__pycache__/_mcp_utils.cpython-313.pyc,, +google/genai/__pycache__/_operations_converters.cpython-313.pyc,, +google/genai/__pycache__/_replay_api_client.cpython-313.pyc,, +google/genai/__pycache__/_test_api_client.cpython-313.pyc,, +google/genai/__pycache__/_tokens_converters.cpython-313.pyc,, +google/genai/__pycache__/_transformers.cpython-313.pyc,, +google/genai/__pycache__/batches.cpython-313.pyc,, +google/genai/__pycache__/caches.cpython-313.pyc,, +google/genai/__pycache__/chats.cpython-313.pyc,, +google/genai/__pycache__/client.cpython-313.pyc,, +google/genai/__pycache__/documents.cpython-313.pyc,, +google/genai/__pycache__/errors.cpython-313.pyc,, +google/genai/__pycache__/file_search_stores.cpython-313.pyc,, +google/genai/__pycache__/files.cpython-313.pyc,, +google/genai/__pycache__/interactions.cpython-313.pyc,, +google/genai/__pycache__/live.cpython-313.pyc,, +google/genai/__pycache__/live_music.cpython-313.pyc,, +google/genai/__pycache__/local_tokenizer.cpython-313.pyc,, +google/genai/__pycache__/models.cpython-313.pyc,, +google/genai/__pycache__/operations.cpython-313.pyc,, +google/genai/__pycache__/pagers.cpython-313.pyc,, +google/genai/__pycache__/tokens.cpython-313.pyc,, +google/genai/__pycache__/tunings.cpython-313.pyc,, +google/genai/__pycache__/types.cpython-313.pyc,, +google/genai/__pycache__/version.cpython-313.pyc,, +google/genai/_adapters.py,sha256=Kok38miNYJff2n--l0zEK_hbq0y2rWOH7k75J7SMYbQ,1744 +google/genai/_api_client.py,sha256=Ofm7DZgAWAOG7kGZPwyat3s5O2-NYkIWpr4RHaUvRTE,76083 +google/genai/_api_module.py,sha256=lj8eUWx8_LBGBz-49qz6_ywWm3GYp3d8Bg5JoOHbtbI,902 +google/genai/_automatic_function_calling_util.py,sha256=xXNkJR-pzSMkeSXMz3Jw-kMHFbTJEiRJ3wocuwtWW4I,11627 +google/genai/_base_transformers.py,sha256=wljA6m4tLl4XLGlBC2DNOls5N9-X9tffBq0M7i8jgpw,1034 +google/genai/_base_url.py,sha256=E5H4dew14Y16qfnB3XRnjSCi19cJVlkaMNoM_8ip-PM,1597 +google/genai/_common.py,sha256=XY1eXuzSnPcBx4Fuk2EOvP8xboW4ef6JrOs6uhG7_l4,26544 +google/genai/_extra_utils.py,sha256=64oZAxmRHdTdY8cStpU8T1mMWsi08ND-t9aoC8gcCtM,25403 +google/genai/_interactions/__init__.py,sha256=Zl5wlyZ1be3a1ENIERjj9ocpELL89RdZkHF3MnCkB3M,3571 +google/genai/_interactions/__pycache__/__init__.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_base_client.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_client.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_client_adapter.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_compat.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_constants.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_exceptions.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_files.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_models.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_qs.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_resource.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_response.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_streaming.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_types.cpython-313.pyc,, +google/genai/_interactions/__pycache__/_version.cpython-313.pyc,, +google/genai/_interactions/_base_client.py,sha256=74TV62DtGdRyVQlU818zMvXMDVkpwpEaboJX5najHCg,74013 +google/genai/_interactions/_client.py,sha256=-kobwfZCBK9hwhSF8tA87IAgKtd8BDVILhW68oRNY18,21108 +google/genai/_interactions/_client_adapter.py,sha256=QLQa352-22JgCa72uFo0UGzZr0v-BaTZ4yUVKCQ5LIU,1349 +google/genai/_interactions/_compat.py,sha256=czywtWjj7E01kx0psVmhLJEKDQV1FtClukOG0M5Otzs,7388 +google/genai/_interactions/_constants.py,sha256=t7rpey7f7Z65WNYx8OzR-VGkTEHaz_WCLOREzHLjFhk,1039 +google/genai/_interactions/_exceptions.py,sha256=n421n5EZ4v7MHqIrBm505dytWRsAI52u_yuvZZ4vprE,3829 +google/genai/_interactions/_files.py,sha256=K7qgCZWoSaNI4RrdY1cUnNMXNF3Usq1IgCvzqwFgfMQ,4144 +google/genai/_interactions/_models.py,sha256=zfKeV3VeGCG2J8Xieu7ClHwewEpQQdvLfDUn34ebxUQ,32711 +google/genai/_interactions/_qs.py,sha256=EM8TBHM3wnCBUK9M0CmimdRgOYVbzUQtcHpmSpOmoKM,5501 +google/genai/_interactions/_resource.py,sha256=2SnZ1mvldUzurojYs_Pg_aItzP5A9WmhjjMCh_dXnCg,1773 +google/genai/_interactions/_response.py,sha256=BLssmkqOR8kQXiykbFgENShXv0_V33e3ifjgKcORm5I,29644 +google/genai/_interactions/_streaming.py,sha256=nSWWNU06ioJF4v8ZK2RcnAxIRo0EaBoUbDWRyCuOf60,11345 +google/genai/_interactions/_types.py,sha256=TjWdymD1c9FJG7ddPpyxhR-imYoYr5HHPeBqum3qt-s,8191 +google/genai/_interactions/_utils/__init__.py,sha256=Ko2pAw5_20UK2PHNQO8lnEjzs-VBHlNR5ykB0OLdTpg,2932 +google/genai/_interactions/_utils/__pycache__/__init__.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_compat.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_datetime_parse.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_json.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_logs.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_path.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_proxy.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_reflection.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_resources_proxy.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_streams.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_sync.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_transform.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_typing.cpython-313.pyc,, +google/genai/_interactions/_utils/__pycache__/_utils.cpython-313.pyc,, +google/genai/_interactions/_utils/_compat.py,sha256=ZHNNL7ES64w9qQfW6mXtIf2yTQ-dI29aP2ZWmOukSVk,1830 +google/genai/_interactions/_utils/_datetime_parse.py,sha256=dYUm7Y3pBD4dzQmpr-onIalbkEQH8gSqdSok5wx24wE,4781 +google/genai/_interactions/_utils/_json.py,sha256=miy3kDffBjNQQQyYCVdHiMRU-ymfcXI2nyY7S6_Efzs,1539 +google/genai/_interactions/_utils/_logs.py,sha256=z9QPllBTUdyCkIpb3iHi_NZnM3GTG_OQtD4t1Htpex4,1404 +google/genai/_interactions/_utils/_path.py,sha256=FHlQFyyrZCVZRkB-zKJKrRvW8Vkbj-dzpthl2kkYUPE,5278 +google/genai/_interactions/_utils/_proxy.py,sha256=V_QfMtbDL4_OFaYynWeyCCkP7KPBuV7GEJspth55rS0,2552 +google/genai/_interactions/_utils/_reflection.py,sha256=F4i9cYP3sGnxZ-dhp3lcFSRiB115znLodOM-gcVh-wA,1941 +google/genai/_interactions/_utils/_resources_proxy.py,sha256=oblNXyW_PaDX3oFD5HPfSj4nEk5t7yTfPN6CXfMchv8,1266 +google/genai/_interactions/_utils/_streams.py,sha256=qFn4GbF3Vvdx7oc65J7WjeEyUBF8rlMB_HvubXAlhII,866 +google/genai/_interactions/_utils/_sync.py,sha256=mLePq9GOEBxScaapheKwO4ON-pCfXpzktYj6a5xdKTQ,2166 +google/genai/_interactions/_utils/_transform.py,sha256=TjAN4LumRdzvMD0rcrFQhrlC31Mivg-c2kgRBIrn4Cg,16528 +google/genai/_interactions/_utils/_typing.py,sha256=Z5S4PcLWBL5GEhqU6j_XKaoh9ANrTSDyMDDTlMB0KJ8,5385 +google/genai/_interactions/_utils/_utils.py,sha256=qWdNSrAUkn_wYeK5YFSeHyZWtEYJQkbh_Sg2t7impKQ,12851 +google/genai/_interactions/_version.py,sha256=HYUoiFQBODx2RJNZpIxeUnGFUe8Gc9FEO6tSeZQgO-I,668 +google/genai/_interactions/resources/__init__.py,sha256=TNMFv_-Zv9ayAgjkecVIBOnIK-goQIIvkvR3WiQl_DA,1207 +google/genai/_interactions/resources/__pycache__/__init__.cpython-313.pyc,, +google/genai/_interactions/resources/__pycache__/interactions.cpython-313.pyc,, +google/genai/_interactions/resources/interactions.py,sha256=z6S9UBbRK5ftMgbzZcqc3mBkWWRTUSzYlpE4fEq8YaU,59843 +google/genai/_interactions/types/__init__.py,sha256=dmUkgjtxwm-aMx9pY6Ni5HEkx5DHoLKySmfTh_slVII,8521 +google/genai/_interactions/types/__pycache__/__init__.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/allowed_tools.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/allowed_tools_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/annotation.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/annotation_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/audio_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/audio_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/code_execution_call_arguments.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/code_execution_call_arguments_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/code_execution_call_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/code_execution_call_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/code_execution_result_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/code_execution_result_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/content_delta.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/content_start.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/content_stop.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/deep_research_agent_config.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/deep_research_agent_config_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/document_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/document_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/dynamic_agent_config.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/dynamic_agent_config_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/error_event.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/file_citation.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/file_citation_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/file_search_call_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/file_search_call_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/file_search_result_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/file_search_result_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/function.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/function_call_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/function_call_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/function_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/function_result_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/function_result_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/generation_config.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/generation_config_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_maps_call_arguments.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_maps_call_arguments_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_maps_call_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_maps_call_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_maps_result.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_maps_result_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_maps_result_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_maps_result_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_search_call_arguments.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_search_call_arguments_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_search_call_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_search_call_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_search_result.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_search_result_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_search_result_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/google_search_result_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/image_config.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/image_config_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/image_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/image_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/interaction.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/interaction_complete_event.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/interaction_create_params.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/interaction_get_params.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/interaction_sse_event.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/interaction_start_event.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/interaction_status_update.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/mcp_server_tool_call_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/mcp_server_tool_call_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/mcp_server_tool_result_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/mcp_server_tool_result_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/model.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/model_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/place_citation.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/place_citation_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/speech_config.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/speech_config_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/text_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/text_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/thinking_level.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/thought_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/thought_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/tool.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/tool_choice_config.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/tool_choice_config_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/tool_choice_type.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/tool_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/turn.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/turn_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_citation.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_citation_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_context_call_arguments.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_context_call_arguments_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_context_call_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_context_call_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_context_result.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_context_result_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_context_result_content_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/url_context_result_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/usage.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/usage_param.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/video_content.cpython-313.pyc,, +google/genai/_interactions/types/__pycache__/video_content_param.cpython-313.pyc,, +google/genai/_interactions/types/allowed_tools.py,sha256=Hke2IEAT_lc51MCt0_tGZGx3yvE7HTSawIlm-prCCGg,1047 +google/genai/_interactions/types/allowed_tools_param.py,sha256=PAAFKM2qX_Pj_pTxqcc0IQvii9soKLW_scMud2nUwMc,1092 +google/genai/_interactions/types/annotation.py,sha256=ETbr__1wXt6GG5LiVLPCfd-ZpvKbEu1086tsH0zZzzs,1041 +google/genai/_interactions/types/annotation_param.py,sha256=rFA_9Im9pxF_AvFyZn1C3QyNnz1XSp_iIk0pyNkWK3w,1043 +google/genai/_interactions/types/audio_content.py,sha256=g_ByLpUFfQvx2saBIeplbL_M6wvv2U2MgD4ilEHuUlg,1569 +google/genai/_interactions/types/audio_content_param.py,sha256=FhRBuXsNxlAOK9Y1d7ecMUeFOwEaiSIJspLhXX6IkuQ,1739 +google/genai/_interactions/types/code_execution_call_arguments.py,sha256=0EaxrwSqMBrASkdMBDktqgM0ou2iWO1Llq49swL6d0M,1070 +google/genai/_interactions/types/code_execution_call_arguments_param.py,sha256=gvbXJt_cdTCpU7WQo1IeM0Bj-E5Hrj3H2OybcnlO9NE,1045 +google/genai/_interactions/types/code_execution_call_content.py,sha256=yax82QDz_uDZCpTwgIAywxOzbaSs29UcgwCTuLnjiY0,1264 +google/genai/_interactions/types/code_execution_call_content_param.py,sha256=UGPdsgX5mefInCBaL1Y7gZRLW5p0Ge486hzGhoybiWQ,1616 +google/genai/_interactions/types/code_execution_result_content.py,sha256=2Ww4fYSWq-YlX3J24RjteVkZ2Yl0HTlN-0SJxFNCkHI,1279 +google/genai/_interactions/types/code_execution_result_content_param.py,sha256=-OWruENx0p2S-nX9RggU2-_XWQJx8fGBJrBHaVWY2xc,1600 +google/genai/_interactions/types/content.py,sha256=gZQ4ADYw8g29CoanKYrnubY1JVGXbK-UGAfVPWE53lI,2627 +google/genai/_interactions/types/content_delta.py,sha256=7xuPcBXdUFa9_TrvWRAXpOoJDbo--_TiuN4KE1oT1nQ,10979 +google/genai/_interactions/types/content_param.py,sha256=uPEd5NHMJ3zy4ut14T5LRKkxAob3GC1cDtu94FiWTTw,2806 +google/genai/_interactions/types/content_start.py,sha256=oYUEPoIA1iuJFRFs68Z23tDBWsFRrlW6AzbFpNgJRjY,1108 +google/genai/_interactions/types/content_stop.py,sha256=NX9fN1yajDJVhWboJphGd6kOJnu6gqgrcTm8LoNlQr8,1015 +google/genai/_interactions/types/deep_research_agent_config.py,sha256=zDMOn7V91OHpY04PIkAHhHlV3VtHyxKu9IvWVG8m9qw,1065 +google/genai/_interactions/types/deep_research_agent_config_param.py,sha256=8Zp-A7Vg4oupnNUUFYuZfeqWxCPBn5c5etfzSzFXqsU,1077 +google/genai/_interactions/types/document_content.py,sha256=fkuFMcmaRhXTRgSjYF3YRCHb300cL368YKpLVHxYgW0,1128 +google/genai/_interactions/types/document_content_param.py,sha256=_D6Eipyw6UmonmvZ583G3cMRQai0DZ9k5wCV9bxRMos,1401 +google/genai/_interactions/types/dynamic_agent_config.py,sha256=NyUhUFhyyyZEqLPZPaKhD7yZ9NzPSnAMLzTb2KzlSwo,1580 +google/genai/_interactions/types/dynamic_agent_config_param.py,sha256=uMWAhhZRDU_PAFYiWmNZQBMw-0CodgUNokAJTcmrZrc,985 +google/genai/_interactions/types/error_event.py,sha256=aeqwnjmbfQNbd0Am6UkIsbK198pNJUWQs8bGj7u_90g,1307 +google/genai/_interactions/types/file_citation.py,sha256=Cc6jOQX7i9gMZ8igoeB9reLsPpGnESzkxz37_h55pHQ,1404 +google/genai/_interactions/types/file_citation_param.py,sha256=Dxzt7ttPP8OAL11bjt9ZGBkRvq3T1_TB1Cm5-HFvtsY,1348 +google/genai/_interactions/types/file_search_call_content.py,sha256=Vs_tq5uKCZvzxNWIA3Ji78BD7YL5c5mLrx0BrKldtXI,1074 +google/genai/_interactions/types/file_search_call_content_param.py,sha256=M9HSNqVtLYu5H9qmtiKJCIJO3UxIZ6-f8CRLUtEytus,1397 +google/genai/_interactions/types/file_search_result_content.py,sha256=yD9DuUJdjFVEhkL6Ilu9dFGK5gSiwCzyRBgRTzhMkBY,1375 +google/genai/_interactions/types/file_search_result_content_param.py,sha256=tsk_wcB1yg-tNgCbGvnUgh7akQAR351eGTJSbcnWOlQ,1718 +google/genai/_interactions/types/function.py,sha256=0lh1qn73ZVJ7THAOq0pcfUV_37u9VspSCMlOXVKUed4,1141 +google/genai/_interactions/types/function_call_content.py,sha256=aosD1i3Cwa3IBzWTUbvxJcCLJM0mbYPSLi9c1eknaHA,1246 +google/genai/_interactions/types/function_call_content_param.py,sha256=0vRud8LlBu7wi9XByKLt9CQb-B5Ao9QGfGoPDc0NPTQ,1587 +google/genai/_interactions/types/function_param.py,sha256=GMSumys9sCsWix9f4db6Pbc3pg7mGYrQJgWuawiANAY,1119 +google/genai/_interactions/types/function_result_content.py,sha256=HXghuuPZcIuHlDpf0ZokuIp26l0jBnqHVKNXyuc_YxM,1707 +google/genai/_interactions/types/function_result_content_param.py,sha256=HqY2xah3bxk7PHNI1VtdftoEIyaQ2sqIPYMuwhSxGfw,1941 +google/genai/_interactions/types/generation_config.py,sha256=1c9KMbI2kmUm7n788GOSv0836v3qSSiWgv0xceJOeBo,2273 +google/genai/_interactions/types/generation_config_param.py,sha256=VOLJE_qLWHhgRYMExo-5u-epTWk-IZFq6pQl7fsDGK0,2233 +google/genai/_interactions/types/google_maps_call_arguments.py,sha256=PRkXc9ysgwVQ8SiD2TpWd-JqdvRXyzFlWu05yZX774g,950 +google/genai/_interactions/types/google_maps_call_arguments_param.py,sha256=-oY_if4CWdYWVSChg9bcKlCJ_snpSBOEectLePQ-Ftk,1012 +google/genai/_interactions/types/google_maps_call_content.py,sha256=Kfyhg-GUo6y5-NurGKnEEgut01AkhnAj2dJKT0ZE6ag,1252 +google/genai/_interactions/types/google_maps_call_content_param.py,sha256=jgXTcryMB7ynWRO2j3gjBWsPN2ngMmju7wCmCpvfemg,1574 +google/genai/_interactions/types/google_maps_result.py,sha256=TmcqSuBEqpmxJSKo3OtkvufJ1FGOrMWtBwybEeOUwbM,1936 +google/genai/_interactions/types/google_maps_result_content.py,sha256=8lK5wAvHbo2-XJSv3_eKDa16-OjEyasCUZGayuBOR-E,1243 +google/genai/_interactions/types/google_maps_result_content_param.py,sha256=4b38zZ9lby4TgfEcpQRoL6VEOMB93aYdHWQfh6zoquc,1602 +google/genai/_interactions/types/google_maps_result_param.py,sha256=i1A5vWezu1AwfMpvFQ0crzVgcn6cAixqr-QNoEc6SSQ,1877 +google/genai/_interactions/types/google_search_call_arguments.py,sha256=KZbdLhr6kFCZruO-nIkZaq2qm_wMlQjH65xZHwlfOGU,971 +google/genai/_interactions/types/google_search_call_arguments_param.py,sha256=6W-HI1t2QOFJWDy8yfNU88ACq9sxigFufi74AIqMQX8,1033 +google/genai/_interactions/types/google_search_call_content.py,sha256=HWAABJ4XUSnZPOPglZ5KyhwVpen9JsslozlmjjOWeDQ,1398 +google/genai/_interactions/types/google_search_call_content_param.py,sha256=an92spR3r47mP4QgERvkp7To0JP8UJKaKCXYcM8FP6A,1732 +google/genai/_interactions/types/google_search_result.py,sha256=z3oMxXjXkB1z5y7RdEiKko0i5xwBwCGZ9ly9FCSvS28,971 +google/genai/_interactions/types/google_search_result_content.py,sha256=LRGbQSEn_o6YjR0dw8D23m5YKiCXA0FeKXxSkTu936k,1354 +google/genai/_interactions/types/google_search_result_content_param.py,sha256=p2IB5EKF0JzeTLrZBMKcr0RSC7Z3FuLkZz2Q1OOlbfc,1698 +google/genai/_interactions/types/google_search_result_param.py,sha256=hT7WBKG7o90ZApdtP5Fxv1knHgDc1nIZdN1ENF_SBe8,992 +google/genai/_interactions/types/image_config.py,sha256=EQ92GOzOC2bdwIN8j2z1Ye_YgIcqmQ5rM9oqIc3by8s,1099 +google/genai/_interactions/types/image_config_param.py,sha256=5IVv6sNrniNHQ-DudnVZSqeaJIYdIqgN85MBFnJ0jm4,1074 +google/genai/_interactions/types/image_content.py,sha256=LSh8g3yYu0BOmaWYrJV3grWFhtxbMQqa0HFzR_-qDUo,1354 +google/genai/_interactions/types/image_content_param.py,sha256=k3EkJHMfs1_8ZT88b4gkVHF2iIjLBBKwPL4rK2Rfh3g,1585 +google/genai/_interactions/types/interaction.py,sha256=j0Dk8I8iUP13uBm93rXjoPq10VQSajUHUj-Rt_ZTUgs,5334 +google/genai/_interactions/types/interaction_complete_event.py,sha256=QXRx9Sfj756xBu0e4X16tL3KgdFrIRygg7Rz3PBTaDc,1268 +google/genai/_interactions/types/interaction_create_params.py,sha256=HDFuoJNJL56rNnOnKL8tfzbFemPEoNHyUGDFuJohQZ4,7407 +google/genai/_interactions/types/interaction_get_params.py,sha256=SThZ8vwg4tzQpl2S7CYrhI64HYFJO6x9syNoDDazMQI,1719 +google/genai/_interactions/types/interaction_sse_event.py,sha256=1Pmvb1skAgqrXyYpWdpRyc94L31lQAf_n5pXAYHJFPI,1445 +google/genai/_interactions/types/interaction_start_event.py,sha256=eNIooDmS9o0uKoRpN8O2O0oKTMMmo5ZeC2GdjOOqObE,1127 +google/genai/_interactions/types/interaction_status_update.py,sha256=daNt0nxC5E7H3D_wEm_KdXjANLuGmWmQEPJPW7VxadM,1166 +google/genai/_interactions/types/mcp_server_tool_call_content.py,sha256=PZytVm53dwLSUt6XroC17QBniLMJDW70ZWyWHi21L7Q,1348 +google/genai/_interactions/types/mcp_server_tool_call_content_param.py,sha256=tNnt2bz5fUhhXKbFrVR56rBkzFldmH5HhKjl9ICFaQY,1704 +google/genai/_interactions/types/mcp_server_tool_result_content.py,sha256=uCSmzWsCP_4kMfmVUlL7xuOqeV7ROq5OczAh4Og2VHY,1776 +google/genai/_interactions/types/mcp_server_tool_result_content_param.py,sha256=eg7umU0GCtedFFPaEiK6tbYuPPy9jlKgNwzht6BqIDA,2015 +google/genai/_interactions/types/model.py,sha256=Op0bbftVNlQCvbvBw53B7vk2mw4NUOtzZGBVW7d8kGo,1501 +google/genai/_interactions/types/model_param.py,sha256=x0dfFylRywe2BZMR5DgK53tOoSS9N1aB_WdYgZBs6UI,1547 +google/genai/_interactions/types/place_citation.py,sha256=uTp6eWNpK5CRbSK-rULvUH5rG_fYDSW-2uNbS1J1mQU,2038 +google/genai/_interactions/types/place_citation_param.py,sha256=vK4-3JWHQwQ_oUpigvHzj8iAm9gnCdZKnBLiC42OVCs,1953 +google/genai/_interactions/types/speech_config.py,sha256=VHJj9KCC9NMO0hbczIZn7KkPnO7ktcDmwajR5xUv11g,1100 +google/genai/_interactions/types/speech_config_param.py,sha256=ByojkgPZiLXUjT5aVmiGyDOtLzKZpG-B8VPJJjjvGmI,1087 +google/genai/_interactions/types/text_content.py,sha256=S6gJ8zblpE4FfZJApD2ZO75vzK9WU_YeQQF35NlCBBE,1087 +google/genai/_interactions/types/text_content_param.py,sha256=84uBSaN5jpKDBII-hluZCFWPvD2C7wPmzT4m1fhY2A8,1152 +google/genai/_interactions/types/thinking_level.py,sha256=mmoPse7-zDLEqinDsxk7r5NWy21vRSUBur1CEaJxCVk,814 +google/genai/_interactions/types/thought_content.py,sha256=qQI78dluucYjOlr4jqWwk5XsIBqJXu2gytA9cksHHOk,1349 +google/genai/_interactions/types/thought_content_param.py,sha256=3zho-ybUfDtL6LVIq0o0aL-PWkxonm9hrUXDnJjk0tY,1579 +google/genai/_interactions/types/tool.py,sha256=04_BraIVQEE8l-gCFEqI5SSdc8VuKx-UwHU6Ikgkj5U,4521 +google/genai/_interactions/types/tool_choice_config.py,sha256=fyKvOHAZprqFMpUhbTa7uEsyMOH_2wj--7Z0esvEpZs,979 +google/genai/_interactions/types/tool_choice_config_param.py,sha256=LQ4vn1-mCJ3ycCJgyKGfzruL7rw_SvLQz6su7Dcqfqc,1017 +google/genai/_interactions/types/tool_choice_type.py,sha256=XtE6ZbwRYXmMYwNBe8zmw_0INIVzwgXfRStVWbmwuAU,816 +google/genai/_interactions/types/tool_param.py,sha256=MDKH4VTtEa4BYvumiwfJDL7rTqeygkNYwfN-AjKBjho,4479 +google/genai/_interactions/types/turn.py,sha256=qq2M8B3eZ8kbW_MxtrKzcT5dc_DOaB52Sjp4KLx5agY,985 +google/genai/_interactions/types/turn_param.py,sha256=5Yip4HFIWQmQy3pIPAng0xU2Q5Ksff1fYGiKRxm023I,1036 +google/genai/_interactions/types/url_citation.py,sha256=rCDqIftXeEKBw6NoLYEEaTGoB9xDOpkumLPZCSpdPVI,1286 +google/genai/_interactions/types/url_citation_param.py,sha256=di0xFMHf-go1YGeYfBVtAXuDfTgg8OOBzl5Y-JDcBss,1247 +google/genai/_interactions/types/url_context_call_arguments.py,sha256=JLPsuJmq816_lgT8qq_Sc8tMD0sAax5EmHWvTTMessc,933 +google/genai/_interactions/types/url_context_call_arguments_param.py,sha256=lMBhQVJlaaUgOTZwqwwxoeOJvbFekO21GVBNMvPjt98,995 +google/genai/_interactions/types/url_context_call_content.py,sha256=Q4eanthzgagjT3OEsHz9SEeOI2P2snn_OJ8EcMesmB0,1240 +google/genai/_interactions/types/url_context_call_content_param.py,sha256=_JK8wHY7tOqZB6dV2OcEXHiShb_9aJMDWAlmqQhmX_8,1589 +google/genai/_interactions/types/url_context_result.py,sha256=R4TzIKOiG59aA2gbXHIuJFW3C2FukolXOOtUIpCTIM0,1062 +google/genai/_interactions/types/url_context_result_content.py,sha256=V8YhGXO02bBh6W4-_WOhC4GRoG99gyasCvQG5v7Byok,1336 +google/genai/_interactions/types/url_context_result_content_param.py,sha256=9jhQ78QOcDDp9ohHA1WhdCzPPlvGS-ffaY7Ui2ryIbo,1678 +google/genai/_interactions/types/url_context_result_param.py,sha256=XmQ2EgunZDshXUbuy50J88kY1h2p1REzrIZV4Qp1mDI,1037 +google/genai/_interactions/types/usage.py,sha256=9a-NQ3aAUtxWHjMEmROMJhQ_pS3l02GY300lRrtwHSw,3554 +google/genai/_interactions/types/usage_param.py,sha256=hDFqDuOOnYBcOu_2p525dKoWLkBoD0N9oZW8Ug7Ch0Y,3347 +google/genai/_interactions/types/video_content.py,sha256=S9PpblyzmfcdJXNqqHDuXgz9drbtBYwTPtMKhE2nNw8,1463 +google/genai/_interactions/types/video_content_param.py,sha256=JWo87PMHolBw9nJLMglEFnqfBXfX-1lmCAU_7a1j0y8,1662 +google/genai/_live_converters.py,sha256=v31NSVYYQpFIjg5wWnLTMWzKCpJUnO67bb1M5KZXsoc,58999 +google/genai/_local_tokenizer_loader.py,sha256=YdnnFPXB8eNZ3VhzTzHovE7ZSD3n729wpV42aoOLd7c,7185 +google/genai/_mcp_utils.py,sha256=HuWJ8FUjquv40Mf_QjcL5r5yXWrS-JjINsjlOSbbyAc,3870 +google/genai/_operations_converters.py,sha256=zw8DqkgJWHphrw9waAjAiH98QbE2Rnum3zGm02dHQWo,11695 +google/genai/_replay_api_client.py,sha256=6sDMMHbmH5pZIjlaEsqjVwLwQS_4evSs8tCK2FOUlIs,23438 +google/genai/_test_api_client.py,sha256=4ruFIy5_1qcbKqqIBu3HSQbpSOBrxiecBtDZaTGFR1s,4797 +google/genai/_tokens_converters.py,sha256=ypx5jjl_zPEBr8Nh0fzC9lue2rRq6hwTvIE4ys4C334,19390 +google/genai/_transformers.py,sha256=jWFIc5jOXOszv7jjQefPuHnpQjJU9A90M7WIUkr07So,43343 +google/genai/batches.py,sha256=XCtZ--_vNJXv0azkq1iAEexwAP6Ozim4A0Prv6U4eIU,87023 +google/genai/caches.py,sha256=iRkiIS1dcT5dmuYYUC-_g5KCgRFAy12HKElw-5YtR-A,59460 +google/genai/chats.py,sha256=q3_iONHx8l-Y7EG29_f45yjFDdL2VFefUDLMdJtw0sE,16583 +google/genai/client.py,sha256=--tM_bHIiuc7tYQwoQr-14epbtO_4WM5DoPZQiCPCBw,21352 +google/genai/documents.py,sha256=VSVUCvcNbQ9a505TXFyunC-pLT8lpkCJw2iXym3T648,18210 +google/genai/errors.py,sha256=h615SoRP6P7AlDRECQwhMikCKmuQtkXMGX3CgeNfDhE,9545 +google/genai/file_search_stores.py,sha256=6r055_4G4BnbcdpM2e-r4EFRLVVBupZgcRYYiJaJ_g8,46572 +google/genai/files.py,sha256=X-3XbYnHoCc-ejZSZkVikBxg_DwfQTjC7M1ZRzcpjps,44129 +google/genai/interactions.py,sha256=GLpo-rTdxb1JfL3LXE0c52JWaEGloLnPeCI9hoO_M2g,642 +google/genai/live.py,sha256=zwPW5xPxXERyPVYRIDKUCd4uJooHqojmocCShGkmBiM,42781 +google/genai/live_music.py,sha256=Tc-dfxvWt7gxcpaCmomtNpFu2RcIaU5xuuwsajkdDHs,7288 +google/genai/local_tokenizer.py,sha256=EKZ72cV2Zfutlo_efMOPnLRNZN4WQe57rD3G80cF340,14109 +google/genai/models.py,sha256=r7F_9yF8fvRAcv90d62fr3jNlpundTSZo536ui1LlFY,285520 +google/genai/operations.py,sha256=ECJQ5AE8PuaUmz7Hry0PH7TAewJl-OX-ia3uKHG_siI,18848 +google/genai/pagers.py,sha256=1i8NXDuKuQznFin5H5-I0hmj6H5YMTYsEJP7S0ITSbY,7158 +google/genai/py.typed,sha256=RsMFoLwBkAvY05t6izop4UHZtqOPLiKp3GkIEizzmQY,40 +google/genai/tests/__init__.py,sha256=gg8QQy0VqB4Cgf50Tbf5AAEf3IdzKsnCPf6IHXXbikY,689 +google/genai/tests/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/__pycache__/conftest.cpython-313.pyc,, +google/genai/tests/__pycache__/pytest_helper.cpython-313.pyc,, +google/genai/tests/afc/__init__.py,sha256=AqPvJAlU0sazclZEv9w4ycsKaRW1MNmjCmSWakTe7a8,708 +google/genai/tests/afc/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_convert_if_exist_pydantic_model.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_convert_number_values_for_function_call_args.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_find_afc_incompatible_tool_indexes.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_generate_content_stream_afc.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_generate_content_stream_afc_thoughts.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_get_function_map.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_get_function_response_parts.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_get_max_remote_calls_for_afc.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_invoke_function_from_dict_args.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_raise_error_for_afc_incompatible_config.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_should_append_afc_history.cpython-313.pyc,, +google/genai/tests/afc/__pycache__/test_should_disable_afc.cpython-313.pyc,, +google/genai/tests/afc/test_convert_if_exist_pydantic_model.py,sha256=A0uBgJAWimtky4P3XKNg2qH9tVEb3aYDzlsASQjTWRQ,8935 +google/genai/tests/afc/test_convert_number_values_for_function_call_args.py,sha256=LLKU67BU_Tib_pmkOyb1hm5Ew9O2d08klLGJEjvYPy4,1769 +google/genai/tests/afc/test_find_afc_incompatible_tool_indexes.py,sha256=Ct2PfhihMGaTxz0hUY0RhBpcCA_L6TvqchRZVRppwA4,9576 +google/genai/tests/afc/test_generate_content_stream_afc.py,sha256=oO08IofdnxMR4AEXE_Xim0Q8SvkOGdElcX-_podqF18,16572 +google/genai/tests/afc/test_generate_content_stream_afc_thoughts.py,sha256=Fy65xYRvWMlBF7D3h1qy3sO86UVMKQccjCsxtRBr2P8,2261 +google/genai/tests/afc/test_get_function_map.py,sha256=2Byh4Tg2VEGyc2dX9WduiF8lwwOJTTNjeqDsHkNxq-o,4817 +google/genai/tests/afc/test_get_function_response_parts.py,sha256=PFhFqlsjQpK7c7I837kl5EiIVDkie3qiXETFc_5zIT8,8025 +google/genai/tests/afc/test_get_max_remote_calls_for_afc.py,sha256=ZDnRUbTc-7lM0ohDbzbemSa09XPWJkFWCn_9d2WkURM,3361 +google/genai/tests/afc/test_invoke_function_from_dict_args.py,sha256=dOjqzQFLhy6We3Bb-VOI8X5V5I74DI9HNIe5pVwCmQA,7319 +google/genai/tests/afc/test_raise_error_for_afc_incompatible_config.py,sha256=ZjEqqvcKHn-SP-D48Ghr3eOY5cc1IuLiXMNOMZ3oPSM,4803 +google/genai/tests/afc/test_should_append_afc_history.py,sha256=HNEXhwgxD_PN-1FDr-c0z4W6mcMmg2hlO1wVJMuFro4,1656 +google/genai/tests/afc/test_should_disable_afc.py,sha256=nJQzI7uN7wBy1OOgqQx1PFJNOYWzN6Ae98MGwrhEgL4,4951 +google/genai/tests/batches/__init__.py,sha256=iN1nyq74rtvWV5ksbYJ9IQnkyNZA8dZxnHs9fD-yfJs,632 +google/genai/tests/batches/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_cancel.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_create.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_create_with_bigquery.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_create_with_file.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_create_with_gcs.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_create_with_inlined_requests.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_delete.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_embedding.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_get.cpython-313.pyc,, +google/genai/tests/batches/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/batches/test_cancel.py,sha256=BRhpmy9Vr6wGjigRpQeGxONBJ9j8vNPg6n6p5MOA6z8,2348 +google/genai/tests/batches/test_create.py,sha256=3YBAh1eN4jTQy1pRm8TRC9bzHkAYSszuE2hj0zDEkLw,2356 +google/genai/tests/batches/test_create_with_bigquery.py,sha256=KterzZUzmGgyhuwbTiBndtXnnMM5BHD-3CN2IOYFano,3697 +google/genai/tests/batches/test_create_with_file.py,sha256=6KGRTNV8cojhMN3PtzD8nzioRi0xYBLInmLpfv6eIrA,2416 +google/genai/tests/batches/test_create_with_gcs.py,sha256=5-e4otl3OJZV7BxDeTqHO8Cp0Pe_CgRUAf1zC3aLDd0,4057 +google/genai/tests/batches/test_create_with_inlined_requests.py,sha256=8J-0166qLyv9OhGFunrk7sxb_PoLNkGCoiy5EAp-4l8,7856 +google/genai/tests/batches/test_delete.py,sha256=RhyFKjt1qEFbPvPPzoBfeVvtb3GoLYCamsIz2QmlOzo,2718 +google/genai/tests/batches/test_embedding.py,sha256=o7mKpzwDYArCgUBZ8Twl2hRiN6KS3gKTb_2-PemGUqI,4859 +google/genai/tests/batches/test_get.py,sha256=33saXNAIo7Z5mHABZTSJ-6FECApftSZgy-J8vYwVIlU,2269 +google/genai/tests/batches/test_list.py,sha256=SVeUk4QcNsrEHe1S5EZuJB9UepEPK0eszq5uvLCPUv8,2343 +google/genai/tests/caches/__init__.py,sha256=3ox8j_0aP_e-KYnSX9IefvLEE1qz4hnV6rtc0t5cuAg,632 +google/genai/tests/caches/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/constants.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_create.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_create_custom_url.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_delete.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_delete_custom_url.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_get.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_get_custom_url.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_update.cpython-313.pyc,, +google/genai/tests/caches/__pycache__/test_update_custom_url.cpython-313.pyc,, +google/genai/tests/caches/constants.py,sha256=XzAlcPTd8sfu4xhrYuHJecwOKDEThzzoyn4s9BPgPsU,1003 +google/genai/tests/caches/test_create.py,sha256=9SZi9vOgBhnD3Z7fDJs-aYUGoU0XTp8i31t06drylqM,7962 +google/genai/tests/caches/test_create_custom_url.py,sha256=93LcV9BxCtZVDMDagf6etzEVDrk3Z_g85pcYa0EzDxc,4003 +google/genai/tests/caches/test_delete.py,sha256=s2rq7qU87R1UZx4tBIp5PaU6-890XIJd8jXXTE2uOKY,1798 +google/genai/tests/caches/test_delete_custom_url.py,sha256=vHZOr7f7_vIQN8AOiwd8FKg0kUP6FcsLIANo2k_AX6Y,1718 +google/genai/tests/caches/test_get.py,sha256=6MiFJaXsy8XELN1GpAbx9tRWWAN2Q9UBCCBOePag3yQ,3008 +google/genai/tests/caches/test_get_custom_url.py,sha256=6X5yeP50YyetcJPFHtc0EctQURdwTD6fdqyExa-cUm4,1697 +google/genai/tests/caches/test_list.py,sha256=nSOwJBJylpZrThaSV_ah8O6LzVNYHVPMHUUVS_aDc4k,2184 +google/genai/tests/caches/test_update.py,sha256=ZaxyiytKf3Pu0Iiyet-7uEE2WOy4_srqOy0GJNAGeAw,2111 +google/genai/tests/caches/test_update_custom_url.py,sha256=XxncRa2YNCFp2TJFDIdYYznyvEkGGZFzrO4sxXwmFzM,1798 +google/genai/tests/chats/__init__.py,sha256=kOWMJqwDSOryDqDMkmkteFrz-YQtqfIfo9dhD0_r93M,53 +google/genai/tests/chats/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/chats/__pycache__/test_get_history.cpython-313.pyc,, +google/genai/tests/chats/__pycache__/test_send_message.cpython-313.pyc,, +google/genai/tests/chats/__pycache__/test_validate_response.cpython-313.pyc,, +google/genai/tests/chats/test_get_history.py,sha256=_H6K__2dn47_6XZyvEo4uNY9ntdvRW0K4BA20eaYTa4,17897 +google/genai/tests/chats/test_send_message.py,sha256=HJFfAsQc7y6U64DASJZpGrpIhGP5-m5Wl-KBz3g0pR4,28126 +google/genai/tests/chats/test_validate_response.py,sha256=07zq5pJ3rL2zu8o5RKJZKFyZQ9tMZyVXLBrLuADkGUQ,2420 +google/genai/tests/client/__init__.py,sha256=RvGOeb5ZdxjMSh_frXTcrenwE_UsF3_vlDaI-_ml74Y,616 +google/genai/tests/client/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_async_stream.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_client_close.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_client_initialization.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_client_requests.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_custom_client.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_http_options.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_replay_client_equality.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_retries.cpython-313.pyc,, +google/genai/tests/client/__pycache__/test_upload_errors.cpython-313.pyc,, +google/genai/tests/client/test_async_stream.py,sha256=wDrCIvxP9s_nwMI_GMs8hwB-I9bEYbrSLZPstNVWxRw,12755 +google/genai/tests/client/test_client_close.py,sha256=VrnJfuXGSaW5_306eAlTYycz01Cd7cwoEqzzbEVuqkQ,6388 +google/genai/tests/client/test_client_initialization.py,sha256=GSMzHzMJAu3tLsLYTXS18HZrWBsqMwkAoPyu5tQ66uA,58940 +google/genai/tests/client/test_client_requests.py,sha256=ATTGdQPLpTWp25f5apIcWTRjV5aEHQoUDOHRRUpxLlU,7403 +google/genai/tests/client/test_custom_client.py,sha256=1E8fAhPdKYYnKvDJuqPyptEfU9zh1WmOurxlnXg9huc,3239 +google/genai/tests/client/test_http_options.py,sha256=Uiad0x4r5gDmiD8z36-P4S1VslPNp81AScoI3bnWG3w,5515 +google/genai/tests/client/test_replay_client_equality.py,sha256=W6NvtEObD6nkAryHYYNvpQnTvshWh8GVbGE3bjtf8tk,5139 +google/genai/tests/client/test_retries.py,sha256=YkFr2tXKNRTCeeWAICAh7M-WtZ68KxqAUYMJhPG0a7A,38015 +google/genai/tests/client/test_upload_errors.py,sha256=pJOTwjX__ylY22-0_RqPdj7InvqRvgo-TihAVIOPFws,6600 +google/genai/tests/common/__init__.py,sha256=E0qCY_jgwzKoYZLacliuf7Mk0DsO3mdLyVwBYOK20U4,632 +google/genai/tests/common/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/common/__pycache__/test_common.cpython-313.pyc,, +google/genai/tests/common/__pycache__/test_duck_type.cpython-313.pyc,, +google/genai/tests/common/test_common.py,sha256=lvbgSiqo7LBYkAw7jy4ig-JytVYs3lBizA5FhoYlmig,26872 +google/genai/tests/common/test_duck_type.py,sha256=HToEJbPu4w9tAb4xPIKfmNQ2edukYQc8IEAMG0zg09U,2340 +google/genai/tests/conftest.py,sha256=qUw3yQte5eQo4VG-m3uWwamUy9LaQMbkdBMxuuFjtlU,5021 +google/genai/tests/documents/__init__.py,sha256=D6WPZHqgHQZJ6zXGqoG5i5_XPykoB3wzwwbDx9lXuz4,635 +google/genai/tests/documents/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/documents/__pycache__/test_delete.cpython-313.pyc,, +google/genai/tests/documents/__pycache__/test_get.cpython-313.pyc,, +google/genai/tests/documents/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/documents/test_delete.py,sha256=O33JZOTpdhrCRmAudC6YudHpuv46uRD2tpwjJ3s_wTM,1718 +google/genai/tests/documents/test_get.py,sha256=Z-aMd_vxjnxUVDg_4iphCkXJnqDM6ZMaiqa87ip172s,3191 +google/genai/tests/documents/test_list.py,sha256=qgdc__sH88NA8Ptd83BfPsGLaoZntdn0D6eHajr-jl0,2425 +google/genai/tests/errors/__init__.py,sha256=8hdiuOvLIiX_to2O6rc8Af04-85qQuRu62gOhQQyNx8,39 +google/genai/tests/errors/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/errors/__pycache__/test_api_error.cpython-313.pyc,, +google/genai/tests/errors/test_api_error.py,sha256=Aur-8Q_ZJmMmGOewgWvYcaANxZk8xN7WEqWJYG-o5j8,12162 +google/genai/tests/file_search_stores/__init__.py,sha256=IGpNdiCD34aFEuUWM4QyGS-ekZM29FxL1uM2oRP1E4M,644 +google/genai/tests/file_search_stores/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/file_search_stores/__pycache__/test_create.cpython-313.pyc,, +google/genai/tests/file_search_stores/__pycache__/test_delete.cpython-313.pyc,, +google/genai/tests/file_search_stores/__pycache__/test_get.cpython-313.pyc,, +google/genai/tests/file_search_stores/__pycache__/test_import_file.cpython-313.pyc,, +google/genai/tests/file_search_stores/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/file_search_stores/__pycache__/test_upload_to_file_search_store.cpython-313.pyc,, +google/genai/tests/file_search_stores/test_create.py,sha256=1a90j-1oOYBPF7DPIxgMFblhxLtmo_KBL3eUrCOLpzI,2090 +google/genai/tests/file_search_stores/test_delete.py,sha256=hRfxcMbaB3Q93izLd0JfS4HOu7sttugV0bLmF6GrGIs,2158 +google/genai/tests/file_search_stores/test_get.py,sha256=I26LR_k_GVsipkDYh4rPoGAJsiSQdrGxybod3C445gM,3348 +google/genai/tests/file_search_stores/test_import_file.py,sha256=-f9uUkzLkz_bVvnQ_mdoX4FyYQ0ofWM-jsAkVrv5OWM,3629 +google/genai/tests/file_search_stores/test_list.py,sha256=hlZz-3F1B6zqvg37Ydz545VFA6tAUJb7iVnzCZwxk20,1860 +google/genai/tests/file_search_stores/test_upload_to_file_search_store.py,sha256=935XNOVKsl0Ml86qvE-Zp30m5CBaG9b4YbYxsmjuDj8,4845 +google/genai/tests/files/__init__.py,sha256=OCJF9_KGxqq2oRETThZwtL2X3K11aKPBjJ6pipkYgWc,630 +google/genai/tests/files/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/files/__pycache__/test_delete.cpython-313.pyc,, +google/genai/tests/files/__pycache__/test_download.cpython-313.pyc,, +google/genai/tests/files/__pycache__/test_get.cpython-313.pyc,, +google/genai/tests/files/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/files/__pycache__/test_register.cpython-313.pyc,, +google/genai/tests/files/__pycache__/test_register_table.cpython-313.pyc,, +google/genai/tests/files/__pycache__/test_upload.cpython-313.pyc,, +google/genai/tests/files/test_delete.py,sha256=mL15UCFIaWwyUNZGvAQEx4YQBIFkZv_RfmMfNaiYXTU,1416 +google/genai/tests/files/test_download.py,sha256=j44qwIhVAcmGSV2EEDgftFfgGoCB0XSR2BE1tSoTnZQ,2341 +google/genai/tests/files/test_get.py,sha256=IJTaDxh6MCPXDMwZgQJY6xnTQOKyIwJt67O2TRwQmoo,1404 +google/genai/tests/files/test_list.py,sha256=BuidbWnOJKeQcl8g78v9HvLJJhgcHSV2Mpb_b-vvh_o,2224 +google/genai/tests/files/test_register.py,sha256=rCFTY3U3_OrovGgTJsCJ2rQbqV4P1lobNObqegLZCME,8368 +google/genai/tests/files/test_register_table.py,sha256=TiJkutQ2IvPRuTjeSpDUc1kEyRVaTeFvQzvC2iCMjmE,2341 +google/genai/tests/files/test_upload.py,sha256=uPioeL38l9lu2ebenllW3Co1tN5xeCMQuSvHudfRNmU,8372 +google/genai/tests/imports/__pycache__/test_no_optional_imports.cpython-313.pyc,, +google/genai/tests/imports/test_no_optional_imports.py,sha256=fhSdu9gHQYoGYsgbfb3qdoI5cipJJ67Dk5RwSk4vcFE,987 +google/genai/tests/interactions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google/genai/tests/interactions/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/interactions/__pycache__/test_auth.cpython-313.pyc,, +google/genai/tests/interactions/__pycache__/test_integration.cpython-313.pyc,, +google/genai/tests/interactions/__pycache__/test_paths.cpython-313.pyc,, +google/genai/tests/interactions/test_auth.py,sha256=t0mvJVZIgfdEcWihIbe-fgaPrnMrVXuKwtaSEoR9J8s,17591 +google/genai/tests/interactions/test_integration.py,sha256=JMOfFkbvDL0IfGr2Dq5_iYpETG4-9D35TYgMVlyy7tc,2318 +google/genai/tests/interactions/test_paths.py,sha256=7JRpeyaGyh5_Lj8BPKlXsskfsG5Xpw07Ns_KcsO17Pg,4441 +google/genai/tests/live/__init__.py,sha256=KbDhwTfDYAhkNqkbDeqOxlfFwjij-deuilWGXN9cySc,578 +google/genai/tests/live/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/live/__pycache__/test_live.cpython-313.pyc,, +google/genai/tests/live/__pycache__/test_live_music.cpython-313.pyc,, +google/genai/tests/live/__pycache__/test_live_response.cpython-313.pyc,, +google/genai/tests/live/__pycache__/test_send_client_content.cpython-313.pyc,, +google/genai/tests/live/__pycache__/test_send_realtime_input.cpython-313.pyc,, +google/genai/tests/live/__pycache__/test_send_tool_response.cpython-313.pyc,, +google/genai/tests/live/test_live.py,sha256=DSbjeZRHYyss8o6Gelclm6B0b_Ui_CFfr0GmmTOPsW8,68198 +google/genai/tests/live/test_live_music.py,sha256=VC7QuLQYY4LKkDcfUtizCc-K4JPm7LCd5oDwVBb_Zuc,11252 +google/genai/tests/live/test_live_response.py,sha256=z5xyev6PL0h-WChGFy1QhWiJ8ld2Vt5dHa9PtQ7DN5w,5531 +google/genai/tests/live/test_send_client_content.py,sha256=slHTAKalYzQncLF37stThKcTHEoC2FVQtPghAeIUSWM,4946 +google/genai/tests/live/test_send_realtime_input.py,sha256=jHb-ncYTXwt9Dps8oWu3ofWs99q0kxP4eCvIBjW4WL8,9493 +google/genai/tests/live/test_send_tool_response.py,sha256=ZbrF5VjztSgfDpxPTFCjqSApIYYDwYUGsYIRD-sLimM,6280 +google/genai/tests/local_tokenizer/__init__.py,sha256=5ffJTDv71l3pLvTGF58kb_vFf8TUDpfM5cGWp4DMwDw,641 +google/genai/tests/local_tokenizer/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/local_tokenizer/__pycache__/test_local_tokenizer.cpython-313.pyc,, +google/genai/tests/local_tokenizer/__pycache__/test_local_tokenizer_loader.cpython-313.pyc,, +google/genai/tests/local_tokenizer/test_local_tokenizer.py,sha256=iktgMtFPfsqT5aZ_uVpBjzT32WqO8kbI9YPpdgqLZaw,12254 +google/genai/tests/local_tokenizer/test_local_tokenizer_loader.py,sha256=mKIA6L9wobG6V_jKFuQF_P0Bv9XZsFikyKVWq9iGRrM,7196 +google/genai/tests/mcp/__init__.py,sha256=VyFzMY6rRcPk9glMUZe0sO_GQlTMFNjfibEqp8iVLkI,635 +google/genai/tests/mcp/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/mcp/__pycache__/test_has_mcp_tool_usage.cpython-313.pyc,, +google/genai/tests/mcp/__pycache__/test_mcp_to_gemini_tools.cpython-313.pyc,, +google/genai/tests/mcp/__pycache__/test_parse_config_for_mcp_sessions.cpython-313.pyc,, +google/genai/tests/mcp/__pycache__/test_parse_config_for_mcp_usage.cpython-313.pyc,, +google/genai/tests/mcp/__pycache__/test_set_mcp_usage_header.cpython-313.pyc,, +google/genai/tests/mcp/test_has_mcp_tool_usage.py,sha256=_TPC55X8pCB7F0Pv7ljQcNKFQ00jjW-tmCHevFh-beY,2411 +google/genai/tests/mcp/test_mcp_to_gemini_tools.py,sha256=qAS-1qvx5tu6xsJmfvy4ESf9nQBemIpaYuPb04uxvDU,5366 +google/genai/tests/mcp/test_parse_config_for_mcp_sessions.py,sha256=NeUBaRmvSjiOVcLAzPrF5piRpIxRWwZoWNUth5NKI54,6467 +google/genai/tests/mcp/test_parse_config_for_mcp_usage.py,sha256=FGPASkuwBT0-m5qhPP4jtuE8F-WK4Jv6Jbmo6F8vuqQ,4283 +google/genai/tests/mcp/test_set_mcp_usage_header.py,sha256=D5-t7z7G2diSXPXVrFj0DuGGMs_2CdRta0tvTYpmt2s,2122 +google/genai/tests/models/__init__.py,sha256=66KctCh8D4-qJya9yM7roDVN_yHdKrfxaJq76uOxFnQ,631 +google/genai/tests/models/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/models/__pycache__/constants.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_compute_tokens.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_count_tokens.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_delete.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_edit_image.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_embed_content.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_function_call_streaming.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_cached_content.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_config_zero_value.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_from_apikey.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_http_options.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_image_generation.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_mcp.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_media_resolution.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_model.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_part.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_thought.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_content_tools.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_images.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_generate_videos.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_get.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_recontext_image.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_segment_image.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_update.cpython-313.pyc,, +google/genai/tests/models/__pycache__/test_upscale_image.cpython-313.pyc,, +google/genai/tests/models/constants.py,sha256=7D3RsvXF0NfDWla6z-hIXJftJXRdCd2yPgNb4cWf6Ic,238 +google/genai/tests/models/test_compute_tokens.py,sha256=NSwwV_TEW07yb7_99WgyIz1Xgy2rSs0eCgADs-5Y3zM,4171 +google/genai/tests/models/test_count_tokens.py,sha256=ErSJWMYxnBYmpnvSXhIKn7B-PKlyQiSFYGuk9RLXE8Y,5042 +google/genai/tests/models/test_delete.py,sha256=OBl8mfHychtjWy6v19Das3ikYtBwN3pojXZ-BxL8zpY,3286 +google/genai/tests/models/test_edit_image.py,sha256=2QG3ufsRGqryk9jSgyiTgMnuT8VuSZJvghatwEA3NXo,9369 +google/genai/tests/models/test_embed_content.py,sha256=63BQk0pOu1nD6o8hedoD7cgbQrrgs1tASzL9aN3i1fc,7488 +google/genai/tests/models/test_function_call_streaming.py,sha256=8R6upyqnrBkajl_OH8V1lYepuMD9KV2oTTIbMfQoX9A,14787 +google/genai/tests/models/test_generate_content.py,sha256=6ur08TXdX-6Qbe2ppHGcKXEg6WYf5-zNAgEdlfFeFlI,80387 +google/genai/tests/models/test_generate_content_cached_content.py,sha256=gwZTuvvjtavtYKHZMM6_qOikWSh08LWWZ6z-qGhk9DE,4754 +google/genai/tests/models/test_generate_content_config_zero_value.py,sha256=TNBTFFA9HLidwEF3tV1FV413kilLZWhrnN8MAulxqcc,3335 +google/genai/tests/models/test_generate_content_from_apikey.py,sha256=i-cqsmyfBfkP_Xu-x3l3lO9aUhBLViU4fNuNiDik2JU,1452 +google/genai/tests/models/test_generate_content_http_options.py,sha256=UpYh2wqUBa5XLrVOevB85umcKU74aEbU6gYCkPvGb5M,1232 +google/genai/tests/models/test_generate_content_image_generation.py,sha256=4_kiIr7RMm7D6pPTW_rG8deERpSIbSbJVewZvRNIe8g,4857 +google/genai/tests/models/test_generate_content_mcp.py,sha256=8ikv3aFdCJhDTVAdRbmsmX2ZXWZfuvBJJb0Vm9iVYB8,10050 +google/genai/tests/models/test_generate_content_media_resolution.py,sha256=1lYYd9-Uv1YIgOxfjhqfyTm3AINDsgT5FAaufx5qT7Y,3429 +google/genai/tests/models/test_generate_content_model.py,sha256=hvh6_92l4pscqdC9N0xmTkwqu29fAylQCxj4wC-vL6Q,4491 +google/genai/tests/models/test_generate_content_part.py,sha256=UTGD550fXlqgZbkIDd1v9ScdOMgu7yc3n_z7m4yIXVU,26477 +google/genai/tests/models/test_generate_content_thought.py,sha256=rJsC1HyyJdB8-vcTqgCUhofaodRSdIVNSRSVh93vu_8,2296 +google/genai/tests/models/test_generate_content_tools.py,sha256=MOaJkDml-FCeKHKVJQp5CGKp19DCOaf8KK_FyvXxjp4,61235 +google/genai/tests/models/test_generate_images.py,sha256=TNfsQrhja8k4STXixdTwn_YO97jUGOF3-YKFqJu2Fmk,6952 +google/genai/tests/models/test_generate_videos.py,sha256=jIvTT2pOQIPaOX-Otw1cEU2oRDIVmWHuLxkCQ_PBNuc,24163 +google/genai/tests/models/test_get.py,sha256=tW0142USI8uUkwDjfDX52oiuoJ9OKEz5g1sL7fhm-3o,3251 +google/genai/tests/models/test_list.py,sha256=EfIzUNKn4b0MX5OHUh6_ZzPM6jzfoN_FV7SSBd6ajG4,7125 +google/genai/tests/models/test_recontext_image.py,sha256=FTlCSOUsgD6a92ahHwynl85kNpE3Lj02xJHuYl5rCo8,3422 +google/genai/tests/models/test_segment_image.py,sha256=Sp750MAO9hVSElK82f8xjufFBQ-PSAO8IkKNRBGYJoA,5005 +google/genai/tests/models/test_update.py,sha256=H8NITq04d5D1ekzSiU9d8LJZM2BLCmtT5eYl7vK8kCk,2890 +google/genai/tests/models/test_upscale_image.py,sha256=a-Jv1VoPNtszZRqXRV1PkUo4uIYcTRFzL2ssLjpmEuU,5340 +google/genai/tests/operations/__init__.py,sha256=Mw7f19mQhYNr18sj0_eDhmDlpKAHz1VTSPrO4ubbIio,610 +google/genai/tests/operations/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/operations/__pycache__/test_get.cpython-313.pyc,, +google/genai/tests/operations/test_get.py,sha256=xIyQxRpYdj_7wQ53mkYFaC1YZlXofkaNsYhyUTQrV9s,1130 +google/genai/tests/public_samples/__init__.py,sha256=6CxAr03tXnfNhx-Bs34r6OokIkXlFVw5Ydnv9pHHsJU,635 +google/genai/tests/public_samples/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/public_samples/__pycache__/test_gemini_text_only.cpython-313.pyc,, +google/genai/tests/public_samples/test_gemini_text_only.py,sha256=t256zyR7v1LNZDHrw8F9oXSGud5Fp7xHVZ0SW78oObU,1094 +google/genai/tests/pytest_helper.py,sha256=KFFRlwtVLJSnRuYzQoe5OID6QplC7Byzgr3nCmZJV98,8287 +google/genai/tests/shared/__init__.py,sha256=KbDhwTfDYAhkNqkbDeqOxlfFwjij-deuilWGXN9cySc,578 +google/genai/tests/shared/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/shared/batches/__init__.py,sha256=Uo6Ox63057cG3O2ahnelWqdHzChYgJHfFNIW7EFewZ4,576 +google/genai/tests/shared/batches/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/shared/batches/__pycache__/test_create_delete.cpython-313.pyc,, +google/genai/tests/shared/batches/__pycache__/test_create_get_cancel.cpython-313.pyc,, +google/genai/tests/shared/batches/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/shared/batches/test_create_delete.py,sha256=qydHMtN0eabBnQSE_SWeEW-ktyDLABLXFTTO9bWT7k0,1750 +google/genai/tests/shared/batches/test_create_get_cancel.py,sha256=NX1KtYiLw68lEKaaYpsnsQYe-ZEmCSJVWGXwiIJJPnE,1664 +google/genai/tests/shared/batches/test_list.py,sha256=xtS6EylJ0i1doc_5hW8RFlka5W3QJU2uLaK8qcMK_Eg,1158 +google/genai/tests/shared/caches/__init__.py,sha256=Uo6Ox63057cG3O2ahnelWqdHzChYgJHfFNIW7EFewZ4,576 +google/genai/tests/shared/caches/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/shared/caches/__pycache__/test_create_get_delete.cpython-313.pyc,, +google/genai/tests/shared/caches/__pycache__/test_create_update_get.cpython-313.pyc,, +google/genai/tests/shared/caches/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/shared/caches/test_create_get_delete.py,sha256=spP-y12HMcMsZ71SwovpLnQBBWQhhBa8wB__mTIWQtI,2150 +google/genai/tests/shared/caches/test_create_update_get.py,sha256=8KtQCtWEAWrgX6eQGJCEC4qvAGXL1NsNc8Ho6173510,2239 +google/genai/tests/shared/caches/test_list.py,sha256=iUNAHt7GhbCAPYAIm_SR5VuPDXxQ6j4iqIGZ8hHO-oc,1171 +google/genai/tests/shared/chats/__init__.py,sha256=Uo6Ox63057cG3O2ahnelWqdHzChYgJHfFNIW7EFewZ4,576 +google/genai/tests/shared/chats/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/shared/chats/__pycache__/test_send_message.cpython-313.pyc,, +google/genai/tests/shared/chats/__pycache__/test_send_message_stream.cpython-313.pyc,, +google/genai/tests/shared/chats/test_send_message.py,sha256=M8h69CbVrtJhb8vecw0psYsiMKayObrZraadi1wSmxY,1320 +google/genai/tests/shared/chats/test_send_message_stream.py,sha256=PGvNxmIYK1JtFvjCITCH2ArD7AY3Jnz9Vw1t5SMPZSY,1419 +google/genai/tests/shared/files/__init__.py,sha256=Uo6Ox63057cG3O2ahnelWqdHzChYgJHfFNIW7EFewZ4,576 +google/genai/tests/shared/files/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/shared/files/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/shared/files/__pycache__/test_upload_get_delete.cpython-313.pyc,, +google/genai/tests/shared/files/test_list.py,sha256=wFKohgtdnW2p5iglRf3AJs_WsnzAkvdtdffWFRfMW9o,1218 +google/genai/tests/shared/files/test_upload_get_delete.py,sha256=f8vTsl-7O8k8OVDhzCctgZxbPQJArrH_ut6an2DXZXI,1589 +google/genai/tests/shared/models/__init__.py,sha256=Uo6Ox63057cG3O2ahnelWqdHzChYgJHfFNIW7EFewZ4,576 +google/genai/tests/shared/models/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_compute_tokens.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_count_tokens.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_edit_image.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_embed.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_generate_content.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_generate_content_stream.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_generate_images.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_generate_videos.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_recontext_image.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_segment_image.cpython-313.pyc,, +google/genai/tests/shared/models/__pycache__/test_upscale_image.cpython-313.pyc,, +google/genai/tests/shared/models/test_compute_tokens.py,sha256=SvhhQzUxkHLukIXGb09gcjti7PYpV0Vwta9OaWeB1oE,1249 +google/genai/tests/shared/models/test_count_tokens.py,sha256=DQxnGSwmnxn1Cl4V5z8030o--Yes3l1Wwq7fqAtAqI8,1179 +google/genai/tests/shared/models/test_edit_image.py,sha256=-GG2FjXSo7PC0r0OEkxEGPBEM1q2kQlP2EzwWnXB5mI,1954 +google/genai/tests/shared/models/test_embed.py,sha256=pl7reBwI6_MRoG10aW5_gfC0rPQA4H-WaHcpwCO-8C0,1219 +google/genai/tests/shared/models/test_generate_content.py,sha256=IS9nPqwP_8yryC0LBjPWobNAeRfYL6Fhe3jufSeAIFk,2080 +google/genai/tests/shared/models/test_generate_content_stream.py,sha256=7qR2TLad6zPg5RIZNGxr71tFt899QZM72WyRHZlsnBM,1522 +google/genai/tests/shared/models/test_generate_images.py,sha256=Vqk0hT08FlQ2tQootyn0KSBnOf3Ow-3e0C2khMkDKEY,1280 +google/genai/tests/shared/models/test_generate_videos.py,sha256=jGuu85FNOUIvfNkEL6qFlQTzlAEg6XFpCtZy3K4Vzqs,1136 +google/genai/tests/shared/models/test_list.py,sha256=34LDppIOJMqajBiJpopseybKZFN1ghoWV0RfpjI6wwk,1041 +google/genai/tests/shared/models/test_recontext_image.py,sha256=JkFRmfHwjmR5Sxoy9yLyqGnn3std43jGeA5t1ysWBMw,1728 +google/genai/tests/shared/models/test_segment_image.py,sha256=293qOOxZCS5-zeR-DvgUwrsEgqq9ZTWlkNJRT2MZBEs,1588 +google/genai/tests/shared/models/test_upscale_image.py,sha256=usoKZAQhpZRmWidLp73YAOito-L_4jCIK7fLA7Y9apA,1661 +google/genai/tests/shared/tunings/__init__.py,sha256=KbDhwTfDYAhkNqkbDeqOxlfFwjij-deuilWGXN9cySc,578 +google/genai/tests/shared/tunings/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/shared/tunings/__pycache__/test_create.cpython-313.pyc,, +google/genai/tests/shared/tunings/__pycache__/test_create_get_cancel.cpython-313.pyc,, +google/genai/tests/shared/tunings/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/shared/tunings/test_create.py,sha256=FlUjMlaw2THfwUr7IKXA1SKDnfvTlhmhZrXsGl7Icl4,1440 +google/genai/tests/shared/tunings/test_create_get_cancel.py,sha256=takzmmhktF7CIyRD4pldCFzxU4J8MP5fjBJD-0QZxkA,1798 +google/genai/tests/shared/tunings/test_list.py,sha256=RNRzoPBjY5eq3AECvIekOTaHB1n8FxfaOytZHyOWOgo,1121 +google/genai/tests/tokens/__init__.py,sha256=KbDhwTfDYAhkNqkbDeqOxlfFwjij-deuilWGXN9cySc,578 +google/genai/tests/tokens/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/tokens/__pycache__/test_create.cpython-313.pyc,, +google/genai/tests/tokens/test_create.py,sha256=iENP2DZxxxpT8cJf3Iirb1erQ7MxcgYAnm7wMN-Eiwc,5452 +google/genai/tests/transformers/__init__.py,sha256=IjrnP6P8utKkw6Xz9zJNQNzT-dIxIHQkv0FxiHDkOPQ,638 +google/genai/tests/transformers/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_blobs.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_bytes.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_function_responses.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_schema.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_t_batch.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_t_content.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_t_contents.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_t_part.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_t_parts.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_t_tool.cpython-313.pyc,, +google/genai/tests/transformers/__pycache__/test_t_tools.cpython-313.pyc,, +google/genai/tests/transformers/test_blobs.py,sha256=B6kNKAc_PsC647dIP_d1jnel25WnOXcg9Cyi1vSQHJ4,2403 +google/genai/tests/transformers/test_bytes.py,sha256=F2yxf_s2cxqGzvqf6uhGuNW53MBmbxuBo2Ea--9jFa0,442 +google/genai/tests/transformers/test_function_responses.py,sha256=J-KTJBskAxiwL2skRidQN2iumi1uS7nqr_2ACzOlCQc,2307 +google/genai/tests/transformers/test_schema.py,sha256=Ebv3HR0GD-DMTenl98mGj9TrMvt1FRlvrIX7ha-zrew,20662 +google/genai/tests/transformers/test_t_batch.py,sha256=LfTJ3ZSkbMISsNv6stUOXlYWTDejj7ZSpnsyzj5jQmo,9512 +google/genai/tests/transformers/test_t_content.py,sha256=qs7yYq9GKeLegcch48XtDnUnKxMbyAGazyBZ2bUXerk,4005 +google/genai/tests/transformers/test_t_contents.py,sha256=Evu3CerxHYc2w-7ZplYNU-JRysCrKsOWN_AsHGHQ7HI,10057 +google/genai/tests/transformers/test_t_part.py,sha256=52lwSQN8UYlJUKIhvKgsmSbP2nQt6D8L465mKVtrU-Q,2002 +google/genai/tests/transformers/test_t_parts.py,sha256=aqQ7mY7hMzmFptLrO7in35WVOHUokdzg5P662zJIAAU,1977 +google/genai/tests/transformers/test_t_tool.py,sha256=XVpdyf4e-zgCcSK6mO9Z3tRE9yqbL07Gt-tLcBj1u1w,4080 +google/genai/tests/transformers/test_t_tools.py,sha256=7-iAVLTOvhOQ-Xlu46-oTAsHfCMwEBf0Np-R87nYqZU,5219 +google/genai/tests/tunings/__init__.py,sha256=KbDhwTfDYAhkNqkbDeqOxlfFwjij-deuilWGXN9cySc,578 +google/genai/tests/tunings/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/tunings/__pycache__/test_cancel.cpython-313.pyc,, +google/genai/tests/tunings/__pycache__/test_end_to_end.cpython-313.pyc,, +google/genai/tests/tunings/__pycache__/test_get.cpython-313.pyc,, +google/genai/tests/tunings/__pycache__/test_list.cpython-313.pyc,, +google/genai/tests/tunings/__pycache__/test_tune.cpython-313.pyc,, +google/genai/tests/tunings/test_cancel.py,sha256=wFBQLIY0Ni1AAxFPjEXdEmewn_6Zg_8aBfDL4pvYiT4,1198 +google/genai/tests/tunings/test_end_to_end.py,sha256=ISDpbJGfHuRBV1TZKgAtOfy7WnXD0ilyCt-9HudcWIs,3124 +google/genai/tests/tunings/test_get.py,sha256=Xaji6XYF33DYZ97j-sQZJ9xuUIJfHiP98vi6I2QDtf0,2060 +google/genai/tests/tunings/test_list.py,sha256=VRCLzodimtyLTAL2k-epqTGZcaVRA7F9pSRPi6TeWYU,2263 +google/genai/tests/tunings/test_tune.py,sha256=7dQjiJA5Uo6be0QqGS3652RWLceTyHX-BFatKzgK-cM,21536 +google/genai/tests/types/__init__.py,sha256=KbDhwTfDYAhkNqkbDeqOxlfFwjij-deuilWGXN9cySc,578 +google/genai/tests/types/__pycache__/__init__.cpython-313.pyc,, +google/genai/tests/types/__pycache__/test_bytes_internal.cpython-313.pyc,, +google/genai/tests/types/__pycache__/test_bytes_type.cpython-313.pyc,, +google/genai/tests/types/__pycache__/test_future.cpython-313.pyc,, +google/genai/tests/types/__pycache__/test_optional_types.cpython-313.pyc,, +google/genai/tests/types/__pycache__/test_part_type.cpython-313.pyc,, +google/genai/tests/types/__pycache__/test_schema_from_json_schema.cpython-313.pyc,, +google/genai/tests/types/__pycache__/test_schema_json_schema.cpython-313.pyc,, +google/genai/tests/types/__pycache__/test_types.cpython-313.pyc,, +google/genai/tests/types/test_bytes_internal.py,sha256=QNA1sez1FozvrJh7K6-HG2FNBGD2-9VG5ZEp_snPGR4,8632 +google/genai/tests/types/test_bytes_type.py,sha256=cWb_-pBwhnJR2Tfk0PTnLiyvG5k1yKhyc_XgESg81rg,5906 +google/genai/tests/types/test_future.py,sha256=F8eW2IyWXjzhIKmwD49yrScRffFiCL-16dwFbXtkxUI,3211 +google/genai/tests/types/test_optional_types.py,sha256=LCA_pAcOJH_7lniZhVu4YG_Yxx9WSXsr0_xzHQzcl5I,1150 +google/genai/tests/types/test_part_type.py,sha256=TRaSCvMPD-hyTUujfeUwGsaAPAkUKzmb8-qQ0pgOHB0,17726 +google/genai/tests/types/test_schema_from_json_schema.py,sha256=WiraJx5mRLW8lKHiWsyHTBYge4jVpeCYklbqGd4BkZQ,13894 +google/genai/tests/types/test_schema_json_schema.py,sha256=zn1gjsXcHTztzmajr8YX3Yb6rWnchjgjw6Yj1NZnG-0,15536 +google/genai/tests/types/test_types.py,sha256=-B42g1PHwQIh4tVo30OZN7QnDFco1CN3RBBfPvzh7Kk,85060 +google/genai/tokens.py,sha256=4BPW0gGWFeFVk3INkuY2tfREnsrvzQDhouvRI6_F9Q8,12235 +google/genai/tunings.py,sha256=amfMSYul7KuZAfTUomvzkrBnqHhJ7MVlkV3c0e1bGyo,92885 +google/genai/types.py,sha256=i5_yQbpD-Ohap1nt6_obfGc6tpnFdj0LnAQ_Oau8U6E,766178 +google/genai/version.py,sha256=lS1gA2itRa3rcYRzd65KJCnOUC1XD5ALRtX_ggveCVA,627 +google_genai-1.72.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_genai-1.72.0.dist-info/METADATA,sha256=ZclqswGwpS-nF3grSwb6O3JTuG7vr-V3JS-ayXuAQYk,52378 +google_genai-1.72.0.dist-info/RECORD,, +google_genai-1.72.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google_genai-1.72.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +google_genai-1.72.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +google_genai-1.72.0.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/google_genai-1.72.0.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8056834e6714b089ef49847820064a1ae4b041fd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/METADATA @@ -0,0 +1,625 @@ +Metadata-Version: 2.4 +Name: httpcore +Version: 1.0.9 +Summary: A minimal low-level HTTP client. +Project-URL: Documentation, https://www.encode.io/httpcore +Project-URL: Homepage, https://www.encode.io/httpcore/ +Project-URL: Source, https://github.com/encode/httpcore +Author-email: Tom Christie +License-Expression: BSD-3-Clause +License-File: LICENSE.md +Classifier: Development Status :: 3 - Alpha +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: Trio +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Requires-Dist: certifi +Requires-Dist: h11>=0.16 +Provides-Extra: asyncio +Requires-Dist: anyio<5.0,>=4.0; extra == 'asyncio' +Provides-Extra: http2 +Requires-Dist: h2<5,>=3; extra == 'http2' +Provides-Extra: socks +Requires-Dist: socksio==1.*; extra == 'socks' +Provides-Extra: trio +Requires-Dist: trio<1.0,>=0.22.0; extra == 'trio' +Description-Content-Type: text/markdown + +# HTTP Core + +[![Test Suite](https://github.com/encode/httpcore/workflows/Test%20Suite/badge.svg)](https://github.com/encode/httpcore/actions) +[![Package version](https://badge.fury.io/py/httpcore.svg)](https://pypi.org/project/httpcore/) + +> *Do one thing, and do it well.* + +The HTTP Core package provides a minimal low-level HTTP client, which does +one thing only. Sending HTTP requests. + +It does not provide any high level model abstractions over the API, +does not handle redirects, multipart uploads, building authentication headers, +transparent HTTP caching, URL parsing, session cookie handling, +content or charset decoding, handling JSON, environment based configuration +defaults, or any of that Jazz. + +Some things HTTP Core does do: + +* Sending HTTP requests. +* Thread-safe / task-safe connection pooling. +* HTTP(S) proxy & SOCKS proxy support. +* Supports HTTP/1.1 and HTTP/2. +* Provides both sync and async interfaces. +* Async backend support for `asyncio` and `trio`. + +## Requirements + +Python 3.8+ + +## Installation + +For HTTP/1.1 only support, install with: + +```shell +$ pip install httpcore +``` + +There are also a number of optional extras available... + +```shell +$ pip install httpcore['asyncio,trio,http2,socks'] +``` + +## Sending requests + +Send an HTTP request: + +```python +import httpcore + +response = httpcore.request("GET", "https://www.example.com/") + +print(response) +# +print(response.status) +# 200 +print(response.headers) +# [(b'Accept-Ranges', b'bytes'), (b'Age', b'557328'), (b'Cache-Control', b'max-age=604800'), ...] +print(response.content) +# b'\n\n\nExample Domain\n\n\n ...' +``` + +The top-level `httpcore.request()` function is provided for convenience. In practice whenever you're working with `httpcore` you'll want to use the connection pooling functionality that it provides. + +```python +import httpcore + +http = httpcore.ConnectionPool() +response = http.request("GET", "https://www.example.com/") +``` + +Once you're ready to get going, [head over to the documentation](https://www.encode.io/httpcore/). + +## Motivation + +You *probably* don't want to be using HTTP Core directly. It might make sense if +you're writing something like a proxy service in Python, and you just want +something at the lowest possible level, but more typically you'll want to use +a higher level client library, such as `httpx`. + +The motivation for `httpcore` is: + +* To provide a reusable low-level client library, that other packages can then build on top of. +* To provide a *really clear interface split* between the networking code and client logic, + so that each is easier to understand and reason about in isolation. + +## Dependencies + +The `httpcore` package has the following dependencies... + +* `h11` +* `certifi` + +And the following optional extras... + +* `anyio` - Required by `pip install httpcore['asyncio']`. +* `trio` - Required by `pip install httpcore['trio']`. +* `h2` - Required by `pip install httpcore['http2']`. +* `socksio` - Required by `pip install httpcore['socks']`. + +## Versioning + +We use [SEMVER for our versioning policy](https://semver.org/). + +For changes between package versions please see our [project changelog](CHANGELOG.md). + +We recommend pinning your requirements either the most current major version, or a more specific version range: + +```python +pip install 'httpcore==1.*' +``` +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## Version 1.0.9 (April 24th, 2025) + +- Resolve https://github.com/advisories/GHSA-vqfr-h8mv-ghfj with h11 dependency update. (#1008) + +## Version 1.0.8 (April 11th, 2025) + +- Fix `AttributeError` when importing on Python 3.14. (#1005) + +## Version 1.0.7 (November 15th, 2024) + +- Support `proxy=…` configuration on `ConnectionPool()`. (#974) + +## Version 1.0.6 (October 1st, 2024) + +- Relax `trio` dependency pinning. (#956) +- Handle `trio` raising `NotImplementedError` on unsupported platforms. (#955) +- Handle mapping `ssl.SSLError` to `httpcore.ConnectError`. (#918) + +## 1.0.5 (March 27th, 2024) + +- Handle `EndOfStream` exception for anyio backend. (#899) +- Allow trio `0.25.*` series in package dependancies. (#903) + +## 1.0.4 (February 21st, 2024) + +- Add `target` request extension. (#888) +- Fix support for connection `Upgrade` and `CONNECT` when some data in the stream has been read. (#882) + +## 1.0.3 (February 13th, 2024) + +- Fix support for async cancellations. (#880) +- Fix trace extension when used with socks proxy. (#849) +- Fix SSL context for connections using the "wss" scheme (#869) + +## 1.0.2 (November 10th, 2023) + +- Fix `float("inf")` timeouts in `Event.wait` function. (#846) + +## 1.0.1 (November 3rd, 2023) + +- Fix pool timeout to account for the total time spent retrying. (#823) +- Raise a neater RuntimeError when the correct async deps are not installed. (#826) +- Add support for synchronous TLS-in-TLS streams. (#840) + +## 1.0.0 (October 6th, 2023) + +From version 1.0 our async support is now optional, as the package has minimal dependencies by default. + +For async support use either `pip install 'httpcore[asyncio]'` or `pip install 'httpcore[trio]'`. + +The project versioning policy is now explicitly governed by SEMVER. See https://semver.org/. + +- Async support becomes fully optional. (#809) +- Add support for Python 3.12. (#807) + +## 0.18.0 (September 8th, 2023) + +- Add support for HTTPS proxies. (#745, #786) +- Drop Python 3.7 support. (#727) +- Handle `sni_hostname` extension with SOCKS proxy. (#774) +- Handle HTTP/1.1 half-closed connections gracefully. (#641) +- Change the type of `Extensions` from `Mapping[Str, Any]` to `MutableMapping[Str, Any]`. (#762) + +## 0.17.3 (July 5th, 2023) + +- Support async cancellations, ensuring that the connection pool is left in a clean state when cancellations occur. (#726) +- The networking backend interface has [been added to the public API](https://www.encode.io/httpcore/network-backends). Some classes which were previously private implementation detail are now part of the top-level public API. (#699) +- Graceful handling of HTTP/2 GoAway frames, with requests being transparently retried on a new connection. (#730) +- Add exceptions when a synchronous `trace callback` is passed to an asynchronous request or an asynchronous `trace callback` is passed to a synchronous request. (#717) +- Drop Python 3.7 support. (#727) + +## 0.17.2 (May 23th, 2023) + +- Add `socket_options` argument to `ConnectionPool` and `HTTProxy` classes. (#668) +- Improve logging with per-module logger names. (#690) +- Add `sni_hostname` request extension. (#696) +- Resolve race condition during import of `anyio` package. (#692) +- Enable TCP_NODELAY for all synchronous sockets. (#651) + +## 0.17.1 (May 17th, 2023) + +- If 'retries' is set, then allow retries if an SSL handshake error occurs. (#669) +- Improve correctness of tracebacks on network exceptions, by raising properly chained exceptions. (#678) +- Prevent connection-hanging behaviour when HTTP/2 connections are closed by a server-sent 'GoAway' frame. (#679) +- Fix edge-case exception when removing requests from the connection pool. (#680) +- Fix pool timeout edge-case. (#688) + +## 0.17.0 (March 16th, 2023) + +- Add DEBUG level logging. (#648) +- Respect HTTP/2 max concurrent streams when settings updates are sent by server. (#652) +- Increase the allowable HTTP header size to 100kB. (#647) +- Add `retries` option to SOCKS proxy classes. (#643) + +## 0.16.3 (December 20th, 2022) + +- Allow `ws` and `wss` schemes. Allows us to properly support websocket upgrade connections. (#625) +- Forwarding HTTP proxies use a connection-per-remote-host. Required by some proxy implementations. (#637) +- Don't raise `RuntimeError` when closing a connection pool with active connections. Removes some error cases when cancellations are used. (#631) +- Lazy import `anyio`, so that it's no longer a hard dependancy, and isn't imported if unused. (#639) + +## 0.16.2 (November 25th, 2022) + +- Revert 'Fix async cancellation behaviour', which introduced race conditions. (#627) +- Raise `RuntimeError` if attempting to us UNIX domain sockets on Windows. (#619) + +## 0.16.1 (November 17th, 2022) + +- Fix HTTP/1.1 interim informational responses, such as "100 Continue". (#605) + +## 0.16.0 (October 11th, 2022) + +- Support HTTP/1.1 informational responses. (#581) +- Fix async cancellation behaviour. (#580) +- Support `h11` 0.14. (#579) + +## 0.15.0 (May 17th, 2022) + +- Drop Python 3.6 support (#535) +- Ensure HTTP proxy CONNECT requests include `timeout` configuration. (#506) +- Switch to explicit `typing.Optional` for type hints. (#513) +- For `trio` map OSError exceptions to `ConnectError`. (#543) + +## 0.14.7 (February 4th, 2022) + +- Requests which raise a PoolTimeout need to be removed from the pool queue. (#502) +- Fix AttributeError that happened when Socks5Connection were terminated. (#501) + +## 0.14.6 (February 1st, 2022) + +- Fix SOCKS support for `http://` URLs. (#492) +- Resolve race condition around exceptions during streaming a response. (#491) + +## 0.14.5 (January 18th, 2022) + +- SOCKS proxy support. (#478) +- Add proxy_auth argument to HTTPProxy. (#481) +- Improve error message on 'RemoteProtocolError' exception when server disconnects without sending a response. (#479) + +## 0.14.4 (January 5th, 2022) + +- Support HTTP/2 on HTTPS tunnelling proxies. (#468) +- Fix proxy headers missing on HTTP forwarding. (#456) +- Only instantiate SSL context if required. (#457) +- More robust HTTP/2 handling. (#253, #439, #440, #441) + +## 0.14.3 (November 17th, 2021) + +- Fix race condition when removing closed connections from the pool. (#437) + +## 0.14.2 (November 16th, 2021) + +- Failed connections no longer remain in the pool. (Pull #433) + +## 0.14.1 (November 12th, 2021) + +- `max_connections` becomes optional. (Pull #429) +- `certifi` is now included in the install dependancies. (Pull #428) +- `h2` is now strictly optional. (Pull #428) + +## 0.14.0 (November 11th, 2021) + +The 0.14 release is a complete reworking of `httpcore`, comprehensively addressing some underlying issues in the connection pooling, as well as substantially redesigning the API to be more user friendly. + +Some of the lower-level API design also makes the components more easily testable in isolation, and the package now has 100% test coverage. + +See [discussion #419](https://github.com/encode/httpcore/discussions/419) for a little more background. + +There's some other neat bits in there too, such as the "trace" extension, which gives a hook into inspecting the internal events that occur during the request/response cycle. This extension is needed for the HTTPX cli, in order to... + +* Log the point at which the connection is established, and the IP/port on which it is made. +* Determine if the outgoing request should log as HTTP/1.1 or HTTP/2, rather than having to assume it's HTTP/2 if the --http2 flag was passed. (Which may not actually be true.) +* Log SSL version info / certificate info. + +Note that `curio` support is not currently available in 0.14.0. If you're using `httpcore` with `curio` please get in touch, so we can assess if we ought to prioritize it as a feature or not. + +## 0.13.7 (September 13th, 2021) + +- Fix broken error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #403) + +## 0.13.6 (June 15th, 2021) + +### Fixed + +- Close sockets when read or write timeouts occur. (Pull #365) + +## 0.13.5 (June 14th, 2021) + +### Fixed + +- Resolved niggles with AnyIO EOF behaviours. (Pull #358, #362) + +## 0.13.4 (June 9th, 2021) + +### Added + +- Improved error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #354) + +### Fixed + +- Switched to `anyio` as the default backend implementation when running with `asyncio`. Resolves some awkward [TLS timeout issues](https://github.com/encode/httpx/discussions/1511). + +## 0.13.3 (May 6th, 2021) + +### Added + +- Support HTTP/2 prior knowledge, using `httpcore.SyncConnectionPool(http1=False)`. (Pull #333) + +### Fixed + +- Handle cases where environment does not provide `select.poll` support. (Pull #331) + +## 0.13.2 (April 29th, 2021) + +### Added + +- Improve error message for specific case of `RemoteProtocolError` where server disconnects without sending a response. (Pull #313) + +## 0.13.1 (April 28th, 2021) + +### Fixed + +- More resiliant testing for closed connections. (Pull #311) +- Don't raise exceptions on ungraceful connection closes. (Pull #310) + +## 0.13.0 (April 21st, 2021) + +The 0.13 release updates the core API in order to match the HTTPX Transport API, +introduced in HTTPX 0.18 onwards. + +An example of making requests with the new interface is: + +```python +with httpcore.SyncConnectionPool() as http: + status_code, headers, stream, extensions = http.handle_request( + method=b'GET', + url=(b'https', b'example.org', 443, b'/'), + headers=[(b'host', b'example.org'), (b'user-agent', b'httpcore')] + stream=httpcore.ByteStream(b''), + extensions={} + ) + body = stream.read() + print(status_code, body) +``` + +### Changed + +- The `.request()` method is now `handle_request()`. (Pull #296) +- The `.arequest()` method is now `.handle_async_request()`. (Pull #296) +- The `headers` argument is no longer optional. (Pull #296) +- The `stream` argument is no longer optional. (Pull #296) +- The `ext` argument is now named `extensions`, and is no longer optional. (Pull #296) +- The `"reason"` extension keyword is now named `"reason_phrase"`. (Pull #296) +- The `"reason_phrase"` and `"http_version"` extensions now use byte strings for their values. (Pull #296) +- The `httpcore.PlainByteStream()` class becomes `httpcore.ByteStream()`. (Pull #296) + +### Added + +- Streams now support a `.read()` interface. (Pull #296) + +### Fixed + +- Task cancellation no longer leaks connections from the connection pool. (Pull #305) + +## 0.12.3 (December 7th, 2020) + +### Fixed + +- Abort SSL connections on close rather than waiting for remote EOF when using `asyncio`. (Pull #167) +- Fix exception raised in case of connect timeouts when using the `anyio` backend. (Pull #236) +- Fix `Host` header precedence for `:authority` in HTTP/2. (Pull #241, #243) +- Handle extra edge case when detecting for socket readability when using `asyncio`. (Pull #242, #244) +- Fix `asyncio` SSL warning when using proxy tunneling. (Pull #249) + +## 0.12.2 (November 20th, 2020) + +### Fixed + +- Properly wrap connect errors on the asyncio backend. (Pull #235) +- Fix `ImportError` occurring on Python 3.9 when using the HTTP/1.1 sync client in a multithreaded context. (Pull #237) + +## 0.12.1 (November 7th, 2020) + +### Added + +- Add connect retries. (Pull #221) + +### Fixed + +- Tweak detection of dropped connections, resolving an issue with open files limits on Linux. (Pull #185) +- Avoid leaking connections when establishing an HTTP tunnel to a proxy has failed. (Pull #223) +- Properly wrap OS errors when using `trio`. (Pull #225) + +## 0.12.0 (October 6th, 2020) + +### Changed + +- HTTP header casing is now preserved, rather than always sent in lowercase. (#216 and python-hyper/h11#104) + +### Added + +- Add Python 3.9 to officially supported versions. + +### Fixed + +- Gracefully handle a stdlib asyncio bug when a connection is closed while it is in a paused-for-reading state. (#201) + +## 0.11.1 (September 28nd, 2020) + +### Fixed + +- Add await to async semaphore release() coroutine (#197) +- Drop incorrect curio classifier (#192) + +## 0.11.0 (September 22nd, 2020) + +The Transport API with 0.11.0 has a couple of significant changes. + +Firstly we've moved changed the request interface in order to allow extensions, which will later enable us to support features +such as trailing headers, HTTP/2 server push, and CONNECT/Upgrade connections. + +The interface changes from: + +```python +def request(method, url, headers, stream, timeout): + return (http_version, status_code, reason, headers, stream) +``` + +To instead including an optional dictionary of extensions on the request and response: + +```python +def request(method, url, headers, stream, ext): + return (status_code, headers, stream, ext) +``` + +Having an open-ended extensions point will allow us to add later support for various optional features, that wouldn't otherwise be supported without these API changes. + +In particular: + +* Trailing headers support. +* HTTP/2 Server Push +* sendfile. +* Exposing raw connection on CONNECT, Upgrade, HTTP/2 bi-di streaming. +* Exposing debug information out of the API, including template name, template context. + +Currently extensions are limited to: + +* request: `timeout` - Optional. Timeout dictionary. +* response: `http_version` - Optional. Include the HTTP version used on the response. +* response: `reason` - Optional. Include the reason phrase used on the response. Only valid with HTTP/1.*. + +See https://github.com/encode/httpx/issues/1274#issuecomment-694884553 for the history behind this. + +Secondly, the async version of `request` is now namespaced as `arequest`. + +This allows concrete transports to support both sync and async implementations on the same class. + +### Added + +- Add curio support. (Pull #168) +- Add anyio support, with `backend="anyio"`. (Pull #169) + +### Changed + +- Update the Transport API to use 'ext' for optional extensions. (Pull #190) +- Update the Transport API to use `.request` and `.arequest` so implementations can support both sync and async. (Pull #189) + +## 0.10.2 (August 20th, 2020) + +### Added + +- Added Unix Domain Socket support. (Pull #139) + +### Fixed + +- Always include the port on proxy CONNECT requests. (Pull #154) +- Fix `max_keepalive_connections` configuration. (Pull #153) +- Fixes behaviour in HTTP/1.1 where server disconnects can be used to signal the end of the response body. (Pull #164) + +## 0.10.1 (August 7th, 2020) + +- Include `max_keepalive_connections` on `AsyncHTTPProxy`/`SyncHTTPProxy` classes. + +## 0.10.0 (August 7th, 2020) + +The most notable change in the 0.10.0 release is that HTTP/2 support is now fully optional. + +Use either `pip install httpcore` for HTTP/1.1 support only, or `pip install httpcore[http2]` for HTTP/1.1 and HTTP/2 support. + +### Added + +- HTTP/2 support becomes optional. (Pull #121, #130) +- Add `local_address=...` support. (Pull #100, #134) +- Add `PlainByteStream`, `IteratorByteStream`, `AsyncIteratorByteStream`. The `AsyncByteSteam` and `SyncByteStream` classes are now pure interface classes. (#133) +- Add `LocalProtocolError`, `RemoteProtocolError` exceptions. (Pull #129) +- Add `UnsupportedProtocol` exception. (Pull #128) +- Add `.get_connection_info()` method. (Pull #102, #137) +- Add better TRACE logs. (Pull #101) + +### Changed + +- `max_keepalive` is deprecated in favour of `max_keepalive_connections`. (Pull #140) + +### Fixed + +- Improve handling of server disconnects. (Pull #112) + +## 0.9.1 (May 27th, 2020) + +### Fixed + +- Proper host resolution for sync case, including IPv6 support. (Pull #97) +- Close outstanding connections when connection pool is closed. (Pull #98) + +## 0.9.0 (May 21th, 2020) + +### Changed + +- URL port becomes an `Optional[int]` instead of `int`. (Pull #92) + +### Fixed + +- Honor HTTP/2 max concurrent streams settings. (Pull #89, #90) +- Remove incorrect debug log. (Pull #83) + +## 0.8.4 (May 11th, 2020) + +### Added + +- Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variables +and TRACE level logging. (Pull #79) + +### Fixed + +- Reuse of connections on HTTP/2 in close concurrency situations. (Pull #81) + +## 0.8.3 (May 6rd, 2020) + +### Fixed + +- Include `Host` and `Accept` headers on proxy "CONNECT" requests. +- De-duplicate any headers also contained in proxy_headers. +- HTTP/2 flag not being passed down to proxy connections. + +## 0.8.2 (May 3rd, 2020) + +### Fixed + +- Fix connections using proxy forwarding requests not being added to the +connection pool properly. (Pull #70) + +## 0.8.1 (April 30th, 2020) + +### Changed + +- Allow inherintance of both `httpcore.AsyncByteStream`, `httpcore.SyncByteStream` without type conflicts. + +## 0.8.0 (April 30th, 2020) + +### Fixed + +- Fixed tunnel proxy support. + +### Added + +- New `TimeoutException` base class. + +## 0.7.0 (March 5th, 2020) + +- First integration with HTTPX. diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..2721ed2f4e591feebbb740ca2352ba08f70bb689 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/RECORD @@ -0,0 +1,68 @@ +httpcore-1.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpcore-1.0.9.dist-info/METADATA,sha256=_i1P2mGZEol4d54M8n88BFxTGGP83Zh-rMdPOhjUHCE,21529 +httpcore-1.0.9.dist-info/RECORD,, +httpcore-1.0.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +httpcore-1.0.9.dist-info/licenses/LICENSE.md,sha256=_ctZFUx0y6uhahEkL3dAvqnyPW_rVUeRfYxflKgDkqU,1518 +httpcore/__init__.py,sha256=9kT_kqChCCJUTHww24ZmR_ezcdbpRYWksD-gYNzkZP8,3445 +httpcore/__pycache__/__init__.cpython-313.pyc,, +httpcore/__pycache__/_api.cpython-313.pyc,, +httpcore/__pycache__/_exceptions.cpython-313.pyc,, +httpcore/__pycache__/_models.cpython-313.pyc,, +httpcore/__pycache__/_ssl.cpython-313.pyc,, +httpcore/__pycache__/_synchronization.cpython-313.pyc,, +httpcore/__pycache__/_trace.cpython-313.pyc,, +httpcore/__pycache__/_utils.cpython-313.pyc,, +httpcore/_api.py,sha256=unZmeDschBWCGCPCwkS3Wot9euK6bg_kKxLtGTxw214,3146 +httpcore/_async/__init__.py,sha256=EWdl2v4thnAHzJpqjU4h2a8DUiGAvNiWrkii9pfhTf0,1221 +httpcore/_async/__pycache__/__init__.cpython-313.pyc,, +httpcore/_async/__pycache__/connection.cpython-313.pyc,, +httpcore/_async/__pycache__/connection_pool.cpython-313.pyc,, +httpcore/_async/__pycache__/http11.cpython-313.pyc,, +httpcore/_async/__pycache__/http2.cpython-313.pyc,, +httpcore/_async/__pycache__/http_proxy.cpython-313.pyc,, +httpcore/_async/__pycache__/interfaces.cpython-313.pyc,, +httpcore/_async/__pycache__/socks_proxy.cpython-313.pyc,, +httpcore/_async/connection.py,sha256=6OcPXqMEfc0BU38_-iHUNDd1vKSTc2UVT09XqNb_BOk,8449 +httpcore/_async/connection_pool.py,sha256=DOIQ2s2ZCf9qfwxhzMprTPLqCL8OxGXiKF6qRHxvVyY,17307 +httpcore/_async/http11.py,sha256=-qM9bV7PjSQF5vxs37-eUXOIFwbIjPcZbNliuX9TtBw,13880 +httpcore/_async/http2.py,sha256=azX1fcmtXaIwjputFlZ4vd92J8xwjGOa9ax9QIv4394,23936 +httpcore/_async/http_proxy.py,sha256=2zVkrlv-Ds-rWGaqaXlrhEJiAQFPo23BT3Gq_sWoBXU,14701 +httpcore/_async/interfaces.py,sha256=jTiaWL83pgpGC9ziv90ZfwaKNMmHwmOalzaKiuTxATo,4455 +httpcore/_async/socks_proxy.py,sha256=lLKgLlggPfhFlqi0ODeBkOWvt9CghBBUyqsnsU1tx6Q,13841 +httpcore/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +httpcore/_backends/__pycache__/__init__.cpython-313.pyc,, +httpcore/_backends/__pycache__/anyio.cpython-313.pyc,, +httpcore/_backends/__pycache__/auto.cpython-313.pyc,, +httpcore/_backends/__pycache__/base.cpython-313.pyc,, +httpcore/_backends/__pycache__/mock.cpython-313.pyc,, +httpcore/_backends/__pycache__/sync.cpython-313.pyc,, +httpcore/_backends/__pycache__/trio.cpython-313.pyc,, +httpcore/_backends/anyio.py,sha256=x8PgEhXRC8bVqsdzk_YJx8Y6d9Tub06CuUSwnbmtqoY,5252 +httpcore/_backends/auto.py,sha256=zO136PKZmsaTDK-HRk84eA-MUg8_2wJf4NvmK432Aio,1662 +httpcore/_backends/base.py,sha256=aShgRdZnMmRhFWHetjumlM73f8Kz1YOAyCUP_4kHslA,3042 +httpcore/_backends/mock.py,sha256=er9T436uSe7NLrfiLa4x6Nuqg5ivQ693CxWYCWsgbH4,4077 +httpcore/_backends/sync.py,sha256=bhE4d9iK9Umxdsdsgm2EfKnXaBms2WggGYU-7jmUujU,7977 +httpcore/_backends/trio.py,sha256=LHu4_Mr5MswQmmT3yE4oLgf9b_JJfeVS4BjDxeJc7Ro,5996 +httpcore/_exceptions.py,sha256=looCKga3_YVYu3s-d3L9RMPRJyhsY7fiuuGxvkOD0c0,1184 +httpcore/_models.py,sha256=IO2CcXcdpovRcLTdGFGB6RyBZdEm2h_TOmoCc4rEKho,17623 +httpcore/_ssl.py,sha256=srqmSNU4iOUvWF-SrJvb8G_YEbHFELOXQOwdDIBTS9c,187 +httpcore/_sync/__init__.py,sha256=JBDIgXt5la1LCJ1sLQeKhjKFpLnpNr8Svs6z2ni3fgg,1141 +httpcore/_sync/__pycache__/__init__.cpython-313.pyc,, +httpcore/_sync/__pycache__/connection.cpython-313.pyc,, +httpcore/_sync/__pycache__/connection_pool.cpython-313.pyc,, +httpcore/_sync/__pycache__/http11.cpython-313.pyc,, +httpcore/_sync/__pycache__/http2.cpython-313.pyc,, +httpcore/_sync/__pycache__/http_proxy.cpython-313.pyc,, +httpcore/_sync/__pycache__/interfaces.cpython-313.pyc,, +httpcore/_sync/__pycache__/socks_proxy.cpython-313.pyc,, +httpcore/_sync/connection.py,sha256=9exGOb3PB-Mp2T1-sckSeL2t-tJ_9-NXomV8ihmWCgU,8238 +httpcore/_sync/connection_pool.py,sha256=a-T8LTsUxc7r0Ww1atfHSDoWPjQ0fA8Ul7S3-F0Mj70,16955 +httpcore/_sync/http11.py,sha256=IFobD1Md5JFlJGKWnh1_Q3epikUryI8qo09v8MiJIEA,13476 +httpcore/_sync/http2.py,sha256=AxU4yhcq68Bn5vqdJYtiXKYUj7nvhYbxz3v4rT4xnvA,23400 +httpcore/_sync/http_proxy.py,sha256=_al_6crKuEZu2wyvu493RZImJdBJnj5oGKNjLOJL2Zo,14463 +httpcore/_sync/interfaces.py,sha256=snXON42vUDHO5JBJvo8D4VWk2Wat44z2OXXHDrjbl94,4344 +httpcore/_sync/socks_proxy.py,sha256=zegZW9Snqj2_992DFJa8_CppOVBkVL4AgwduRkStakQ,13614 +httpcore/_synchronization.py,sha256=zSi13mAColBnknjZBknUC6hKNDQT4C6ijnezZ-r0T2s,9434 +httpcore/_trace.py,sha256=ck6ZoIzYTkdNAIfq5MGeKqBXDtqjOX-qfYwmZFbrGco,3952 +httpcore/_utils.py,sha256=_RLgXYOAYC350ikALV59GZ68IJrdocRZxPs9PjmzdFY,1537 +httpcore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore-1.0.9.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/__init__.py b/data/miniconda3/lib/python3.13/site-packages/httpcore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a92dc4a440bdf6f259ec1083c89c817eb7b631b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore/__init__.py @@ -0,0 +1,141 @@ +from ._api import request, stream +from ._async import ( + AsyncConnectionInterface, + AsyncConnectionPool, + AsyncHTTP2Connection, + AsyncHTTP11Connection, + AsyncHTTPConnection, + AsyncHTTPProxy, + AsyncSOCKSProxy, +) +from ._backends.base import ( + SOCKET_OPTION, + AsyncNetworkBackend, + AsyncNetworkStream, + NetworkBackend, + NetworkStream, +) +from ._backends.mock import AsyncMockBackend, AsyncMockStream, MockBackend, MockStream +from ._backends.sync import SyncBackend +from ._exceptions import ( + ConnectError, + ConnectionNotAvailable, + ConnectTimeout, + LocalProtocolError, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadError, + ReadTimeout, + RemoteProtocolError, + TimeoutException, + UnsupportedProtocol, + WriteError, + WriteTimeout, +) +from ._models import URL, Origin, Proxy, Request, Response +from ._ssl import default_ssl_context +from ._sync import ( + ConnectionInterface, + ConnectionPool, + HTTP2Connection, + HTTP11Connection, + HTTPConnection, + HTTPProxy, + SOCKSProxy, +) + +# The 'httpcore.AnyIOBackend' class is conditional on 'anyio' being installed. +try: + from ._backends.anyio import AnyIOBackend +except ImportError: # pragma: nocover + + class AnyIOBackend: # type: ignore + def __init__(self, *args, **kwargs): # type: ignore + msg = ( + "Attempted to use 'httpcore.AnyIOBackend' but 'anyio' is not installed." + ) + raise RuntimeError(msg) + + +# The 'httpcore.TrioBackend' class is conditional on 'trio' being installed. +try: + from ._backends.trio import TrioBackend +except ImportError: # pragma: nocover + + class TrioBackend: # type: ignore + def __init__(self, *args, **kwargs): # type: ignore + msg = "Attempted to use 'httpcore.TrioBackend' but 'trio' is not installed." + raise RuntimeError(msg) + + +__all__ = [ + # top-level requests + "request", + "stream", + # models + "Origin", + "URL", + "Request", + "Response", + "Proxy", + # async + "AsyncHTTPConnection", + "AsyncConnectionPool", + "AsyncHTTPProxy", + "AsyncHTTP11Connection", + "AsyncHTTP2Connection", + "AsyncConnectionInterface", + "AsyncSOCKSProxy", + # sync + "HTTPConnection", + "ConnectionPool", + "HTTPProxy", + "HTTP11Connection", + "HTTP2Connection", + "ConnectionInterface", + "SOCKSProxy", + # network backends, implementations + "SyncBackend", + "AnyIOBackend", + "TrioBackend", + # network backends, mock implementations + "AsyncMockBackend", + "AsyncMockStream", + "MockBackend", + "MockStream", + # network backends, interface + "AsyncNetworkStream", + "AsyncNetworkBackend", + "NetworkStream", + "NetworkBackend", + # util + "default_ssl_context", + "SOCKET_OPTION", + # exceptions + "ConnectionNotAvailable", + "ProxyError", + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", + "UnsupportedProtocol", + "TimeoutException", + "PoolTimeout", + "ConnectTimeout", + "ReadTimeout", + "WriteTimeout", + "NetworkError", + "ConnectError", + "ReadError", + "WriteError", +] + +__version__ = "1.0.9" + + +__locals = locals() +for __name in __all__: + # Exclude SOCKET_OPTION, it causes AttributeError on Python 3.14 + if not __name.startswith(("__", "SOCKET_OPTION")): + setattr(__locals[__name], "__module__", "httpcore") # noqa diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/_api.py b/data/miniconda3/lib/python3.13/site-packages/httpcore/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..38b961d10de88bebc98c758d0d1f14af1e7c0370 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore/_api.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import contextlib +import typing + +from ._models import URL, Extensions, HeaderTypes, Response +from ._sync.connection_pool import ConnectionPool + + +def request( + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, +) -> Response: + """ + Sends an HTTP request, returning the response. + + ``` + response = httpcore.request("GET", "https://www.example.com/") + ``` + + Arguments: + method: The HTTP method for the request. Typically one of `"GET"`, + `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. + url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, + or as str/bytes. + headers: The HTTP request headers. Either as a dictionary of str/bytes, + or as a list of two-tuples of str/bytes. + content: The content of the request body. Either as bytes, + or as a bytes iterator. + extensions: A dictionary of optional extra information included on the request. + Possible keys include `"timeout"`. + + Returns: + An instance of `httpcore.Response`. + """ + with ConnectionPool() as pool: + return pool.request( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) + + +@contextlib.contextmanager +def stream( + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, +) -> typing.Iterator[Response]: + """ + Sends an HTTP request, returning the response within a content manager. + + ``` + with httpcore.stream("GET", "https://www.example.com/") as response: + ... + ``` + + When using the `stream()` function, the body of the response will not be + automatically read. If you want to access the response body you should + either use `content = response.read()`, or `for chunk in response.iter_content()`. + + Arguments: + method: The HTTP method for the request. Typically one of `"GET"`, + `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. + url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, + or as str/bytes. + headers: The HTTP request headers. Either as a dictionary of str/bytes, + or as a list of two-tuples of str/bytes. + content: The content of the request body. Either as bytes, + or as a bytes iterator. + extensions: A dictionary of optional extra information included on the request. + Possible keys include `"timeout"`. + + Returns: + An instance of `httpcore.Response`. + """ + with ConnectionPool() as pool: + with pool.stream( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) as response: + yield response diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/_exceptions.py b/data/miniconda3/lib/python3.13/site-packages/httpcore/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..bc28d44f55bdc4b872951a74780469a3999d9ab4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore/_exceptions.py @@ -0,0 +1,81 @@ +import contextlib +import typing + +ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]] + + +@contextlib.contextmanager +def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]: + try: + yield + except Exception as exc: # noqa: PIE786 + for from_exc, to_exc in map.items(): + if isinstance(exc, from_exc): + raise to_exc(exc) from exc + raise # pragma: nocover + + +class ConnectionNotAvailable(Exception): + pass + + +class ProxyError(Exception): + pass + + +class UnsupportedProtocol(Exception): + pass + + +class ProtocolError(Exception): + pass + + +class RemoteProtocolError(ProtocolError): + pass + + +class LocalProtocolError(ProtocolError): + pass + + +# Timeout errors + + +class TimeoutException(Exception): + pass + + +class PoolTimeout(TimeoutException): + pass + + +class ConnectTimeout(TimeoutException): + pass + + +class ReadTimeout(TimeoutException): + pass + + +class WriteTimeout(TimeoutException): + pass + + +# Network errors + + +class NetworkError(Exception): + pass + + +class ConnectError(NetworkError): + pass + + +class ReadError(NetworkError): + pass + + +class WriteError(NetworkError): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/_models.py b/data/miniconda3/lib/python3.13/site-packages/httpcore/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8a65f13347d6621289a166d08123cbc8e1ad0157 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore/_models.py @@ -0,0 +1,516 @@ +from __future__ import annotations + +import base64 +import ssl +import typing +import urllib.parse + +# Functions for typechecking... + + +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] +HeaderTypes = typing.Union[HeadersAsSequence, HeadersAsMapping, None] + +Extensions = typing.MutableMapping[str, typing.Any] + + +def enforce_bytes(value: bytes | str, *, name: str) -> bytes: + """ + Any arguments that are ultimately represented as bytes can be specified + either as bytes or as strings. + + However we enforce that any string arguments must only contain characters in + the plain ASCII range. chr(0)...chr(127). If you need to use characters + outside that range then be precise, and use a byte-wise argument. + """ + if isinstance(value, str): + try: + return value.encode("ascii") + except UnicodeEncodeError: + raise TypeError(f"{name} strings may not include unicode characters.") + elif isinstance(value, bytes): + return value + + seen_type = type(value).__name__ + raise TypeError(f"{name} must be bytes or str, but got {seen_type}.") + + +def enforce_url(value: URL | bytes | str, *, name: str) -> URL: + """ + Type check for URL parameters. + """ + if isinstance(value, (bytes, str)): + return URL(value) + elif isinstance(value, URL): + return value + + seen_type = type(value).__name__ + raise TypeError(f"{name} must be a URL, bytes, or str, but got {seen_type}.") + + +def enforce_headers( + value: HeadersAsMapping | HeadersAsSequence | None = None, *, name: str +) -> list[tuple[bytes, bytes]]: + """ + Convienence function that ensure all items in request or response headers + are either bytes or strings in the plain ASCII range. + """ + if value is None: + return [] + elif isinstance(value, typing.Mapping): + return [ + ( + enforce_bytes(k, name="header name"), + enforce_bytes(v, name="header value"), + ) + for k, v in value.items() + ] + elif isinstance(value, typing.Sequence): + return [ + ( + enforce_bytes(k, name="header name"), + enforce_bytes(v, name="header value"), + ) + for k, v in value + ] + + seen_type = type(value).__name__ + raise TypeError( + f"{name} must be a mapping or sequence of two-tuples, but got {seen_type}." + ) + + +def enforce_stream( + value: bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes] | None, + *, + name: str, +) -> typing.Iterable[bytes] | typing.AsyncIterable[bytes]: + if value is None: + return ByteStream(b"") + elif isinstance(value, bytes): + return ByteStream(value) + return value + + +# * https://tools.ietf.org/html/rfc3986#section-3.2.3 +# * https://url.spec.whatwg.org/#url-miscellaneous +# * https://url.spec.whatwg.org/#scheme-state +DEFAULT_PORTS = { + b"ftp": 21, + b"http": 80, + b"https": 443, + b"ws": 80, + b"wss": 443, +} + + +def include_request_headers( + headers: list[tuple[bytes, bytes]], + *, + url: "URL", + content: None | bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes], +) -> list[tuple[bytes, bytes]]: + headers_set = set(k.lower() for k, v in headers) + + if b"host" not in headers_set: + default_port = DEFAULT_PORTS.get(url.scheme) + if url.port is None or url.port == default_port: + header_value = url.host + else: + header_value = b"%b:%d" % (url.host, url.port) + headers = [(b"Host", header_value)] + headers + + if ( + content is not None + and b"content-length" not in headers_set + and b"transfer-encoding" not in headers_set + ): + if isinstance(content, bytes): + content_length = str(len(content)).encode("ascii") + headers += [(b"Content-Length", content_length)] + else: + headers += [(b"Transfer-Encoding", b"chunked")] # pragma: nocover + + return headers + + +# Interfaces for byte streams... + + +class ByteStream: + """ + A container for non-streaming content, and that supports both sync and async + stream iteration. + """ + + def __init__(self, content: bytes) -> None: + self._content = content + + def __iter__(self) -> typing.Iterator[bytes]: + yield self._content + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + yield self._content + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{len(self._content)} bytes]>" + + +class Origin: + def __init__(self, scheme: bytes, host: bytes, port: int) -> None: + self.scheme = scheme + self.host = host + self.port = port + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, Origin) + and self.scheme == other.scheme + and self.host == other.host + and self.port == other.port + ) + + def __str__(self) -> str: + scheme = self.scheme.decode("ascii") + host = self.host.decode("ascii") + port = str(self.port) + return f"{scheme}://{host}:{port}" + + +class URL: + """ + Represents the URL against which an HTTP request may be made. + + The URL may either be specified as a plain string, for convienence: + + ```python + url = httpcore.URL("https://www.example.com/") + ``` + + Or be constructed with explicitily pre-parsed components: + + ```python + url = httpcore.URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/') + ``` + + Using this second more explicit style allows integrations that are using + `httpcore` to pass through URLs that have already been parsed in order to use + libraries such as `rfc-3986` rather than relying on the stdlib. It also ensures + that URL parsing is treated identically at both the networking level and at any + higher layers of abstraction. + + The four components are important here, as they allow the URL to be precisely + specified in a pre-parsed format. They also allow certain types of request to + be created that could not otherwise be expressed. + + For example, an HTTP request to `http://www.example.com/` forwarded via a proxy + at `http://localhost:8080`... + + ```python + # Constructs an HTTP request with a complete URL as the target: + # GET https://www.example.com/ HTTP/1.1 + url = httpcore.URL( + scheme=b'http', + host=b'localhost', + port=8080, + target=b'https://www.example.com/' + ) + request = httpcore.Request( + method="GET", + url=url + ) + ``` + + Another example is constructing an `OPTIONS *` request... + + ```python + # Constructs an 'OPTIONS *' HTTP request: + # OPTIONS * HTTP/1.1 + url = httpcore.URL(scheme=b'https', host=b'www.example.com', target=b'*') + request = httpcore.Request(method="OPTIONS", url=url) + ``` + + This kind of request is not possible to formulate with a URL string, + because the `/` delimiter is always used to demark the target from the + host/port portion of the URL. + + For convenience, string-like arguments may be specified either as strings or + as bytes. However, once a request is being issue over-the-wire, the URL + components are always ultimately required to be a bytewise representation. + + In order to avoid any ambiguity over character encodings, when strings are used + as arguments, they must be strictly limited to the ASCII range `chr(0)`-`chr(127)`. + If you require a bytewise representation that is outside this range you must + handle the character encoding directly, and pass a bytes instance. + """ + + def __init__( + self, + url: bytes | str = "", + *, + scheme: bytes | str = b"", + host: bytes | str = b"", + port: int | None = None, + target: bytes | str = b"", + ) -> None: + """ + Parameters: + url: The complete URL as a string or bytes. + scheme: The URL scheme as a string or bytes. + Typically either `"http"` or `"https"`. + host: The URL host as a string or bytes. Such as `"www.example.com"`. + port: The port to connect to. Either an integer or `None`. + target: The target of the HTTP request. Such as `"/items?search=red"`. + """ + if url: + parsed = urllib.parse.urlparse(enforce_bytes(url, name="url")) + self.scheme = parsed.scheme + self.host = parsed.hostname or b"" + self.port = parsed.port + self.target = (parsed.path or b"/") + ( + b"?" + parsed.query if parsed.query else b"" + ) + else: + self.scheme = enforce_bytes(scheme, name="scheme") + self.host = enforce_bytes(host, name="host") + self.port = port + self.target = enforce_bytes(target, name="target") + + @property + def origin(self) -> Origin: + default_port = { + b"http": 80, + b"https": 443, + b"ws": 80, + b"wss": 443, + b"socks5": 1080, + b"socks5h": 1080, + }[self.scheme] + return Origin( + scheme=self.scheme, host=self.host, port=self.port or default_port + ) + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, URL) + and other.scheme == self.scheme + and other.host == self.host + and other.port == self.port + and other.target == self.target + ) + + def __bytes__(self) -> bytes: + if self.port is None: + return b"%b://%b%b" % (self.scheme, self.host, self.target) + return b"%b://%b:%d%b" % (self.scheme, self.host, self.port, self.target) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(scheme={self.scheme!r}, " + f"host={self.host!r}, port={self.port!r}, target={self.target!r})" + ) + + +class Request: + """ + An HTTP request. + """ + + def __init__( + self, + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, + extensions: Extensions | None = None, + ) -> None: + """ + Parameters: + method: The HTTP request method, either as a string or bytes. + For example: `GET`. + url: The request URL, either as a `URL` instance, or as a string or bytes. + For example: `"https://www.example.com".` + headers: The HTTP request headers. + content: The content of the request body. + extensions: A dictionary of optional extra information included on + the request. Possible keys include `"timeout"`, and `"trace"`. + """ + self.method: bytes = enforce_bytes(method, name="method") + self.url: URL = enforce_url(url, name="url") + self.headers: list[tuple[bytes, bytes]] = enforce_headers( + headers, name="headers" + ) + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") + ) + self.extensions = {} if extensions is None else extensions + + if "target" in self.extensions: + self.url = URL( + scheme=self.url.scheme, + host=self.url.host, + port=self.url.port, + target=self.extensions["target"], + ) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.method!r}]>" + + +class Response: + """ + An HTTP response. + """ + + def __init__( + self, + status: int, + *, + headers: HeaderTypes = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, + extensions: Extensions | None = None, + ) -> None: + """ + Parameters: + status: The HTTP status code of the response. For example `200`. + headers: The HTTP response headers. + content: The content of the response body. + extensions: A dictionary of optional extra information included on + the responseself.Possible keys include `"http_version"`, + `"reason_phrase"`, and `"network_stream"`. + """ + self.status: int = status + self.headers: list[tuple[bytes, bytes]] = enforce_headers( + headers, name="headers" + ) + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") + ) + self.extensions = {} if extensions is None else extensions + + self._stream_consumed = False + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + if isinstance(self.stream, typing.Iterable): + raise RuntimeError( + "Attempted to access 'response.content' on a streaming response. " + "Call 'response.read()' first." + ) + else: + raise RuntimeError( + "Attempted to access 'response.content' on a streaming response. " + "Call 'await response.aread()' first." + ) + return self._content + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.status}]>" + + # Sync interface... + + def read(self) -> bytes: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to read an asynchronous response using 'response.read()'. " + "You should use 'await response.aread()' instead." + ) + if not hasattr(self, "_content"): + self._content = b"".join([part for part in self.iter_stream()]) + return self._content + + def iter_stream(self) -> typing.Iterator[bytes]: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to stream an asynchronous response using 'for ... in " + "response.iter_stream()'. " + "You should use 'async for ... in response.aiter_stream()' instead." + ) + if self._stream_consumed: + raise RuntimeError( + "Attempted to call 'for ... in response.iter_stream()' more than once." + ) + self._stream_consumed = True + for chunk in self.stream: + yield chunk + + def close(self) -> None: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to close an asynchronous response using 'response.close()'. " + "You should use 'await response.aclose()' instead." + ) + if hasattr(self.stream, "close"): + self.stream.close() + + # Async interface... + + async def aread(self) -> bytes: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to read an synchronous response using " + "'await response.aread()'. " + "You should use 'response.read()' instead." + ) + if not hasattr(self, "_content"): + self._content = b"".join([part async for part in self.aiter_stream()]) + return self._content + + async def aiter_stream(self) -> typing.AsyncIterator[bytes]: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to stream an synchronous response using 'async for ... in " + "response.aiter_stream()'. " + "You should use 'for ... in response.iter_stream()' instead." + ) + if self._stream_consumed: + raise RuntimeError( + "Attempted to call 'async for ... in response.aiter_stream()' " + "more than once." + ) + self._stream_consumed = True + async for chunk in self.stream: + yield chunk + + async def aclose(self) -> None: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to close a synchronous response using " + "'await response.aclose()'. " + "You should use 'response.close()' instead." + ) + if hasattr(self.stream, "aclose"): + await self.stream.aclose() + + +class Proxy: + def __init__( + self, + url: URL | bytes | str, + auth: tuple[bytes | str, bytes | str] | None = None, + headers: HeadersAsMapping | HeadersAsSequence | None = None, + ssl_context: ssl.SSLContext | None = None, + ): + self.url = enforce_url(url, name="url") + self.headers = enforce_headers(headers, name="headers") + self.ssl_context = ssl_context + + if auth is not None: + username = enforce_bytes(auth[0], name="auth") + password = enforce_bytes(auth[1], name="auth") + userpass = username + b":" + password + authorization = b"Basic " + base64.b64encode(userpass) + self.auth: tuple[bytes, bytes] | None = (username, password) + self.headers = [(b"Proxy-Authorization", authorization)] + self.headers + else: + self.auth = None diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/_ssl.py b/data/miniconda3/lib/python3.13/site-packages/httpcore/_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..c99c5a67945b8a3a3544d481e979c791ab45fe23 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore/_ssl.py @@ -0,0 +1,9 @@ +import ssl + +import certifi + + +def default_ssl_context() -> ssl.SSLContext: + context = ssl.create_default_context() + context.load_verify_locations(certifi.where()) + return context diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/_synchronization.py b/data/miniconda3/lib/python3.13/site-packages/httpcore/_synchronization.py new file mode 100644 index 0000000000000000000000000000000000000000..2ecc9e9c363e2f16c4f934cf41cf871826d6a495 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore/_synchronization.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +import threading +import types + +from ._exceptions import ExceptionMapping, PoolTimeout, map_exceptions + +# Our async synchronization primatives use either 'anyio' or 'trio' depending +# on if they're running under asyncio or trio. + +try: + import trio +except (ImportError, NotImplementedError): # pragma: nocover + trio = None # type: ignore + +try: + import anyio +except ImportError: # pragma: nocover + anyio = None # type: ignore + + +def current_async_library() -> str: + # Determine if we're running under trio or asyncio. + # See https://sniffio.readthedocs.io/en/latest/ + try: + import sniffio + except ImportError: # pragma: nocover + environment = "asyncio" + else: + environment = sniffio.current_async_library() + + if environment not in ("asyncio", "trio"): # pragma: nocover + raise RuntimeError("Running under an unsupported async environment.") + + if environment == "asyncio" and anyio is None: # pragma: nocover + raise RuntimeError( + "Running with asyncio requires installation of 'httpcore[asyncio]'." + ) + + if environment == "trio" and trio is None: # pragma: nocover + raise RuntimeError( + "Running with trio requires installation of 'httpcore[trio]'." + ) + + return environment + + +class AsyncLock: + """ + This is a standard lock. + + In the sync case `Lock` provides thread locking. + In the async case `AsyncLock` provides async locking. + """ + + def __init__(self) -> None: + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a lock with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_lock = trio.Lock() + elif self._backend == "asyncio": + self._anyio_lock = anyio.Lock() + + async def __aenter__(self) -> AsyncLock: + if not self._backend: + self.setup() + + if self._backend == "trio": + await self._trio_lock.acquire() + elif self._backend == "asyncio": + await self._anyio_lock.acquire() + + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self._backend == "trio": + self._trio_lock.release() + elif self._backend == "asyncio": + self._anyio_lock.release() + + +class AsyncThreadLock: + """ + This is a threading-only lock for no-I/O contexts. + + In the sync case `ThreadLock` provides thread locking. + In the async case `AsyncThreadLock` is a no-op. + """ + + def __enter__(self) -> AsyncThreadLock: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + pass + + +class AsyncEvent: + def __init__(self) -> None: + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a lock with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_event = trio.Event() + elif self._backend == "asyncio": + self._anyio_event = anyio.Event() + + def set(self) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + self._trio_event.set() + elif self._backend == "asyncio": + self._anyio_event.set() + + async def wait(self, timeout: float | None = None) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + trio_exc_map: ExceptionMapping = {trio.TooSlowError: PoolTimeout} + timeout_or_inf = float("inf") if timeout is None else timeout + with map_exceptions(trio_exc_map): + with trio.fail_after(timeout_or_inf): + await self._trio_event.wait() + elif self._backend == "asyncio": + anyio_exc_map: ExceptionMapping = {TimeoutError: PoolTimeout} + with map_exceptions(anyio_exc_map): + with anyio.fail_after(timeout): + await self._anyio_event.wait() + + +class AsyncSemaphore: + def __init__(self, bound: int) -> None: + self._bound = bound + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a semaphore with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_semaphore = trio.Semaphore( + initial_value=self._bound, max_value=self._bound + ) + elif self._backend == "asyncio": + self._anyio_semaphore = anyio.Semaphore( + initial_value=self._bound, max_value=self._bound + ) + + async def acquire(self) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + await self._trio_semaphore.acquire() + elif self._backend == "asyncio": + await self._anyio_semaphore.acquire() + + async def release(self) -> None: + if self._backend == "trio": + self._trio_semaphore.release() + elif self._backend == "asyncio": + self._anyio_semaphore.release() + + +class AsyncShieldCancellation: + # For certain portions of our codebase where we're dealing with + # closing connections during exception handling we want to shield + # the operation from being cancelled. + # + # with AsyncShieldCancellation(): + # ... # clean-up operations, shielded from cancellation. + + def __init__(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a shielded scope with the correct implementation. + """ + self._backend = current_async_library() + + if self._backend == "trio": + self._trio_shield = trio.CancelScope(shield=True) + elif self._backend == "asyncio": + self._anyio_shield = anyio.CancelScope(shield=True) + + def __enter__(self) -> AsyncShieldCancellation: + if self._backend == "trio": + self._trio_shield.__enter__() + elif self._backend == "asyncio": + self._anyio_shield.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self._backend == "trio": + self._trio_shield.__exit__(exc_type, exc_value, traceback) + elif self._backend == "asyncio": + self._anyio_shield.__exit__(exc_type, exc_value, traceback) + + +# Our thread-based synchronization primitives... + + +class Lock: + """ + This is a standard lock. + + In the sync case `Lock` provides thread locking. + In the async case `AsyncLock` provides async locking. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> Lock: + self._lock.acquire() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self._lock.release() + + +class ThreadLock: + """ + This is a threading-only lock for no-I/O contexts. + + In the sync case `ThreadLock` provides thread locking. + In the async case `AsyncThreadLock` is a no-op. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> ThreadLock: + self._lock.acquire() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self._lock.release() + + +class Event: + def __init__(self) -> None: + self._event = threading.Event() + + def set(self) -> None: + self._event.set() + + def wait(self, timeout: float | None = None) -> None: + if timeout == float("inf"): # pragma: no cover + timeout = None + if not self._event.wait(timeout=timeout): + raise PoolTimeout() # pragma: nocover + + +class Semaphore: + def __init__(self, bound: int) -> None: + self._semaphore = threading.Semaphore(value=bound) + + def acquire(self) -> None: + self._semaphore.acquire() + + def release(self) -> None: + self._semaphore.release() + + +class ShieldCancellation: + # Thread-synchronous codebases don't support cancellation semantics. + # We have this class because we need to mirror the async and sync + # cases within our package, but it's just a no-op. + def __enter__(self) -> ShieldCancellation: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/_trace.py b/data/miniconda3/lib/python3.13/site-packages/httpcore/_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1cd7c47829ce17dbcf651ab56b4ffdce04a485 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore/_trace.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import inspect +import logging +import types +import typing + +from ._models import Request + + +class Trace: + def __init__( + self, + name: str, + logger: logging.Logger, + request: Request | None = None, + kwargs: dict[str, typing.Any] | None = None, + ) -> None: + self.name = name + self.logger = logger + self.trace_extension = ( + None if request is None else request.extensions.get("trace") + ) + self.debug = self.logger.isEnabledFor(logging.DEBUG) + self.kwargs = kwargs or {} + self.return_value: typing.Any = None + self.should_trace = self.debug or self.trace_extension is not None + self.prefix = self.logger.name.split(".")[-1] + + def trace(self, name: str, info: dict[str, typing.Any]) -> None: + if self.trace_extension is not None: + prefix_and_name = f"{self.prefix}.{name}" + ret = self.trace_extension(prefix_and_name, info) + if inspect.iscoroutine(ret): # pragma: no cover + raise TypeError( + "If you are using a synchronous interface, " + "the callback of the `trace` extension should " + "be a normal function instead of an asynchronous function." + ) + + if self.debug: + if not info or "return_value" in info and info["return_value"] is None: + message = name + else: + args = " ".join([f"{key}={value!r}" for key, value in info.items()]) + message = f"{name} {args}" + self.logger.debug(message) + + def __enter__(self) -> Trace: + if self.should_trace: + info = self.kwargs + self.trace(f"{self.name}.started", info) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self.should_trace: + if exc_value is None: + info = {"return_value": self.return_value} + self.trace(f"{self.name}.complete", info) + else: + info = {"exception": exc_value} + self.trace(f"{self.name}.failed", info) + + async def atrace(self, name: str, info: dict[str, typing.Any]) -> None: + if self.trace_extension is not None: + prefix_and_name = f"{self.prefix}.{name}" + coro = self.trace_extension(prefix_and_name, info) + if not inspect.iscoroutine(coro): # pragma: no cover + raise TypeError( + "If you're using an asynchronous interface, " + "the callback of the `trace` extension should " + "be an asynchronous function rather than a normal function." + ) + await coro + + if self.debug: + if not info or "return_value" in info and info["return_value"] is None: + message = name + else: + args = " ".join([f"{key}={value!r}" for key, value in info.items()]) + message = f"{name} {args}" + self.logger.debug(message) + + async def __aenter__(self) -> Trace: + if self.should_trace: + info = self.kwargs + await self.atrace(f"{self.name}.started", info) + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self.should_trace: + if exc_value is None: + info = {"return_value": self.return_value} + await self.atrace(f"{self.name}.complete", info) + else: + info = {"exception": exc_value} + await self.atrace(f"{self.name}.failed", info) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/_utils.py b/data/miniconda3/lib/python3.13/site-packages/httpcore/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c44ff93cb2f572afc6e679308024b744b65c3b0a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpcore/_utils.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import select +import socket +import sys + + +def is_socket_readable(sock: socket.socket | None) -> bool: + """ + Return whether a socket, as identifed by its file descriptor, is readable. + "A socket is readable" means that the read buffer isn't empty, i.e. that calling + .recv() on it would immediately return some data. + """ + # NOTE: we want check for readability without actually attempting to read, because + # we don't want to block forever if it's not readable. + + # In the case that the socket no longer exists, or cannot return a file + # descriptor, we treat it as being readable, as if it the next read operation + # on it is ready to return the terminating `b""`. + sock_fd = None if sock is None else sock.fileno() + if sock_fd is None or sock_fd < 0: # pragma: nocover + return True + + # The implementation below was stolen from: + # https://github.com/python-trio/trio/blob/20ee2b1b7376db637435d80e266212a35837ddcc/trio/_socket.py#L471-L478 + # See also: https://github.com/encode/httpcore/pull/193#issuecomment-703129316 + + # Use select.select on Windows, and when poll is unavailable and select.poll + # everywhere else. (E.g. When eventlet is in use. See #327) + if ( + sys.platform == "win32" or getattr(select, "poll", None) is None + ): # pragma: nocover + rready, _, _ = select.select([sock_fd], [], [], 0) + return bool(rready) + p = select.poll() + p.register(sock_fd, select.POLLIN) + return bool(p.poll(0)) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpcore/py.typed b/data/miniconda3/lib/python3.13/site-packages/httpcore/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b0d2b196385e98259971519793447c1fd7a9a643 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/METADATA @@ -0,0 +1,203 @@ +Metadata-Version: 2.3 +Name: httpx +Version: 0.28.1 +Summary: The next generation HTTP client. +Project-URL: Changelog, https://github.com/encode/httpx/blob/master/CHANGELOG.md +Project-URL: Documentation, https://www.python-httpx.org +Project-URL: Homepage, https://github.com/encode/httpx +Project-URL: Source, https://github.com/encode/httpx +Author-email: Tom Christie +License: BSD-3-Clause +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: Trio +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Requires-Dist: anyio +Requires-Dist: certifi +Requires-Dist: httpcore==1.* +Requires-Dist: idna +Provides-Extra: brotli +Requires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli' +Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli' +Provides-Extra: cli +Requires-Dist: click==8.*; extra == 'cli' +Requires-Dist: pygments==2.*; extra == 'cli' +Requires-Dist: rich<14,>=10; extra == 'cli' +Provides-Extra: http2 +Requires-Dist: h2<5,>=3; extra == 'http2' +Provides-Extra: socks +Requires-Dist: socksio==1.*; extra == 'socks' +Provides-Extra: zstd +Requires-Dist: zstandard>=0.18.0; extra == 'zstd' +Description-Content-Type: text/markdown + +

+ HTTPX +

+ +

HTTPX - A next-generation HTTP client for Python.

+ +

+ + Test Suite + + + Package version + +

+ +HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**. + +--- + +Install HTTPX using pip: + +```shell +$ pip install httpx +``` + +Now, let's get started: + +```pycon +>>> import httpx +>>> r = httpx.get('https://www.example.org/') +>>> r + +>>> r.status_code +200 +>>> r.headers['content-type'] +'text/html; charset=UTF-8' +>>> r.text +'\n\n\nExample Domain...' +``` + +Or, using the command-line client. + +```shell +$ pip install 'httpx[cli]' # The command line client is an optional dependency. +``` + +Which now allows us to use HTTPX directly from the command-line... + +

+ httpx --help +

+ +Sending a request... + +

+ httpx http://httpbin.org/json +

+ +## Features + +HTTPX builds on the well-established usability of `requests`, and gives you: + +* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/). +* An integrated command-line client. +* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/). +* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/). +* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/transports/#wsgi-transport) or [ASGI applications](https://www.python-httpx.org/advanced/transports/#asgi-transport). +* Strict timeouts everywhere. +* Fully type annotated. +* 100% test coverage. + +Plus all the standard features of `requests`... + +* International Domains and URLs +* Keep-Alive & Connection Pooling +* Sessions with Cookie Persistence +* Browser-style SSL Verification +* Basic/Digest Authentication +* Elegant Key/Value Cookies +* Automatic Decompression +* Automatic Content Decoding +* Unicode Response Bodies +* Multipart File Uploads +* HTTP(S) Proxy Support +* Connection Timeouts +* Streaming Downloads +* .netrc Support +* Chunked Requests + +## Installation + +Install with pip: + +```shell +$ pip install httpx +``` + +Or, to include the optional HTTP/2 support, use: + +```shell +$ pip install httpx[http2] +``` + +HTTPX requires Python 3.8+. + +## Documentation + +Project documentation is available at [https://www.python-httpx.org/](https://www.python-httpx.org/). + +For a run-through of all the basics, head over to the [QuickStart](https://www.python-httpx.org/quickstart/). + +For more advanced topics, see the [Advanced Usage](https://www.python-httpx.org/advanced/) section, the [async support](https://www.python-httpx.org/async/) section, or the [HTTP/2](https://www.python-httpx.org/http2/) section. + +The [Developer Interface](https://www.python-httpx.org/api/) provides a comprehensive API reference. + +To find out about tools that integrate with HTTPX, see [Third Party Packages](https://www.python-httpx.org/third_party_packages/). + +## Contribute + +If you want to contribute with HTTPX check out the [Contributing Guide](https://www.python-httpx.org/contributing/) to learn how to start. + +## Dependencies + +The HTTPX project relies on these excellent libraries: + +* `httpcore` - The underlying transport implementation for `httpx`. + * `h11` - HTTP/1.1 support. +* `certifi` - SSL certificates. +* `idna` - Internationalized domain name support. +* `sniffio` - Async library autodetection. + +As well as these optional installs: + +* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)* +* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)* +* `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)* +* `click` - Command line client support. *(Optional, with `httpx[cli]`)* +* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)* +* `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)* + +A huge amount of credit is due to `requests` for the API layout that +much of this work follows, as well as to `urllib3` for plenty of design +inspiration around the lower-level networking details. + +--- + +

HTTPX is BSD licensed code.
Designed & crafted with care.

— 🦋 —

+ +## Release Information + +### Fixed + +* Reintroduced supposedly-private `URLTypes` shortcut. (#2673) + + +--- + +[Full changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a8b1f387980915445490496155d1dbe498f6acbd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/RECORD @@ -0,0 +1,54 @@ +../../../bin/httpx,sha256=KJhgQ0gT0v88_dNQKz1HETwOnFAtXqYfSaMcJDmb7K0,201 +httpx-0.28.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpx-0.28.1.dist-info/METADATA,sha256=_rubD48-gNV8gZnDBPNcQzboWB0dGNeYPJJ2a4J5OyU,7052 +httpx-0.28.1.dist-info/RECORD,, +httpx-0.28.1.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87 +httpx-0.28.1.dist-info/entry_points.txt,sha256=2lVkdQmxLA1pNMgSN2eV89o90HCZezhmNwsy6ryKDSA,37 +httpx-0.28.1.dist-info/licenses/LICENSE.md,sha256=TsWdVE8StfU5o6cW_TIaxYzNgDC0ZSIfLIgCAM3yjY0,1508 +httpx/__init__.py,sha256=CsaZe6yZj0rHg6322AWKWHGTMVr9txgEfD5P3_Rrz60,2171 +httpx/__pycache__/__init__.cpython-313.pyc,, +httpx/__pycache__/__version__.cpython-313.pyc,, +httpx/__pycache__/_api.cpython-313.pyc,, +httpx/__pycache__/_auth.cpython-313.pyc,, +httpx/__pycache__/_client.cpython-313.pyc,, +httpx/__pycache__/_config.cpython-313.pyc,, +httpx/__pycache__/_content.cpython-313.pyc,, +httpx/__pycache__/_decoders.cpython-313.pyc,, +httpx/__pycache__/_exceptions.cpython-313.pyc,, +httpx/__pycache__/_main.cpython-313.pyc,, +httpx/__pycache__/_models.cpython-313.pyc,, +httpx/__pycache__/_multipart.cpython-313.pyc,, +httpx/__pycache__/_status_codes.cpython-313.pyc,, +httpx/__pycache__/_types.cpython-313.pyc,, +httpx/__pycache__/_urlparse.cpython-313.pyc,, +httpx/__pycache__/_urls.cpython-313.pyc,, +httpx/__pycache__/_utils.cpython-313.pyc,, +httpx/__version__.py,sha256=LoUyYeOXTieGzuP_64UL0wxdtxjuu_QbOvE7NOg-IqU,108 +httpx/_api.py,sha256=r_Zgs4jIpcPJLqK5dbbSayqo_iVMKFaxZCd-oOHxLEs,11743 +httpx/_auth.py,sha256=Yr3QwaUSK17rGYx-7j-FdicFIzz4Y9FFV-1F4-7RXX4,11891 +httpx/_client.py,sha256=xD-UG67-WMkeltAAOeGGj-cZ2RRTAm19sWRxlFY7_40,65714 +httpx/_config.py,sha256=pPp2U-wicfcKsF-KYRE1LYdt3e6ERGeIoXZ8Gjo3LWc,8547 +httpx/_content.py,sha256=LGGzrJTR3OvN4Mb1GVVNLXkXJH-6oKlwAttO9p5w_yg,8161 +httpx/_decoders.py,sha256=p0dX8I0NEHexs3UGp4SsZutiMhsXrrWl6-GnqVb0iKM,12041 +httpx/_exceptions.py,sha256=bxW7fxzgVMAdNTbwT0Vnq04gJDW1_gI_GFiQPuMyjL0,8527 +httpx/_main.py,sha256=Cg9GMabiTT_swaDfUgIRitSwxLRMSwUDOm7LdSGqlA4,15626 +httpx/_models.py,sha256=4__Guyv1gLxuZChwim8kfQNiIOcJ9acreFOSurvZfms,44700 +httpx/_multipart.py,sha256=KOHEZZl6oohg9mPaKyyu345qq1rJLg35TUG3YAzXB3Y,9843 +httpx/_status_codes.py,sha256=DYn-2ufBgMeXy5s8x3_TB7wjAuAAMewTakPrm5rXEsc,5639 +httpx/_transports/__init__.py,sha256=GbUoBSAOp7z-l-9j5YhMhR3DMIcn6FVLhj072O3Nnno,275 +httpx/_transports/__pycache__/__init__.cpython-313.pyc,, +httpx/_transports/__pycache__/asgi.cpython-313.pyc,, +httpx/_transports/__pycache__/base.cpython-313.pyc,, +httpx/_transports/__pycache__/default.cpython-313.pyc,, +httpx/_transports/__pycache__/mock.cpython-313.pyc,, +httpx/_transports/__pycache__/wsgi.cpython-313.pyc,, +httpx/_transports/asgi.py,sha256=HRfiDYMPt4wQH2gFgHZg4c-i3sblo6bL5GTqcET-xz8,5501 +httpx/_transports/base.py,sha256=kZS_VMbViYfF570pogUCJ1bulz-ybfL51Pqs9yktebU,2523 +httpx/_transports/default.py,sha256=AzeaRUyVwCccTyyNJexDf0n1dFfzzydpdIQgvw7PLnk,13983 +httpx/_transports/mock.py,sha256=PTo0d567RITXxGrki6kN7_67wwAxfwiMDcuXJiZCjEo,1232 +httpx/_transports/wsgi.py,sha256=NcPX3Xap_EwCFZWO_OaSyQNuInCYx1QMNbO8GAei6jY,4825 +httpx/_types.py,sha256=Jyh41GQq7AOev8IOWKDAg7zCbvHAfufmW5g_PiTtErY,2965 +httpx/_urlparse.py,sha256=ZAmH47ONfkxrrj-PPYhGeiHjb6AjKCS-ANWIN4OL_KY,18546 +httpx/_urls.py,sha256=dX99VR1DSOHpgo9Aq7PzYO4FKdxqKjwyNp8grf8dHN0,21550 +httpx/_utils.py,sha256=_TVeqAKvxJkKHdz7dFeb4s0LZqQXgeFkXSgfiHBK_1o,8285 +httpx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..21aaa72961a8af71c17d2cb3b76d5f7f567100e4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.26.3 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ae96007f7d725813fd02dc1d06d3834ee1939e4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx-0.28.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +httpx = httpx:main diff --git a/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..7a4a4b7a7e9adbe4542d98f6b2f40e65ee64b182 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/METADATA @@ -0,0 +1,209 @@ +Metadata-Version: 2.4 +Name: idna +Version: 3.11 +Summary: Internationalized Domain Names in Applications (IDNA) +Author-email: Kim Davies +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: Name Service (DNS) +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Utilities +License-File: LICENSE.md +Requires-Dist: ruff >= 0.6.2 ; extra == "all" +Requires-Dist: mypy >= 1.11.2 ; extra == "all" +Requires-Dist: pytest >= 8.3.2 ; extra == "all" +Requires-Dist: flake8 >= 7.1.1 ; extra == "all" +Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.rst +Project-URL: Issue tracker, https://github.com/kjd/idna/issues +Project-URL: Source, https://github.com/kjd/idna +Provides-Extra: all + +Internationalized Domain Names in Applications (IDNA) +===================================================== + +Support for `Internationalized Domain Names in +Applications (IDNA) `_ +and `Unicode IDNA Compatibility Processing +`_. + +The latest versions of these standards supplied here provide +more comprehensive language coverage and reduce the potential of +allowing domains with known security vulnerabilities. This library +is a suitable replacement for the “encodings.idna” +module that comes with the Python standard library, but which +only supports an older superseded IDNA specification from 2003. + +Basic functions are simply executed: + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('ドメイン.テスト') + b'xn--eckwd4c7c.xn--zckzah' + >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) + ドメイン.テスト + + +Installation +------------ + +This package is available for installation from PyPI via the +typical mechanisms, such as: + +.. code-block:: bash + + $ python3 -m pip install idna + + +Usage +----- + +For typical usage, the ``encode`` and ``decode`` functions will take a +domain name argument and perform a conversion to ASCII compatible encoding +(known as A-labels), or to Unicode strings (known as U-labels) +respectively. + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('ドメイン.テスト') + b'xn--eckwd4c7c.xn--zckzah' + >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) + ドメイン.テスト + +Conversions can be applied at a per-label basis using the ``ulabel`` or +``alabel`` functions if necessary: + +.. code-block:: pycon + + >>> idna.alabel('测试') + b'xn--0zwm56d' + + +Compatibility Mapping (UTS #46) ++++++++++++++++++++++++++++++++ + +This library provides support for `Unicode IDNA Compatibility +Processing `_ which normalizes input from +different potential ways a user may input a domain prior to performing the IDNA +conversion operations. This functionality, known as a +`mapping `_, is considered by the +specification to be a local user-interface issue distinct from IDNA +conversion functionality. + +For example, “Königsgäßchen” is not a permissible label as *LATIN +CAPITAL LETTER K* is not allowed (nor are capital letters in general). +UTS 46 will convert this into lower case prior to applying the IDNA +conversion. + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('Königsgäßchen') + ... + idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed + >>> idna.encode('Königsgäßchen', uts46=True) + b'xn--knigsgchen-b4a3dun' + >>> print(idna.decode('xn--knigsgchen-b4a3dun')) + königsgäßchen + + +Exceptions +---------- + +All errors raised during the conversion following the specification +should raise an exception derived from the ``idna.IDNAError`` base +class. + +More specific exceptions that may be generated as ``idna.IDNABidiError`` +when the error reflects an illegal combination of left-to-right and +right-to-left characters in a label; ``idna.InvalidCodepoint`` when +a specific codepoint is an illegal character in an IDN label (i.e. +INVALID); and ``idna.InvalidCodepointContext`` when the codepoint is +illegal based on its position in the string (i.e. it is CONTEXTO or CONTEXTJ +but the contextual requirements are not satisfied.) + +Building and Diagnostics +------------------------ + +The IDNA and UTS 46 functionality relies upon pre-calculated lookup +tables for performance. These tables are derived from computing against +eligibility criteria in the respective standards using the command-line +script ``tools/idna-data``. + +This tool will fetch relevant codepoint data from the Unicode repository +and perform the required calculations to identify eligibility. There are +three main modes: + +* ``idna-data make-libdata``. Generates ``idnadata.py`` and + ``uts46data.py``, the pre-calculated lookup tables used for IDNA and + UTS 46 conversions. Implementers who wish to track this library against + a different Unicode version may use this tool to manually generate a + different version of the ``idnadata.py`` and ``uts46data.py`` files. + +* ``idna-data make-table``. Generate a table of the IDNA disposition + (e.g. PVALID, CONTEXTJ, CONTEXTO) in the format found in Appendix + B.1 of RFC 5892 and the pre-computed tables published by `IANA + `_. + +* ``idna-data U+0061``. Prints debugging output on the various + properties associated with an individual Unicode codepoint (in this + case, U+0061), that are used to assess the IDNA and UTS 46 status of a + codepoint. This is helpful in debugging or analysis. + +The tool accepts a number of arguments, described using ``idna-data +-h``. Most notably, the ``--version`` argument allows the specification +of the version of Unicode to be used in computing the table data. For +example, ``idna-data --version 9.0.0 make-libdata`` will generate +library data against Unicode 9.0.0. + + +Additional Notes +---------------- + +* **Packages**. The latest tagged release version is published in the + `Python Package Index `_. + +* **Version support**. This library supports Python 3.8 and higher. + As this library serves as a low-level toolkit for a variety of + applications, many of which strive for broad compatibility with older + Python versions, there is no rush to remove older interpreter support. + Support for older versions are likely to be removed from new releases + as automated tests can no longer easily be run, i.e. once the Python + version is officially end-of-life. + +* **Testing**. The library has a test suite based on each rule of the + IDNA specification, as well as tests that are provided as part of the + Unicode Technical Standard 46, `Unicode IDNA Compatibility Processing + `_. + +* **Emoji**. It is an occasional request to support emoji domains in + this library. Encoding of symbols like emoji is expressly prohibited by + the technical standard IDNA 2008 and emoji domains are broadly phased + out across the domain industry due to associated security risks. For + now, applications that need to support these non-compliant labels + may wish to consider trying the encode/decode operation in this library + first, and then falling back to using `encodings.idna`. See `the Github + project `_ for more discussion. + +* **Transitional processing**. Unicode 16.0.0 removed transitional + processing so the `transitional` argument for the encode() method + no longer has any effect and will be removed at a later date. + diff --git a/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..2d0cc65d9b4f8e71abc4547a0e92cf0b1f7077b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/RECORD @@ -0,0 +1,24 @@ +idna-3.11.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +idna-3.11.dist-info/METADATA,sha256=fCwSww9SuiN8TIHllFSASUQCW55hAs8dzKnr9RaEEbA,8378 +idna-3.11.dist-info/RECORD,, +idna-3.11.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +idna-3.11.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +idna-3.11.dist-info/direct_url.json,sha256=wIhSgGUY4bpIgKvFAcvs9P2KdzWpOCQSVkGWrMfEmT0,94 +idna-3.11.dist-info/licenses/LICENSE.md,sha256=t6M2q_OwThgOwGXN0W5wXQeeHMehT5EKpukYfza5zYc,1541 +idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868 +idna/__pycache__/__init__.cpython-313.pyc,, +idna/__pycache__/codec.cpython-313.pyc,, +idna/__pycache__/compat.cpython-313.pyc,, +idna/__pycache__/core.cpython-313.pyc,, +idna/__pycache__/idnadata.cpython-313.pyc,, +idna/__pycache__/intranges.cpython-313.pyc,, +idna/__pycache__/package_data.cpython-313.pyc,, +idna/__pycache__/uts46data.cpython-313.pyc,, +idna/codec.py,sha256=M2SGWN7cs_6B32QmKTyTN6xQGZeYQgQ2wiX3_DR6loE,3438 +idna/compat.py,sha256=RzLy6QQCdl9784aFhb2EX9EKGCJjg0P3PilGdeXXcx8,316 +idna/core.py,sha256=P26_XVycuMTZ1R2mNK1ZREVzM5mvTzdabBXfyZVU1Lc,13246 +idna/idnadata.py,sha256=SG8jhaGE53iiD6B49pt2pwTv_UvClciWE-N54oR2p4U,79623 +idna/intranges.py,sha256=amUtkdhYcQG8Zr-CoMM_kVRacxkivC1WgxN1b63KKdU,1898 +idna/package_data.py,sha256=_CUavOxobnbyNG2FLyHoN8QHP3QM9W1tKuw7eq9QwBk,21 +idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +idna/uts46data.py,sha256=H9J35VkD0F9L9mKOqjeNGd2A-Va6FlPoz6Jz4K7h-ps,243725 diff --git a/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..24bd475e9d592789258195d1f13f222a130d9674 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/idna-3.11.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176191175488988/conda-bld/idna_1761911981595/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b5445db16437dde0bd43d892483ed2df101f7d2d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/METADATA @@ -0,0 +1,105 @@ +Metadata-Version: 2.4 +Name: ifcopenshell +Version: 0.8.4 +Summary: Python bindings, utility functions, and high-level API for IfcOpenShell +Author-email: Dion Moult +Project-URL: Homepage, http://ifcopenshell.org +Project-URL: Bug Tracker, https://github.com/ifcopenshell/ifcopenshell/issues +Classifier: Programming Language :: Python :: 3 +Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+) +Requires-Python: <3.15,>=3.9 +Description-Content-Type: text/markdown +Requires-Dist: shapely +Requires-Dist: numpy +Requires-Dist: isodate +Requires-Dist: python-dateutil +Requires-Dist: lark +Requires-Dist: typing-extensions +Provides-Extra: advanced +Requires-Dist: networkx; extra == "advanced" +Provides-Extra: dev +Requires-Dist: pytest; extra == "dev" +Requires-Dist: tabulate; extra == "dev" + + +IfcOpenShell +============ + +

+ +

+ + +IfcOpenShell is an open source ([LGPL]) software library for working with Industry Foundation Classes ([IFC]). Complete +parsing support is provided for [IFC2x3 TC1], [IFC4 Add2 TC1], IFC4x1, IFC4x2, and [IFC4x3 Add2]. Extensive geometric support +is implemented for the IFC releases [IFC2x3 TC1] and [IFC4 Add2 TC1]. Extending with support for arbitrary IFC schemas +is possible at compile-time when using C++ and at run-time when using Python. + +In addition to a C++ and Python API, IfcOpenShell comes with an ecosystem of tools, notably including IfcConvert (an application +to convert IFC models to other formats), Bonsai (an add-on to Blender providing a graphical IFC authoring platform), +and many other libraries, CLI apps, and more. Support is also provided for auxiliary standards such as BCF and IDS. + +For more information, see: + +* [IfcOpenShell Website](http://ifcopenshell.org) +* [IfcOpenShell Documentation](https://docs.ifcopenshell.org) + * [IfcOpenShell C++ Installation](https://docs.ifcopenshell.org/ifcopenshell/installation.html) + * [IfcOpenShell Python Installation](https://docs.ifcopenshell.org/ifcopenshell-python/installation.html) + * [IfcOpenShell Python Hello World Tutorial](https://docs.ifcopenshell.org/ifcopenshell-python/hello_world.html) +* [Bonsai Website](https://bonsaibim.org) +* [Bonsai Documentation](https://docs.bonsaibim.org/index.html) + * [Add-on Installation](https://docs.bonsaibim.org/quickstart/installation.html) + * [Exploring an IFC model](https://docs.bonsaibim.org/quickstart/explore_model.html) + +Development is sponsored through your generous donations! + +[![Open Collective Contributors](https://img.shields.io/opencollective/all/opensourcebim?label=Sponsors&color=22ce5f)](https://opencollective.com/opensourcebim/) + +Contents +-------- + +| Name | Description | License | Service | +| ------------------------- | --------------------------------------------------------------------- | ------------------- | ------- | +| [bcf](https://docs.ifcopenshell.org/bcf.html) | Library to read and write BCF-XML and query OpenCDE BCF-API modules | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/bcf-client?label=PyPI&color=006dad)](https://pypi.org/project/bcf-client/) [![Anaconda-Server Badge](https://anaconda.org/conda-forge/bcf-client/badges/version.svg)](https://anaconda.org/conda-forge/bcf-client) | +| [bonsai](https://docs.ifcopenshell.org/bonsai.html) | Add-on to Blender providing a graphical native IFC authoring platform | GPL-3.0-or-later | [![Official](https://img.shields.io/badge/BonsaiBIM.org-Download-70ba35)](https://bonsaibim.org/download.html) [![GitHub Unstable](https://img.shields.io/github/v/release/ifcopenshell/ifcopenshell?filter=bonsai-*&label=GitHub-Unstable&color=f6f8fa)](https://github.com/IfcOpenShell/IfcOpenShell/releases?q=bonsai&expanded=true) [![Chocolatey](https://img.shields.io/chocolatey/v/blenderbim-nightly?label=Chocolatey&color=5c9fd8)](https://community.chocolatey.org/packages/blenderbim-nightly/) | +| [bsdd](https://docs.ifcopenshell.org/bsdd.html) | Library to query the bSDD API | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/bsdd?label=PyPI&color=006dad)](https://pypi.org/project/bsdd/) | +| [ifc2ca](https://docs.ifcopenshell.org/ifc2ca.html) | Utility to convert IFC structural analysis models to Code_Aster | LGPL-3.0-or-later | +| [ifc4d](https://docs.ifcopenshell.org/ifc4d.html) | Convert to and from IFC and project management software | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifc4d?label=PyPI&color=006dad)](https://pypi.org/project/ifc4d/) | +| [ifc5d](https://docs.ifcopenshell.org/ifc5d.html) | Report and optimise cost information from IFC | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifc5d?label=PyPI&color=006dad)](https://pypi.org/project/ifc5d/) | +| [ifcbimtester](https://docs.ifcopenshell.org/bimtester.html) | Wrapper for Gherkin based unit testing for IFC models | LGPL-3.0-or-later | +| ifcblender | Historic Blender IFC import add-on | LGPL-3.0-or-later\* | +| [ifccityjson](https://docs.ifcopenshell.org/ifccityjson.html) | Convert CityJSON to IFC | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifccityjson?label=PyPI&color=006dad)](https://pypi.org/project/ifccityjson/) | +| [ifcclash](https://docs.ifcopenshell.org/ifcclash.html) | Clash detection library and CLI app | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifcclash?label=PyPI&color=006dad)](https://pypi.org/project/ifcclash/) | +| [ifcconvert](https://docs.ifcopenshell.org/ifcconvert.html) | CLI app to convert IFC to many other formats | LGPL-3.0-or-later\* | [![Official](https://img.shields.io/badge/IfcOpenShell.org-Download-70ba35)](https://docs.ifcopenshell.org/ifcconvert/installation.html) [![GitHub](https://img.shields.io/github/v/release/ifcopenshell/ifcopenshell?filter=ifcconvert-*&label=GitHub&color=f6f8fa)](https://github.com/IfcOpenShell/IfcOpenShell/releases?q=ifcconvert&expanded=true) +| [ifccsv](https://docs.ifcopenshell.org/ifccsv.html) | Library and CLI app to export and import schedules from IFC | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifccsv?label=PyPI&color=006dad)](https://pypi.org/project/ifccsv/) | +| [ifcdiff](https://docs.ifcopenshell.org/ifcdiff.html) | Compare changes between IFC models | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifcdiff?label=PyPI&color=006dad)](https://pypi.org/project/ifcdiff/) | +| [ifcfm](https://docs.ifcopenshell.org/ifcfm.html) | Extract IFC data for FM handover requirements | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifcfm?label=PyPI&color=006dad)](https://pypi.org/project/ifcfm/) | +| [ifcmax](https://docs.ifcopenshell.org/ifcmax.html) | Historic extension for IFC support in 3DS Max | LGPL-3.0-or-later\* | [![Official](https://img.shields.io/badge/IfcOpenShell.org-Download-70ba35)](https://docs.ifcopenshell.org/ifcmax.html) +| [ifcopenshell-python](https://docs.ifcopenshell.org/ifcopenshell-python.html) | Python library for IFC manipulation | LGPL-3.0-or-later\* | [![Official](https://img.shields.io/badge/IfcOpenShell.org-Download-70ba35)](https://docs.ifcopenshell.org/ifcopenshell-python/installation.html) [![GitHub](https://img.shields.io/github/v/release/ifcopenshell/ifcopenshell?filter=ifcopenshell-python-*&label=GitHub&color=f6f8fa)](https://github.com/IfcOpenShell/IfcOpenShell/releases?q=ifcopenshell-python&expanded=true) [![PyPI](https://img.shields.io/pypi/v/ifcopenshell?label=PyPI&color=006dad)](https://pypi.org/project/ifcopenshell/) [![Anaconda](https://img.shields.io/conda/vn/conda-forge/ifcopenshell?label=Anaconda&color=43b02a)](https://anaconda.org/conda-forge/ifcopenshell) [![Anaconda](https://img.shields.io/conda/vn/ifcopenshell/ifcopenshell?label=Anaconda-Unstable&color=43b02a)](https://anaconda.org/ifcopenshell/ifcopenshell) [![Docker](https://img.shields.io/docker/pulls/aecgeeks/ifcopenshell?label=Docker&color=1D63ED)](https://hub.docker.com/r/aecgeeks/ifcopenshell) [![AUR](https://img.shields.io/aur/version/ifcopenshell?label=AUR&color=1793d1)](https://aur.archlinux.org/packages/ifcopenshell) [![AUR Unstable](https://img.shields.io/aur/version/ifcopenshell-git?label=AUR-Unstable&color=1793d1)](https://aur.archlinux.org/packages/ifcopenshell-git) [Pyodide WASM Wheels](https://github.com/IfcOpenShell/wasm-wheels#pyodide-test-wheels) | +| [ifcpatch](https://docs.ifcopenshell.org/ifcpatch.html) | Utility to run pre-packaged scripts to manipulate IFCs | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifcpatch?label=PyPI&color=006dad)](https://pypi.org/project/ifcpatch/) | +| [ifcsverchok](https://docs.ifcopenshell.org/ifcsverchok.html) | Blender Add-on for visual node programming with IFC | GPL-3.0-or-later | [![GitHub Unstable](https://img.shields.io/github/v/release/ifcopenshell/ifcopenshell?filter=ifcsverchok-*.*.*.*&label=GitHub-Unstable&color=f6f8fa)](https://github.com/IfcOpenShell/IfcOpenShell/releases?q=ifcsverchok&expanded=true) +| [ifctester](https://docs.ifcopenshell.org/ifctester.html) | Library, CLI and webapp for IDS model auditing | LGPL-3.0-or-later | [![PyPI](https://img.shields.io/pypi/v/ifctester?label=PyPI&color=006dad)](https://pypi.org/project/ifctester/) | + +The IfcOpenShell C++ codebase is split into multiple interal libraries: + +| Name | Description | License | +| ------------------------- | --------------------------------------------------------------------- | ------------------- | +| ifcgeom | Internal library for IfcOpenShell | LGPL-3.0-or-later\* | +| ifcgeom\_schema\_agnostic | Internal library for IfcOpenShell | LGPL-3.0-or-later\* | +| ifcgeomserver | Internal library for IfcOpenShell | LGPL-3.0-or-later\* | +| ifcjni | Internal library for IfcOpenShell | LGPL-3.0-or-later\* | +| ifcparse | Internal library for IfcOpenShell | LGPL-3.0-or-later\* | +| ifcwrap | Internal library for IfcOpenShell | LGPL-3.0-or-later\* | +| qtviewer | Internal library for IfcOpenShell | LGPL-3.0-or-later\* | +| serializers | Internal library for IfcOpenShell | LGPL-3.0-or-later\* | + +[LGPL]: https://github.com/IfcOpenShell/IfcOpenShell/tree/master/COPYING.LESSER "LGPL-3.0-or-later" +[IFC]: https://technical.buildingsmart.org/standards/ifc/ "IFC" +[IFC2x3 TC1]: https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/TC1/HTML/ "IFC2x3 TC1" +[IFC4 Add2 TC1]: https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2_TC1/HTML/ "IFC4 Add2 TC1" +[IFC4x3 Add2]: https://standards.buildingsmart.org/IFC/RELEASE/IFC4_3/ "IFC4x3 Add2" +[Visual Studio]: https://www.visualstudio.com/ "Visual Studio" +[Visual C++ Build Tools]: http://landinghub.visualstudio.com/visual-cpp-build-tools "Visual C++ Build Tools" +[MSYS2]: https://msys2.github.io/ "MSYS2" +[win/readme.md]: https://github.com/IfcOpenShell/IfcOpenShell/tree/master/win/readme.md "win/readme.md" +[nix/build-all.py]: https://github.com/IfcOpenShell/IfcOpenShell/tree/master/nix/build-all.py "nix/build-all.py" diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..86e4b3d9a67b8a6cb9d48d8cc03d9cde9bc1a4bb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/RECORD @@ -0,0 +1,1075 @@ +ifcopenshell-0.8.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ifcopenshell-0.8.4.dist-info/METADATA,sha256=hXd4J0qq7X3sY2EbcA6E8ouLF6M-hJrztG1u57E7ZGo,12296 +ifcopenshell-0.8.4.dist-info/RECORD,, +ifcopenshell-0.8.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ifcopenshell-0.8.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +ifcopenshell-0.8.4.dist-info/direct_url.json,sha256=1LacrmKN7ZgaqSjhgLOsB3-LgXRucHrD9AEb3Ozw1OQ,277 +ifcopenshell-0.8.4.dist-info/top_level.txt,sha256=XHZBq9xj7JVAek1MJfXMzG1-B0TZNOzguApbnlDH-IM,13 +ifcopenshell/__init__.py,sha256=WGZP8-iG1zEAobqRpdRSNjvHftf0Xz2pNk808NlTGhw,13610 +ifcopenshell/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/__pycache__/draw.cpython-313.pyc,, +ifcopenshell/__pycache__/entity_instance.cpython-313.pyc,, +ifcopenshell/__pycache__/file.cpython-313.pyc,, +ifcopenshell/__pycache__/guid.cpython-313.pyc,, +ifcopenshell/__pycache__/ifcopenshell_wrapper.cpython-313.pyc,, +ifcopenshell/__pycache__/settings.cpython-313.pyc,, +ifcopenshell/__pycache__/sql.cpython-313.pyc,, +ifcopenshell/__pycache__/stream.cpython-313.pyc,, +ifcopenshell/__pycache__/template.cpython-313.pyc,, +ifcopenshell/__pycache__/validate.cpython-313.pyc,, +ifcopenshell/_ifcopenshell_wrapper.cpython-313-x86_64-linux-gnu.so,sha256=RoJzxBrMrgD2-mDDWB1alKzyFmBjw6UiHocpdroxFtg,151708408 +ifcopenshell/api/__init__.py,sha256=BRGhjHyZpuahdIE538TuCn5GmRpiNAl2zs30IPcDmXo,12751 +ifcopenshell/api/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/aggregate/__init__.py,sha256=LG8rxG5RwDFZS-I6A0Zh-fEi4HCc9th9juhBOwb8rEI,1326 +ifcopenshell/api/aggregate/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/aggregate/__pycache__/assign_object.cpython-313.pyc,, +ifcopenshell/api/aggregate/__pycache__/unassign_object.cpython-313.pyc,, +ifcopenshell/api/aggregate/assign_object.py,sha256=gtaIdImBpQsJvQTeT7FJtSCtdpqkdxXmDol_IVE1Duc,6906 +ifcopenshell/api/aggregate/unassign_object.py,sha256=g7AuZxoe6FvL20AmMYLXsVQpt7fai_5SfqOBvRutyKE,3160 +ifcopenshell/api/alignment/__init__.py,sha256=vy77TztEzoo3siLeLlWiGw5UYkKkV2Dsw4brI3Kyrag,5901 +ifcopenshell/api/alignment/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_add_segment_to_curve.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_add_segment_to_layout.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_add_zero_length_segment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_create_geometric_representation.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_create_offset_curve_representation.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_create_polyline_representation.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_get_cant_segment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_get_segment_start_point_label.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_map_alignment_cant_segment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_map_alignment_horizontal_segment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_map_alignment_vertical_segment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/_update_curve_segment_transition_code.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/add_stationing_referent.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/add_vertical_layout.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/add_zero_length_segment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/create.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/create_as_offset_curve.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/create_as_polyline.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/create_by_pi_method.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/create_from_csv.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/create_layout_segment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/create_representation.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/create_segment_representations.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/distance_along_from_station.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_alignment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_alignment_layout_nest.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_alignment_layouts.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_alignment_segment_nest.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_alignment_start_station.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_axis_subcontext.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_basis_curve.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_cant_layout.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_child_alignments.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_curve.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_curve_segment_transition_code.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_horizontal_layout.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_layout_curve.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_layout_segments.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_mapped_segments.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_parent_alignment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_referent_nest.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/get_vertical_layout.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/has_zero_length_segment.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/layout_horizontal_alignment_by_pi_method.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/layout_vertical_alignment_by_pi_method.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/name_segments.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/update_fallback_position.cpython-313.pyc,, +ifcopenshell/api/alignment/__pycache__/util.cpython-313.pyc,, +ifcopenshell/api/alignment/_add_segment_to_curve.py,sha256=_sXxfl8Zn3pZdYeIP0vGigMDFuYEb7t4Mr8Js1MuZTo,6463 +ifcopenshell/api/alignment/_add_segment_to_layout.py,sha256=2LYaIFo7uDilkUKX-Ro29jJNjBA3TseEs1dqamlg1F0,10287 +ifcopenshell/api/alignment/_add_zero_length_segment.py,sha256=9X3sucwWbo3gfz993W-0Yq4J4Lzs6A3W1UUXwhy4-rQ,2737 +ifcopenshell/api/alignment/_create_geometric_representation.py,sha256=mbY5SwrY5C9EzyKJL6QyJYokywWJoFfvbX6YQ645DUU,7830 +ifcopenshell/api/alignment/_create_offset_curve_representation.py,sha256=_9ARuRf-MhAp-lKDuK-URzWNTDB0ru198bw-3nx7s_k,2711 +ifcopenshell/api/alignment/_create_polyline_representation.py,sha256=x2FuL5aL9kw6BHGSz9ps2pjz7_c4_IZr9ZLgDuFv_xo,2575 +ifcopenshell/api/alignment/_get_cant_segment.py,sha256=FmLUeWWnwalsfEuA_p1iqsXQxmg_8ssRQLng-FlULSo,3319 +ifcopenshell/api/alignment/_get_segment_start_point_label.py,sha256=CMWeNBaJ4OMvyKJFt1hZkyoPvePqGgITS4jppvQgjv8,11901 +ifcopenshell/api/alignment/_map_alignment_cant_segment.py,sha256=Ni35482W4rSqTYGfvHwnYEWJfnQqVNVVatDXeCiGyrU,18810 +ifcopenshell/api/alignment/_map_alignment_horizontal_segment.py,sha256=2FQZ5hGToU3VxkB2DF9IM0zefYuVDb2oquVj_1uwLqQ,23403 +ifcopenshell/api/alignment/_map_alignment_vertical_segment.py,sha256=06rxM588qVaISf5ljftrBMs27IpL8jU58fkoPTEIG4k,8613 +ifcopenshell/api/alignment/_update_curve_segment_transition_code.py,sha256=NIlNN2ZWhTgR4ELTY0Er0cPms3aXQZ4UqGEJZ6Nc074,1426 +ifcopenshell/api/alignment/add_stationing_referent.py,sha256=9RH1YZjuCs3rQ9FeeHC4a3vYaomarVW1aMS8ZV17Tj0,6054 +ifcopenshell/api/alignment/add_vertical_layout.py,sha256=7P1pESZqUL0N3tFFcEK6-4cbJyJi_0RD4PfKybLc6GE,11360 +ifcopenshell/api/alignment/add_zero_length_segment.py,sha256=YqiLd09VKwHRn_HvWStYiHfStD0N-5QhLbOXjZjpgkY,11348 +ifcopenshell/api/alignment/create.py,sha256=A9mnKoroIYWvnuWAnJihqPBYm_azUMSThedbBRX57gs,4523 +ifcopenshell/api/alignment/create_as_offset_curve.py,sha256=XvwRBhbfDSBnKWcf8doceOT-bYL0lJB5PbKz4Ra2Au0,2174 +ifcopenshell/api/alignment/create_as_polyline.py,sha256=S8YjCY13-g9MmqLp0tDQbIOP3hcNL6SuGIfVMM8QLwc,5610 +ifcopenshell/api/alignment/create_by_pi_method.py,sha256=k42CvE9gwkUaDZNOnTjiyUKjW1DEQmVFLzHdYIRHLDU,2559 +ifcopenshell/api/alignment/create_from_csv.py,sha256=gQX2s_J0de2aDzWiVmp-wCzhnugJmZ_n-yyYXuqnMl4,3819 +ifcopenshell/api/alignment/create_layout_segment.py,sha256=Goammg-V5t_l_KDNJPpnLcwpPFHYsTa4bUfeL2GkIas,4430 +ifcopenshell/api/alignment/create_representation.py,sha256=KaCNdMZiLWkBU0eQrMJXJbm7TwMkt9hpyF_fqw6CKZk,2371 +ifcopenshell/api/alignment/create_segment_representations.py,sha256=pT7BRnqITZFR-L4sjs4QDBHHS1eiJM7vB_T0Hp9J5kk,3702 +ifcopenshell/api/alignment/distance_along_from_station.py,sha256=FMQxk-mkvGt_ekM9k2kW4eY86BYjHhmLrqI_JpA9Jzo,1986 +ifcopenshell/api/alignment/get_alignment.py,sha256=6aL5mOlpRmO9dK8j9n9BO61WXf5pNzZVTjhC2syCW7k,1163 +ifcopenshell/api/alignment/get_alignment_layout_nest.py,sha256=c0q2l99dRNooV68gA__9zGFiRN4jQ-YdZqDHAPB940E,1458 +ifcopenshell/api/alignment/get_alignment_layouts.py,sha256=klHdTuBhwJKov2v-vENbjvMneyqpY0bVQoUzF8xGrss,1476 +ifcopenshell/api/alignment/get_alignment_segment_nest.py,sha256=5b0DchnpBSd5VpZBWUHnLh-mHT8jAJ7Epq7R0aZyqFY,1380 +ifcopenshell/api/alignment/get_alignment_start_station.py,sha256=-fS1iHgLTKg9DNTQ8opuVjbWZVnwNqUGv_8D4fDjFCU,2028 +ifcopenshell/api/alignment/get_axis_subcontext.py,sha256=H-Sm-yLAPzh1nYP4oFBFl0xcDE4SHyB-8vADp1ctaCg,1692 +ifcopenshell/api/alignment/get_basis_curve.py,sha256=8xXjvExKbFlA50DwYuwkWOuZwar8PMywlNVUeMuA0Y0,2499 +ifcopenshell/api/alignment/get_cant_layout.py,sha256=JF05pypXtxIFeB765HzMVlqVhuiX9z5Dk8q8XNF4MD8,1168 +ifcopenshell/api/alignment/get_child_alignments.py,sha256=zHOttf--Aeifa1C8uY3Ll0OSCPxOlDezJGdbHrbwQCc,1559 +ifcopenshell/api/alignment/get_curve.py,sha256=rLb1Nnfs2ayH6VV_rjwl5C6qyaoYmILDYhEcTvkEE6g,2168 +ifcopenshell/api/alignment/get_curve_segment_transition_code.py,sha256=2K_hDk1VMb91JsYpUCroTFXXoIrN5BzXd0ALJ77-kV0,3658 +ifcopenshell/api/alignment/get_horizontal_layout.py,sha256=2jbiK-VCjUQ4XjKAbqIIwDyxlFt9LfIh8vPf8uREPgg,1186 +ifcopenshell/api/alignment/get_layout_curve.py,sha256=mWKiyqoDblmidkVY9EQTfoLX7T71UpTmcRwLRqXkXxo,2204 +ifcopenshell/api/alignment/get_layout_segments.py,sha256=snVOJin8pYvxqq6EgaSqYXr-WKdJgAQjUIH28eF4Gog,1514 +ifcopenshell/api/alignment/get_mapped_segments.py,sha256=mjbROmjS-bzQ8tfXkDkaFLaMf_cCgXY3mdHG6R52kkw,2555 +ifcopenshell/api/alignment/get_parent_alignment.py,sha256=IwuCxcAwO0D_f_fiF5sNjmfwmfe8_a1S6gob__ndhMM,1649 +ifcopenshell/api/alignment/get_referent_nest.py,sha256=yrjSFBwSmslkphKVbLnyBiSqCgLuwALwcDMepx8CUPo,1638 +ifcopenshell/api/alignment/get_vertical_layout.py,sha256=xA0fFJJueelZTQbBPR_cLhCc80CYFfgYbWxYs_bHSsk,1180 +ifcopenshell/api/alignment/has_zero_length_segment.py,sha256=rGn0uFu9hJQgqvAzfVpS1G3vWFyKT5Yqe29A3SaHhmc,2782 +ifcopenshell/api/alignment/layout_horizontal_alignment_by_pi_method.py,sha256=uwFS8btEvIBcw5ben9eW7ZJAI71r_d_HjcLkLaRyHNY,4932 +ifcopenshell/api/alignment/layout_vertical_alignment_by_pi_method.py,sha256=CpR08oal7_JHYRPBgscpn4JHL4Dy9MWyrCpeYce80UA,4342 +ifcopenshell/api/alignment/name_segments.py,sha256=aKThhcZL2Rs-QbEmIUHVPrrTD-4K8-1qcCYreBPBVKE,1778 +ifcopenshell/api/alignment/update_fallback_position.py,sha256=PY9ty9E-2ztxQQFZZV43E29rt8KKleOD9Tkeguir2ng,2119 +ifcopenshell/api/alignment/util.py,sha256=8sx6SJTCwTUkWk4lbF5E-2pk7T4W3soirKkPz0KWd8k,6495 +ifcopenshell/api/attribute/__init__.py,sha256=oQoQArw7MtD5Csdi4BLqTQXXDmCSq1iOVavLspfNbCE,1206 +ifcopenshell/api/attribute/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/attribute/__pycache__/edit_attributes.cpython-313.pyc,, +ifcopenshell/api/attribute/edit_attributes.py,sha256=p4UGLV9UfFxKJInUr57nixmpr9oUlg5L3xIFFCt864c,3906 +ifcopenshell/api/boundary/__init__.py,sha256=YVG6FZQzKVr8H_0JgxwM2o3LDl4FpnxasuKnDA7BIHg,1406 +ifcopenshell/api/boundary/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/boundary/__pycache__/assign_connection_geometry.cpython-313.pyc,, +ifcopenshell/api/boundary/__pycache__/copy_boundary.cpython-313.pyc,, +ifcopenshell/api/boundary/__pycache__/edit_attributes.cpython-313.pyc,, +ifcopenshell/api/boundary/__pycache__/remove_boundary.cpython-313.pyc,, +ifcopenshell/api/boundary/assign_connection_geometry.py,sha256=bdleZcEyB9n6lF9Bpe1iHIwOzzii-rqjZkT_gAUAW3I,5880 +ifcopenshell/api/boundary/copy_boundary.py,sha256=ssVNzqLxPAEq2Ogr0-ZiabRIP-y--hGV3OxZxKkHFEw,1697 +ifcopenshell/api/boundary/edit_attributes.py,sha256=DvZd3XU56b4TUoVEi0Sw09t39FnKWHNdKyn8gFziho4,2592 +ifcopenshell/api/boundary/remove_boundary.py,sha256=VYQq_2dv1Tpbz4uNaQOwpoOhV3FTqCdFWfrG9sFDmrE,1866 +ifcopenshell/api/classification/__init__.py,sha256=P77XtD_DfZXn5gdtbgfs6tFVsUXSPCRRkMiNQAQgNuE,1766 +ifcopenshell/api/classification/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/classification/__pycache__/add_classification.cpython-313.pyc,, +ifcopenshell/api/classification/__pycache__/add_reference.cpython-313.pyc,, +ifcopenshell/api/classification/__pycache__/edit_classification.cpython-313.pyc,, +ifcopenshell/api/classification/__pycache__/edit_reference.cpython-313.pyc,, +ifcopenshell/api/classification/__pycache__/remove_classification.cpython-313.pyc,, +ifcopenshell/api/classification/__pycache__/remove_reference.cpython-313.pyc,, +ifcopenshell/api/classification/add_classification.py,sha256=jHg4JHX8biK9xzXHt8ubxEpBh8Xa1zLtCSDZcdc9xlA,5383 +ifcopenshell/api/classification/add_reference.py,sha256=POPEeUGswYmbfvcvrwo__t8vRTZe7A0TuAxZQYmlseo,11969 +ifcopenshell/api/classification/edit_classification.py,sha256=S9r00eJJ4KMy_ZSuPtefoWPvISyVs56KXz8n4jvsfeU,1713 +ifcopenshell/api/classification/edit_reference.py,sha256=vHtIJNwybGQHXU_N2BjJJz7r6vXOblCN7ijtPnR6OZQ,1688 +ifcopenshell/api/classification/remove_classification.py,sha256=_egHQwxek5d1gOHGsXvOa1QCaZYTisw193CMdtHOdQc,2995 +ifcopenshell/api/classification/remove_reference.py,sha256=jqTW0t_bEl5Q_2mBmGVwionG0n62VMwVoWNzO0O4flE,4630 +ifcopenshell/api/cogo/__init__.py,sha256=fVfzUQbICULTkTDg-5H0z7VLWgbdD506RoQHUA2MrXs,1218 +ifcopenshell/api/cogo/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/cogo/__pycache__/add_survey_point.cpython-313.pyc,, +ifcopenshell/api/cogo/__pycache__/assign_survey_point.cpython-313.pyc,, +ifcopenshell/api/cogo/__pycache__/bearing2dd.cpython-313.pyc,, +ifcopenshell/api/cogo/__pycache__/edit_survey_point.cpython-313.pyc,, +ifcopenshell/api/cogo/add_survey_point.py,sha256=mRpF__XQMh2v7aaTTlLMxjUiQqKrrov7qA6_SDOh_Lk,2315 +ifcopenshell/api/cogo/assign_survey_point.py,sha256=tJLjvE5tAOdo6xaPHduUQrzT_xCM5owRvLu_GvWGJ3Q,1484 +ifcopenshell/api/cogo/bearing2dd.py,sha256=fxO2M4-D9onofBM4s5scDDZKg4zBjcQPwjGYJFbx0qo,2939 +ifcopenshell/api/cogo/edit_survey_point.py,sha256=aZXLdakoUhNJrR_aPSzQninhxxN71bIBRyDBN0Sv10A,1577 +ifcopenshell/api/constraint/__init__.py,sha256=GH9uuahPc-KNYw7sQ550xrs3W1fMD0UZY0CeLHsT4bE,1666 +ifcopenshell/api/constraint/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/add_metric.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/add_metric_reference.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/add_objective.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/assign_constraint.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/edit_metric.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/edit_objective.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/remove_constraint.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/remove_metric.cpython-313.pyc,, +ifcopenshell/api/constraint/__pycache__/unassign_constraint.cpython-313.pyc,, +ifcopenshell/api/constraint/add_metric.py,sha256=nJfHDf-wH1UDLCwvoVg3-8Kd1FjjH6sgpDUwhjK2uDU,2022 +ifcopenshell/api/constraint/add_metric_reference.py,sha256=TODTxHBO1fppvdWXkEUs5BxLgIwpkW4dk_zcfG2JHnE,1891 +ifcopenshell/api/constraint/add_objective.py,sha256=aociXUCFQFdjlj9Sr5hEL4zYnA7f1Cq5JWrR8gKKC6E,1969 +ifcopenshell/api/constraint/assign_constraint.py,sha256=bVDpUNqs4pQEvJc6LPo1gg5_T_TeVhRuQsbKshRyX1Y,3447 +ifcopenshell/api/constraint/edit_metric.py,sha256=PCcYtilEtXcadzmwFDh0ompbds9wxgHj5-6amAndw1M,1662 +ifcopenshell/api/constraint/edit_objective.py,sha256=d5XlJd5InXocqEVeBmXi9iaFN4CMDjYvz_7dffThNk0,1602 +ifcopenshell/api/constraint/remove_constraint.py,sha256=QYIeRJn-V3sZhN4-Pa4IQCmVYV9Omf_bhaj-ylh007g,1819 +ifcopenshell/api/constraint/remove_metric.py,sha256=BRR_ssg26chGMlfRCmocVEAK5q567MI6099MwSC4Kcc,2491 +ifcopenshell/api/constraint/unassign_constraint.py,sha256=fIRX3OCANksZ2TLpo2MqL9AUNVZ-xQZXAFxXvxCKpjE,2805 +ifcopenshell/api/context/__init__.py,sha256=qKk0zbewUVVm2y4ON8vEvkGZYkH8Lm4jwN_dk7WzwdY,1436 +ifcopenshell/api/context/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/context/__pycache__/add_context.cpython-313.pyc,, +ifcopenshell/api/context/__pycache__/edit_context.cpython-313.pyc,, +ifcopenshell/api/context/__pycache__/remove_context.cpython-313.pyc,, +ifcopenshell/api/context/add_context.py,sha256=Jzl4_FCxBUL7EB10p8KTD9zIueTSqTk9jGo0APDF5jM,11896 +ifcopenshell/api/context/edit_context.py,sha256=6_tBFrtelvIgTofbva5HVsjZNkC7wliaZHuHMoH9QYw,1961 +ifcopenshell/api/context/remove_context.py,sha256=AnaPBOkQTGhQM0k07wB6R3H68qgwdlUfirf_bUHzhLY,2831 +ifcopenshell/api/control/__init__.py,sha256=WhNb7Tj_2m7XVviB0vzSiN0TKcbnOtTfReN_tzIO0hU,1191 +ifcopenshell/api/control/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/control/__pycache__/assign_control.cpython-313.pyc,, +ifcopenshell/api/control/__pycache__/unassign_control.cpython-313.pyc,, +ifcopenshell/api/control/assign_control.py,sha256=uJHCuahWUKNEjXW4UlMiyorRaW4fhnqPjGIPTRcxLuo,4618 +ifcopenshell/api/control/unassign_control.py,sha256=r3-a3YjlFyVaJfgWwwmfFjtq2M4OEGxCd-0qYhqAJDQ,2597 +ifcopenshell/api/cost/__init__.py,sha256=xUXB1Npy6WhHQnDw1CsLja20VLIvYYyfqmSMnxCIs_k,2768 +ifcopenshell/api/cost/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/add_cost_item.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/add_cost_item_quantity.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/add_cost_schedule.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/add_cost_value.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/assign_cost_item_quantity.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/assign_cost_value.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/calculate_cost_item_resource_value.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/copy_cost_item.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/copy_cost_item_values.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/copy_cost_schedule.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/edit_cost_item.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/edit_cost_item_quantity.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/edit_cost_schedule.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/edit_cost_value.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/edit_cost_value_formula.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/remove_cost_item.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/remove_cost_item_quantity.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/remove_cost_schedule.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/remove_cost_value.cpython-313.pyc,, +ifcopenshell/api/cost/__pycache__/unassign_cost_item_quantity.cpython-313.pyc,, +ifcopenshell/api/cost/add_cost_item.py,sha256=fRup5k2GOl5IlZObjrc5k1FGA2Aect-mHsjFuLVpiHk,2637 +ifcopenshell/api/cost/add_cost_item_quantity.py,sha256=Gm04HxIxKcVJW9IP6qMAVbMzNfWICaOLghUOjgVGaFs,3700 +ifcopenshell/api/cost/add_cost_schedule.py,sha256=KavlYsRlGtJcgfAEWbAANucKIzoC40ynne6ZpygJjAE,2377 +ifcopenshell/api/cost/add_cost_value.py,sha256=3ggnoPEZGyTPGK0L2d3d9gNxH6tS6CyZg5sLXq3e6cY,5084 +ifcopenshell/api/cost/assign_cost_item_quantity.py,sha256=rKyL_sbQe2BzAVyCsb1Y6afcbMVHV_eZJcQKYZ6K1Ao,7141 +ifcopenshell/api/cost/assign_cost_value.py,sha256=OK1lZ0kKO-QIAIyzXtJv_ebcR7EnBVmEMTpGwZI6nIs,3115 +ifcopenshell/api/cost/calculate_cost_item_resource_value.py,sha256=vaSV6OkeDNdL0ynaXNZW-MVEZM5I2G0Kfq6hkwZOFcE,5528 +ifcopenshell/api/cost/copy_cost_item.py,sha256=esERzJXGLmdSM9ifMW1c8zfq6zRXV5OngDuycelvMe8,5138 +ifcopenshell/api/cost/copy_cost_item_values.py,sha256=3t9uSq9LPjgbKGcChs7TpjWBf-ApsoNguKhvZ8tu3zw,2502 +ifcopenshell/api/cost/copy_cost_schedule.py,sha256=zBUWNupy4YE769_t6zQjSH4rpV1b6zZKVaxYDzfOPAM,1969 +ifcopenshell/api/cost/edit_cost_item.py,sha256=6Jbq_OrmdFgah7ndKuIvqWRAiDj9dVGkhNM39TjyqeQ,1654 +ifcopenshell/api/cost/edit_cost_item_quantity.py,sha256=u0pRTfTE1lj6f07lpfG4XkKxNNzW3UiAAlbLUmAumhY,2143 +ifcopenshell/api/cost/edit_cost_schedule.py,sha256=qL55Yvcj7TaCfDpJEeyUZFxVAmvnA_UFCzj7gUUTZUc,1624 +ifcopenshell/api/cost/edit_cost_value.py,sha256=Yv6R45PV09brofA4m1Zw3A779FCdX2K2cusyU6OUvSU,2633 +ifcopenshell/api/cost/edit_cost_value_formula.py,sha256=wjANJ-G41aTLwej7ZCkYg0_WkATW6KWN9CJC6e2rw00,3151 +ifcopenshell/api/cost/remove_cost_item.py,sha256=ea9gOrc4bJxyoWOOqA9v1vuTuWGtlSQtM0AeWXGc_SI,2551 +ifcopenshell/api/cost/remove_cost_item_quantity.py,sha256=6GCrAes34TohAPoEND3WtWCJPEAo1OJgMqVhxDic6-Y,2071 +ifcopenshell/api/cost/remove_cost_schedule.py,sha256=8e1fiSnUdn5VPQXjkPAjYpRz9qg32UVaaS4GSZyRdHE,2001 +ifcopenshell/api/cost/remove_cost_value.py,sha256=TBb5Hw7dzy10NVJ_FluQHg8sKIMawozSHhJ-I3CRQhM,2521 +ifcopenshell/api/cost/unassign_cost_item_quantity.py,sha256=lAcAYEYKCKmrRSBJUpflTxKK6r3QCaeQBH3JOAI1yzU,4675 +ifcopenshell/api/document/__init__.py,sha256=aJ8i-7QuBqxVMKXRYcIzlF0FPLefJ-px9eXRja4kp98,1781 +ifcopenshell/api/document/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/document/__pycache__/add_information.cpython-313.pyc,, +ifcopenshell/api/document/__pycache__/add_reference.cpython-313.pyc,, +ifcopenshell/api/document/__pycache__/assign_document.cpython-313.pyc,, +ifcopenshell/api/document/__pycache__/edit_information.cpython-313.pyc,, +ifcopenshell/api/document/__pycache__/edit_reference.cpython-313.pyc,, +ifcopenshell/api/document/__pycache__/remove_information.cpython-313.pyc,, +ifcopenshell/api/document/__pycache__/remove_reference.cpython-313.pyc,, +ifcopenshell/api/document/__pycache__/unassign_document.cpython-313.pyc,, +ifcopenshell/api/document/add_information.py,sha256=OT8gYPoH3SDWL1Ikg6K8-wDB6h-_7XdmL8LRxmffzJM,3556 +ifcopenshell/api/document/add_reference.py,sha256=8wTFPv1AgfLIlU4fkD4uvLCEh2yXZRRkW0-0IXkGdpw,3345 +ifcopenshell/api/document/assign_document.py,sha256=5g83lSnHFW5dzpNGgtDPJKd5u4xKULv9tCm8fohmJ1A,4233 +ifcopenshell/api/document/edit_information.py,sha256=lKE4hoz8ELTtULIqA-bKBgN69KXMdhJP2b2kzCLJ89Q,1754 +ifcopenshell/api/document/edit_reference.py,sha256=G-Ush3zCJR9EvT7u2kkwrRV5CNjG_dYvM87WVp8f1fw,1961 +ifcopenshell/api/document/remove_information.py,sha256=mVwmLpdibsNTnmQLEGibXhBkake1pPr1e8DcF8JriB4,2416 +ifcopenshell/api/document/remove_reference.py,sha256=RUxYF1vJk2ctFurmxd4qxF6uxm-WNTLMjRtHkBHi8jc,1770 +ifcopenshell/api/document/unassign_document.py,sha256=e654n3kRnF6cOVip-jpjgWGjQQZSbZTaiyZQuRkIbhM,3076 +ifcopenshell/api/drawing/__init__.py,sha256=ona-3BJ4fYctadohMsF0zkM6d3EkjoRsJ6iIWAkBmWY,1313 +ifcopenshell/api/drawing/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/drawing/__pycache__/assign_product.cpython-313.pyc,, +ifcopenshell/api/drawing/__pycache__/edit_text_literal.cpython-313.pyc,, +ifcopenshell/api/drawing/__pycache__/unassign_product.cpython-313.pyc,, +ifcopenshell/api/drawing/assign_product.py,sha256=qhA8rMFfLmnnQmjL8yNApNt4NdkmUmahnaEalBjYWbE,4158 +ifcopenshell/api/drawing/edit_text_literal.py,sha256=c5oW7N9SMl9DLYKRsVlcVI7WDvntK91tp2xeeqpMg8o,1602 +ifcopenshell/api/drawing/unassign_product.py,sha256=vu-Y6uflWJXX2TY9_WYK7qpO_O8qEP9eTwjvETqrnkY,3030 +ifcopenshell/api/feature/__init__.py,sha256=iPMLGhSed5hgRlBHYXkoqGFN4NvmPjrXD6bhl5zzNdo,1519 +ifcopenshell/api/feature/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/feature/__pycache__/add_feature.cpython-313.pyc,, +ifcopenshell/api/feature/__pycache__/add_filling.cpython-313.pyc,, +ifcopenshell/api/feature/__pycache__/remove_feature.cpython-313.pyc,, +ifcopenshell/api/feature/__pycache__/remove_filling.cpython-313.pyc,, +ifcopenshell/api/feature/add_feature.py,sha256=1cpH_ieSlxQDkNvcyu0oMJG6BtvPB08d1MrAV856_Vo,6706 +ifcopenshell/api/feature/add_filling.py,sha256=jSLeanrZPy7D6oaq1nWpiKmAkK1Fh-PSeG7_xhBxyDg,5163 +ifcopenshell/api/feature/remove_feature.py,sha256=jmXx8SqYw_fYK9CQBw6Y12GOIv2PuhN8RxBaZK5vaBw,2572 +ifcopenshell/api/feature/remove_filling.py,sha256=bjTCf2VxI0-AXBb0XM71frISJD35BTtZwe_4_MD2o80,2191 +ifcopenshell/api/geometry/__init__.py,sha256=Nc4J8czNOwEwMRFcPH8AqEkjwHXCEKLmESGUjcLB3rk,3449 +ifcopenshell/api/geometry/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_axis_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_boolean.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_door_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_footprint_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_mesh_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_profile_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_railing_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_shape_aspect.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_slab_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_wall_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/add_window_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/assign_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/connect_element.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/connect_path.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/connect_wall.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/create_2pt_wall.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/disconnect_element.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/disconnect_path.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/edit_object_placement.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/map_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/regenerate_wall_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/remove_boolean.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/remove_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/unassign_representation.cpython-313.pyc,, +ifcopenshell/api/geometry/__pycache__/validate_type.cpython-313.pyc,, +ifcopenshell/api/geometry/add_axis_representation.py,sha256=bwv3L8NInotIiVhmolygMmqplaj3R87N-nQWH2hGTko,4750 +ifcopenshell/api/geometry/add_boolean.py,sha256=xVQcTszXCsdOEZSQZRMUhA197fecTY82Dcb5NCe8fr8,5184 +ifcopenshell/api/geometry/add_door_representation.py,sha256=sIxtN-_n8__byFh642Roy_YxOFr6dePvrzDzMWFWcmU,29372 +ifcopenshell/api/geometry/add_footprint_representation.py,sha256=ji2DtL4UD7298SsvA6PrBhXEE-e7qjzoD0jZmQB0zjk,1281 +ifcopenshell/api/geometry/add_mesh_representation.py,sha256=-l1-E_eNoBDoAZHbYzm5krr6ol19-oPQVIvxZVF2KoI,5170 +ifcopenshell/api/geometry/add_profile_representation.py,sha256=lqPj0iAly0idJYNt--89IFLCEXtfvdHlp5MBXWYryRo,10151 +ifcopenshell/api/geometry/add_railing_representation.py,sha256=QH9aavSP2dRQIFlmRoccGge731xd7P8J5Y8j8Tlk6Ys,17729 +ifcopenshell/api/geometry/add_representation.py,sha256=dRGQisL0KzEoP5I3B5aq3U5Q_mFjchhAPE6FkscJDzY,47387 +ifcopenshell/api/geometry/add_shape_aspect.py,sha256=ir4hyXyDgDcsKvOJVkYC_kgXXVIYch2yV4OtfCyzSHs,3823 +ifcopenshell/api/geometry/add_slab_representation.py,sha256=HxbAgyKY-yNm-EyqzZxYk6w6I6aKWQFUQbSUUJ-JAOc,6660 +ifcopenshell/api/geometry/add_wall_representation.py,sha256=7ylXCMAnpxxK_t8kuNMIA_JjqVPFx6XkRHP5mTG6I3Q,6082 +ifcopenshell/api/geometry/add_window_representation.py,sha256=CTF2ZXNJfs34_V9ArHpBBtNEA0SAbpOKY49Yh3RpWQU,32981 +ifcopenshell/api/geometry/assign_representation.py,sha256=jV7G4L1J13dxt6YFNjDSnn43f2nynfseLzYX_pm8ylI,4259 +ifcopenshell/api/geometry/connect_element.py,sha256=NAmB_panCT8CfO09tkC85CcSHGF2hB6U8ltJ3V7ofSE,2322 +ifcopenshell/api/geometry/connect_path.py,sha256=PXYV5_aEcKeJhQJ3rC6ABBz-cs4CSlZCNAvke2BTua0,3397 +ifcopenshell/api/geometry/connect_wall.py,sha256=u0WnqyykbKHAt9jI84b3ztJ__s0bzyCWk_nfaYatfds,2337 +ifcopenshell/api/geometry/create_2pt_wall.py,sha256=0CpD9P_UxsPQW5L31d_Gx67DM9x9YtPUJnEn3qjSegs,3210 +ifcopenshell/api/geometry/disconnect_element.py,sha256=xz1psxzkDcdzRPXuyrfR5f2b32SN6vLq_9pkHmVDivA,2316 +ifcopenshell/api/geometry/disconnect_path.py,sha256=21JHx-aVuD_Y63dElJFv-wLDnLcNVL7dirgBt-iKWYg,2309 +ifcopenshell/api/geometry/edit_object_placement.py,sha256=RGHxhciRBZIxuIC1mC-G8KEgXcvYqIuGc0t3sy3fLVw,9094 +ifcopenshell/api/geometry/map_representation.py,sha256=CN-r8AKP0lGlOSAdN3_W5FNJ27Xh26TBHk0GPW4nStk,2750 +ifcopenshell/api/geometry/regenerate_wall_representation.py,sha256=5nt_37j1F9AKq1U9i3ZeukdDJFn8l_1Qdduqb26QX-M,30489 +ifcopenshell/api/geometry/remove_boolean.py,sha256=DLeTgxyAyoeJaXFlXECZHtnUg6qJ7EZMhPM9f6uMiRY,2434 +ifcopenshell/api/geometry/remove_representation.py,sha256=PA_WKPhNkepxWUceM7SaXp7wv8Jtecdb77urWe4ujbY,4243 +ifcopenshell/api/geometry/unassign_representation.py,sha256=ZqcK_dkE7sL9m7G8KiG002hWmzUvR-AG8Hw4Q6Ye2sI,5530 +ifcopenshell/api/geometry/validate_type.py,sha256=BDJWFad0OtaZzxG-B8LPtkfKf211P8tmJgrl6DC0F5g,3601 +ifcopenshell/api/georeference/__init__.py,sha256=cPgcCMrMucpUwXAbHvhj1Zlv71b34q20B5yhGvqdEtI,1494 +ifcopenshell/api/georeference/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/georeference/__pycache__/add_georeferencing.cpython-313.pyc,, +ifcopenshell/api/georeference/__pycache__/edit_georeferencing.cpython-313.pyc,, +ifcopenshell/api/georeference/__pycache__/edit_true_north.cpython-313.pyc,, +ifcopenshell/api/georeference/__pycache__/edit_wcs.cpython-313.pyc,, +ifcopenshell/api/georeference/__pycache__/remove_georeferencing.cpython-313.pyc,, +ifcopenshell/api/georeference/add_georeferencing.py,sha256=u3ptvmMHXxtAny263MeBhniBSGa1CvfljZO926dDprE,3878 +ifcopenshell/api/georeference/edit_georeferencing.py,sha256=L7e8ngzDj2vAW9od6VygHJ-1ct1sZBQX7dsXyAxX2Wc,5519 +ifcopenshell/api/georeference/edit_true_north.py,sha256=bm3ZkLvYL60-lme44ozWrnJ7jzr_2WN00994VI33R5E,3098 +ifcopenshell/api/georeference/edit_wcs.py,sha256=OSMoewwfExpzWUFU3pnw64Mj5WjmVWDy3c1A_YIOdRY,3690 +ifcopenshell/api/georeference/remove_georeferencing.py,sha256=4DaMPfPcdpG-4I448Yrh8lAa7EXuop_2eu-kXmiJ9eo,2158 +ifcopenshell/api/grid/__init__.py,sha256=TV3dwXdCshIfwaaHCUh9nv0uv-rDGS-XDzqsXr2ksrs,1210 +ifcopenshell/api/grid/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/grid/__pycache__/create_axis_curve.cpython-313.pyc,, +ifcopenshell/api/grid/__pycache__/create_grid_axis.cpython-313.pyc,, +ifcopenshell/api/grid/__pycache__/remove_grid_axis.cpython-313.pyc,, +ifcopenshell/api/grid/create_axis_curve.py,sha256=xbuJ4gNBIkQ4ImJDEfd7DwUO8jWvCa21VC9D7B1CkSs,3411 +ifcopenshell/api/grid/create_grid_axis.py,sha256=NVKf-644lhB5QNjUph8x93sDBw95-gRUqkQ4eriSErs,3500 +ifcopenshell/api/grid/remove_grid_axis.py,sha256=mn2uERruJ-3DApMbKV9oQCqiScjCdxNb34FP537VAJM,1911 +ifcopenshell/api/group/__init__.py,sha256=4C7Mk9_u98lTd4FvUl6lJReURhwhOYQw1Y_wwmbV7MI,1550 +ifcopenshell/api/group/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/group/__pycache__/add_group.cpython-313.pyc,, +ifcopenshell/api/group/__pycache__/assign_group.cpython-313.pyc,, +ifcopenshell/api/group/__pycache__/edit_group.cpython-313.pyc,, +ifcopenshell/api/group/__pycache__/remove_group.cpython-313.pyc,, +ifcopenshell/api/group/__pycache__/unassign_group.cpython-313.pyc,, +ifcopenshell/api/group/__pycache__/update_group_products.cpython-313.pyc,, +ifcopenshell/api/group/add_group.py,sha256=DqGQ29ksMS8Rf7xOOEmGgOJT46xSTCX0QOWcfSBbEf8,2077 +ifcopenshell/api/group/assign_group.py,sha256=v9b8-aMuNW0exXBdtGPuE8bpqLQw_cOZSQRgAGCxteU,2470 +ifcopenshell/api/group/edit_group.py,sha256=cuaucl-jofnFNuE-Ap3lt_lMfo7pLU6Dnwf1MWmokV0,1603 +ifcopenshell/api/group/remove_group.py,sha256=dRPW-eh66x1a5YYahZsJPsbUrxR4Chb0t5LQZjRHgus,2400 +ifcopenshell/api/group/unassign_group.py,sha256=76-y6kY828KCXVHXi_nWjgsaYMCTuavrQQGLr0lHQR8,2166 +ifcopenshell/api/group/update_group_products.py,sha256=VRkCw6vqWGI1eBTIMrLgX6GkAFQe3fuLAQgF8IY1FIo,2498 +ifcopenshell/api/layer/__init__.py,sha256=_-Y69D0myhGsxI64z4lNQs8jA3FRla8fInHbgiDg5XU,1527 +ifcopenshell/api/layer/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/layer/__pycache__/add_layer.cpython-313.pyc,, +ifcopenshell/api/layer/__pycache__/add_layer_with_style.cpython-313.pyc,, +ifcopenshell/api/layer/__pycache__/assign_layer.cpython-313.pyc,, +ifcopenshell/api/layer/__pycache__/edit_layer.cpython-313.pyc,, +ifcopenshell/api/layer/__pycache__/remove_layer.cpython-313.pyc,, +ifcopenshell/api/layer/__pycache__/unassign_layer.cpython-313.pyc,, +ifcopenshell/api/layer/add_layer.py,sha256=be8wrKp6QWHa9u4A8M9QV5KWNEmhePcngyaPiiK8kKM,1882 +ifcopenshell/api/layer/add_layer_with_style.py,sha256=bUDkE1jkG96udNaaJ5Efx50PmBfXOKUqaoBjYrsEykc,2024 +ifcopenshell/api/layer/assign_layer.py,sha256=S1QVXAgysRdiPPujMCR7vMADPmsUDNeLXIexzqG5xQI,3245 +ifcopenshell/api/layer/edit_layer.py,sha256=lDE9N8lvHUrdIs5t5nK6wKUQmilc68xVcyTAWKLNpR4,1660 +ifcopenshell/api/layer/remove_layer.py,sha256=l-cVmZlJ6r71UPA7PP0z58yVWNO1yYAgMhEXHvUxAuo,1345 +ifcopenshell/api/layer/unassign_layer.py,sha256=pOxji2vcqrg_oX--t4rj4_JXG90qbSFQxwIAIsPdGY4,3105 +ifcopenshell/api/library/__init__.py,sha256=5vmRp1wcEmpap8neu6EiTra06jOJJtxt771Zs_-4mTw,1683 +ifcopenshell/api/library/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/library/__pycache__/add_library.cpython-313.pyc,, +ifcopenshell/api/library/__pycache__/add_reference.cpython-313.pyc,, +ifcopenshell/api/library/__pycache__/assign_reference.cpython-313.pyc,, +ifcopenshell/api/library/__pycache__/edit_library.cpython-313.pyc,, +ifcopenshell/api/library/__pycache__/edit_reference.cpython-313.pyc,, +ifcopenshell/api/library/__pycache__/remove_library.cpython-313.pyc,, +ifcopenshell/api/library/__pycache__/remove_reference.cpython-313.pyc,, +ifcopenshell/api/library/__pycache__/unassign_reference.cpython-313.pyc,, +ifcopenshell/api/library/add_library.py,sha256=vcP685WuAlb27j-ai9wsr8uzvrI7sTeIvhD71Dz9dp4,2704 +ifcopenshell/api/library/add_reference.py,sha256=H-iAIlNz6Zyh7_7-0-puE997gwXVzoGoKt05MqNPb9w,2545 +ifcopenshell/api/library/assign_reference.py,sha256=GGzwtZnVbRR3sunU2Dm3gOys-oDY8-qhDPq1wWFRSeU,3634 +ifcopenshell/api/library/edit_library.py,sha256=Bm4AUV9Gd5_1Ydjk0Tnow-3zUL0znpjbuoDyyHPLHZs,2243 +ifcopenshell/api/library/edit_reference.py,sha256=pFU2ZuFiNvvuNzydwibY8Q7CtR3ZwMFB6QuwRJk-nig,1836 +ifcopenshell/api/library/remove_library.py,sha256=0nXNSokm2YPgQlTeLtrLSAVuR6MZBGLVZ5LBPVN4dEU,2192 +ifcopenshell/api/library/remove_reference.py,sha256=NUwukkf8oP26Q6Y_plM1K2gKxgWpirZM9rQgqW6sa2M,1889 +ifcopenshell/api/library/unassign_reference.py,sha256=ncZIpMMWGPFYD_zXfBmwEKKFj2psh8KRm_4lp6eLl4U,3148 +ifcopenshell/api/material/__init__.py,sha256=AzAWAgjvxVFo3WbhZgsnuHNWfPfuO56xXpacAwLZVpc,3207 +ifcopenshell/api/material/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/add_constituent.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/add_layer.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/add_list_item.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/add_material.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/add_material_set.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/add_profile.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/assign_material.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/assign_profile.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/copy_material.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/edit_assigned_material.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/edit_constituent.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/edit_layer.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/edit_layer_usage.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/edit_material.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/edit_profile.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/edit_profile_usage.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/remove_constituent.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/remove_layer.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/remove_list_item.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/remove_material.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/remove_material_set.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/remove_profile.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/reorder_set_item.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/set_shape_aspect_constituents.cpython-313.pyc,, +ifcopenshell/api/material/__pycache__/unassign_material.cpython-313.pyc,, +ifcopenshell/api/material/add_constituent.py,sha256=IQGB18VRyZEAi6RXsHHSeLrIcfw9S6oi6IBfyn70fvQ,4531 +ifcopenshell/api/material/add_layer.py,sha256=Pnb4yWCwVBSZYYRIvslqjJE0F5qePMOAd1Q3VREs2bI,4700 +ifcopenshell/api/material/add_list_item.py,sha256=M71vQLYcIZzLZWqotVQYulCueulH0deSLdvMPFCCZ60,3796 +ifcopenshell/api/material/add_material.py,sha256=FtBR434xqzaP2PkdXldu_f9OH-NMBSgTZIEZ12lMvIo,3901 +ifcopenshell/api/material/add_material_set.py,sha256=VRc1NWIug-VmDixPknkoBqH5sMAAHU-zVQQGPx9j8sE,6060 +ifcopenshell/api/material/add_profile.py,sha256=cxnhuomxMUzw_kASTA1nMeG_tpd4F3Mb4dFU5mswf6U,4539 +ifcopenshell/api/material/assign_material.py,sha256=GdZpb_Qw7n05O5_uxp95GQ42XhgV7NCwlvyOAJe-nY8,18081 +ifcopenshell/api/material/assign_profile.py,sha256=G5yM-eWzr3zCkK20qLn9BUUYROSeK5rq3qOO_7lrags,6005 +ifcopenshell/api/material/copy_material.py,sha256=im_JgYHRwPZU9EgPKO2fcQxY44uq-LZgB8aW7Vd1Kno,4376 +ifcopenshell/api/material/edit_assigned_material.py,sha256=srLbSSHUP_xG8SPoq6Dg6vMlYPqTyI7RWpZh_vkM2qU,1670 +ifcopenshell/api/material/edit_constituent.py,sha256=9DB8DV4tYmkwuLi-0mj1DOCKuR1T0zkZL7XegcwxNC4,2895 +ifcopenshell/api/material/edit_layer.py,sha256=rksDkXuzbziolzyhutV76ZjrsFyMRw_M5cCFzslnFGE,2960 +ifcopenshell/api/material/edit_layer_usage.py,sha256=mXN-P1vNQ2TorI0WlYeKwABVUeg-ktYL_37krde4hH0,3634 +ifcopenshell/api/material/edit_material.py,sha256=_wtlY0fPSSxkwt5HorgPZTBQTSh10XcOeiYXDdvojiw,1096 +ifcopenshell/api/material/edit_profile.py,sha256=030fsbIOfulvfId4peyirO0HmarqF_He_e6HH2aAAZc,3513 +ifcopenshell/api/material/edit_profile_usage.py,sha256=9hoSotdMP1_Be5Wd7vQHkPMgBZaDouyoU4XRf4xOz_0,10519 +ifcopenshell/api/material/remove_constituent.py,sha256=e1qSCgQ-FW5pJ8yq6SWuSHsAU3SoxwZrkCOvfeF8Ckw,2560 +ifcopenshell/api/material/remove_layer.py,sha256=ow0bfjIxg6Z7_4RKxOHT3U6RF5LQayxrfsEyKzY5F6w,2901 +ifcopenshell/api/material/remove_list_item.py,sha256=CV_ZrYeO4kQ8T_YiuQ8KqRW683wN6ffVCJcacv570UI,2333 +ifcopenshell/api/material/remove_material.py,sha256=iLUY3dTjWunUshS9nyIi0yzQCRUVkXmUB-82s_J2aFM,3098 +ifcopenshell/api/material/remove_material_set.py,sha256=IJCknhFhtXIayqpmheCmE8-YgJS1HR_XRtvxexMGrAQ,3929 +ifcopenshell/api/material/remove_profile.py,sha256=XTqy-cni51Nd3pCkNZhGYqIhH_dB78KaXsDwvmisfPg,3355 +ifcopenshell/api/material/reorder_set_item.py,sha256=jgTfbQB7iDaE8WwbnQZ3NmEB4pae-0D7jo59p_oilXE,2918 +ifcopenshell/api/material/set_shape_aspect_constituents.py,sha256=HzZETzSYvi4wo0FS9MxxuXsEk96IGApwYkzd55sWY_Q,5545 +ifcopenshell/api/material/unassign_material.py,sha256=fPIacRTfvco3mkzigoRwTCeevQlPRLSW0hhIDSx5tO4,5899 +ifcopenshell/api/nest/__init__.py,sha256=SjLlFElhnuNr8Dge3jh20eIUTWdPrix_zXrbGdIB4hs,1628 +ifcopenshell/api/nest/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/nest/__pycache__/assign_object.cpython-313.pyc,, +ifcopenshell/api/nest/__pycache__/change_nest.cpython-313.pyc,, +ifcopenshell/api/nest/__pycache__/reorder_nesting.cpython-313.pyc,, +ifcopenshell/api/nest/__pycache__/unassign_object.cpython-313.pyc,, +ifcopenshell/api/nest/assign_object.py,sha256=dMRedmHJtHlqrNAGiBEtb-HtbqssDvcX7NWHQFJ67DQ,7836 +ifcopenshell/api/nest/change_nest.py,sha256=Fh9oxEVoUUbVDOK0gaJT1b1vbnTldJD8ITFA9k_WMls,1703 +ifcopenshell/api/nest/reorder_nesting.py,sha256=Fq4IO1U6h3ZdHrj9e-ThCbo-NOyn05FvgigeSgGudhw,1366 +ifcopenshell/api/nest/unassign_object.py,sha256=nazRKlS8AYJnbF1R_-oLFkpQphJY-IxL5FwPPbyH0G8,3078 +ifcopenshell/api/owner/__init__.py,sha256=C2caqK2C-AGqcQUXoBVg9AIRoQ_dqV7VAxGOldg98Vk,2775 +ifcopenshell/api/owner/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/add_actor.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/add_address.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/add_application.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/add_organisation.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/add_person.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/add_person_and_organisation.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/add_role.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/assign_actor.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/create_owner_history.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/edit_actor.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/edit_address.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/edit_application.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/edit_organisation.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/edit_person.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/edit_role.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/remove_actor.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/remove_address.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/remove_application.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/remove_organisation.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/remove_person.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/remove_person_and_organisation.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/remove_role.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/settings.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/unassign_actor.cpython-313.pyc,, +ifcopenshell/api/owner/__pycache__/update_owner_history.cpython-313.pyc,, +ifcopenshell/api/owner/add_actor.py,sha256=v61EuycgEMbenFnEQ3e5gFsFTSIAJwvxyEGZc3j-MqI,2746 +ifcopenshell/api/owner/add_address.py,sha256=X6CCyC_m0jjaGdw3YHsSyIRwCTZfXUwck3AlZ8SJwd8,3092 +ifcopenshell/api/owner/add_application.py,sha256=CjZQmoQz9HP94OhwQwN1qXNoDYCafwJS2ZOGwXp_pB8,4694 +ifcopenshell/api/owner/add_organisation.py,sha256=uJPKKTNtHwlClwvDAA9tESw24W3vnEuby8jgRl7_UYo,1931 +ifcopenshell/api/owner/add_person.py,sha256=CqvFI_CZsS2G6SG3DswnUXDO4NsKbRxODfmEo1-65_Y,1821 +ifcopenshell/api/owner/add_person_and_organisation.py,sha256=SIJeSm_7tgNL_2jic5RuwyMszbNL703tpu8V2rbx8P4,1881 +ifcopenshell/api/owner/add_role.py,sha256=_B1SRlHqZh9xIkPvNggbefdxJphakaHzY0GY0XO8YLk,2305 +ifcopenshell/api/owner/assign_actor.py,sha256=XiVpqM3vZo1hjV6UJWtDbzkghqWGtsrNBnTeEde4Q8g,4282 +ifcopenshell/api/owner/create_owner_history.py,sha256=KRPj8wDs3wyCvHanAmoZ9ppbOnjtO0SxrMxp33BL4BU,5626 +ifcopenshell/api/owner/edit_actor.py,sha256=NGvGXcw_1f2rh9Ur20Q6sM2x4r9o7zlBnu2uV5n4oWg,2078 +ifcopenshell/api/owner/edit_address.py,sha256=mLGyiAXKjl-0021IvzNo0-0rYOmeLnVOFnlEL7spwIk,2223 +ifcopenshell/api/owner/edit_application.py,sha256=giCct-M8RL5QjXRvkMDQVhk1_VvqllOwK9cF9mjDN4k,1686 +ifcopenshell/api/owner/edit_organisation.py,sha256=xI7-sOoECgg_bvUSoOd1eTCd8jwRZFcD0XLFAvDAtoo,1718 +ifcopenshell/api/owner/edit_person.py,sha256=AxOcgfYWT5zf-R95XzSGhnZHgvNwFQ0NiISDmzjopFM,1671 +ifcopenshell/api/owner/edit_role.py,sha256=DxSZ0CLb3fJ_drUi69oCGw0DO-ramDT3sCg778Vcwg8,1801 +ifcopenshell/api/owner/remove_actor.py,sha256=TSw2twyLixE12BrciJgChbgFg3zQKjRdLm17ePHYcJE,1829 +ifcopenshell/api/owner/remove_address.py,sha256=rNJAiCRKPotRAiddgQ7ly-TfD8TRji2iCONiE5YkCBM,1688 +ifcopenshell/api/owner/remove_application.py,sha256=0-QMFTjk2a23Lswy9ZZCKJ0kLl_ptD3uEtaZEP1PXp4,1390 +ifcopenshell/api/owner/remove_organisation.py,sha256=W77mTclvbrUrgcsTo7UcGr6CAVQam8x5zoVZgzAMdqI,2843 +ifcopenshell/api/owner/remove_person.py,sha256=qbPAFZFSvj6PEah2ftLDApuTjqBprOjR0qZc0lRzjFI,2875 +ifcopenshell/api/owner/remove_person_and_organisation.py,sha256=iPZAWNwUMvhWPCas6aT_XinM7s_ScnLTQd_PF8WupHQ,2391 +ifcopenshell/api/owner/remove_role.py,sha256=ZhEqKUupqg_hFp26SXl6N0P0fHeyQctUAcSNRf0C9zM,2004 +ifcopenshell/api/owner/settings.py,sha256=XyHQazTW1V7VVPGdlv3RnreAA0EJWuCZ--P8IK0XCe4,3879 +ifcopenshell/api/owner/unassign_actor.py,sha256=ILMCrcxMHUdjMkqEdsrAXDoCLFQnOYie2PcNn3X3TqU,2731 +ifcopenshell/api/owner/update_owner_history.py,sha256=AR58PvapnZqwnRgPM4Crv1wmnsI8aHXK83UacGKFAO8,3407 +ifcopenshell/api/profile/__init__.py,sha256=oa-9gC3GGj3TEMOBMWUBadj4hRYEmaQ33nzNdKOEarQ,1582 +ifcopenshell/api/profile/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/profile/__pycache__/add_arbitrary_profile.cpython-313.pyc,, +ifcopenshell/api/profile/__pycache__/add_arbitrary_profile_with_voids.cpython-313.pyc,, +ifcopenshell/api/profile/__pycache__/add_parameterized_profile.cpython-313.pyc,, +ifcopenshell/api/profile/__pycache__/copy_profile.cpython-313.pyc,, +ifcopenshell/api/profile/__pycache__/edit_profile.cpython-313.pyc,, +ifcopenshell/api/profile/__pycache__/remove_profile.cpython-313.pyc,, +ifcopenshell/api/profile/add_arbitrary_profile.py,sha256=efM_pVHxuYTT0A0pM96VF7yeW3wYLxvt3_HW15SUDbE,3326 +ifcopenshell/api/profile/add_arbitrary_profile_with_voids.py,sha256=f9SMQGzXQQfDZwb7EaW8740YsqxMZf51DJKcmdqlx8M,4782 +ifcopenshell/api/profile/add_parameterized_profile.py,sha256=RLajgOG7ZCzgSw216PXuO-ICIOwdrUm4iCd7qNL092o,1845 +ifcopenshell/api/profile/copy_profile.py,sha256=vekFx8isGKAPamg3T_Kxdp4LWR-z04MRjBtdk6OkJxE,1788 +ifcopenshell/api/profile/edit_profile.py,sha256=BTakPXFOJGJDr6HRUIndXoWNWjLxRfJQul6GAzg9AMw,1666 +ifcopenshell/api/profile/remove_profile.py,sha256=yOd6KLAnPmrSIOHnr_rLxPuJl3Haz7vGlbvHxq4aa6U,2046 +ifcopenshell/api/project/__init__.py,sha256=78_ZEJUbvzhrJ6lvX3G1TC_bHx9RdvB5QUm_aWbRhJQ,1495 +ifcopenshell/api/project/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/project/__pycache__/append_asset.cpython-313.pyc,, +ifcopenshell/api/project/__pycache__/assign_declaration.cpython-313.pyc,, +ifcopenshell/api/project/__pycache__/create_file.cpython-313.pyc,, +ifcopenshell/api/project/__pycache__/unassign_declaration.cpython-313.pyc,, +ifcopenshell/api/project/append_asset.py,sha256=kTc25v8q4BdlJxV_8xMWMabHbjc_caOGBprdlU9YBQo,35548 +ifcopenshell/api/project/assign_declaration.py,sha256=_At9hpr9R8e5PWAKZJ3GEXeLietDykI3VsLuAQ_bJhk,6094 +ifcopenshell/api/project/create_file.py,sha256=_QYflZpjImSMhmrBSu-h42cGe01u0Kf_IwM04GPfiFQ,2635 +ifcopenshell/api/project/unassign_declaration.py,sha256=6rAQu2CbtPmbRLPbvvNsr3ZaZSJibFG758V2hw94Mm8,2875 +ifcopenshell/api/pset/__init__.py,sha256=5AeJaw90_1xfbeE7s35VfBzQehayGfPF_hDUK_cXrHY,1556 +ifcopenshell/api/pset/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/pset/__pycache__/add_pset.cpython-313.pyc,, +ifcopenshell/api/pset/__pycache__/add_qto.cpython-313.pyc,, +ifcopenshell/api/pset/__pycache__/assign_pset.cpython-313.pyc,, +ifcopenshell/api/pset/__pycache__/edit_pset.cpython-313.pyc,, +ifcopenshell/api/pset/__pycache__/edit_qto.cpython-313.pyc,, +ifcopenshell/api/pset/__pycache__/remove_pset.cpython-313.pyc,, +ifcopenshell/api/pset/__pycache__/unassign_pset.cpython-313.pyc,, +ifcopenshell/api/pset/__pycache__/unshare_pset.cpython-313.pyc,, +ifcopenshell/api/pset/add_pset.py,sha256=mx-1K5c-9q51HUrOk6fHWrtbXMhhVD5N_oYJ0a_nEqw,7521 +ifcopenshell/api/pset/add_qto.py,sha256=m91vb63sXoxkjyUd0aF316pA8hM32agaeNsQZzmZQms,5614 +ifcopenshell/api/pset/assign_pset.py,sha256=JGHEtRmPrG-dUu6StNQkHqqIQp_OKdjzwGAo6KOd04g,3771 +ifcopenshell/api/pset/edit_pset.py,sha256=qDhk7yuinWl-hbg1fGsuUxba5uiPXntv6zKtvfo6SFE,22045 +ifcopenshell/api/pset/edit_qto.py,sha256=-TT8gIgkFCLo4-turJvUOBXND1T2yfMfY_py6do97uY,10954 +ifcopenshell/api/pset/remove_pset.py,sha256=2HwPJXe9GEWIcUpHDUeGuE2yYTg6aMNn6KBYsXnZ1CU,3368 +ifcopenshell/api/pset/unassign_pset.py,sha256=Mo_xPhzBIQR5ohD6Iq_YX884YELUIY88AJrnuwrZ6c4,2989 +ifcopenshell/api/pset/unshare_pset.py,sha256=QYoVBYWMP5jNQapk7t0uf_daM3a1pH_6N-8rWN3cALw,3751 +ifcopenshell/api/pset_template/__init__.py,sha256=eMmL0RoxIx3jhe7le5UAgY6TMPlbqwEaRAxfQKb03P8,1706 +ifcopenshell/api/pset_template/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/pset_template/__pycache__/add_prop_template.cpython-313.pyc,, +ifcopenshell/api/pset_template/__pycache__/add_pset_template.cpython-313.pyc,, +ifcopenshell/api/pset_template/__pycache__/edit_prop_template.cpython-313.pyc,, +ifcopenshell/api/pset_template/__pycache__/edit_pset_template.cpython-313.pyc,, +ifcopenshell/api/pset_template/__pycache__/remove_prop_template.cpython-313.pyc,, +ifcopenshell/api/pset_template/__pycache__/remove_pset_template.cpython-313.pyc,, +ifcopenshell/api/pset_template/add_prop_template.py,sha256=DGUm1lkPN5HomcperTPR3mRhA9xzcFkL-8Ol-2qH2PU,4882 +ifcopenshell/api/pset_template/add_pset_template.py,sha256=IY2ZCv1MKyS7TecU0dO_L7J2Qw8SAXu2wntVlXdBNes,4802 +ifcopenshell/api/pset_template/edit_prop_template.py,sha256=Sp1UgaR6RqsduU1zBDbdnPI5cMeut7dvOzrFAtR4moM,2735 +ifcopenshell/api/pset_template/edit_pset_template.py,sha256=g2l-nhPEW83ocn0LNrv9QsIeu7pr-pFx9PI3JPz3Y78,1841 +ifcopenshell/api/pset_template/remove_prop_template.py,sha256=6sHJDLrXXzfErx7l70abN4ThWzCgDh9g5rpT09nwSpk,2160 +ifcopenshell/api/pset_template/remove_pset_template.py,sha256=TH_sDIeh2UI2pX_Us1gUxeAoVoFGo07qdpVnDnmvM5E,1523 +ifcopenshell/api/resource/__init__.py,sha256=zM-IuX5AZ7McxvXUvb3NoDbStzHOgbjJ1E9QpN_shQg,2042 +ifcopenshell/api/resource/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/add_resource.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/add_resource_quantity.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/add_resource_time.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/assign_resource.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/calculate_resource_usage.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/calculate_resource_work.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/edit_resource.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/edit_resource_quantity.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/edit_resource_time.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/remove_resource.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/remove_resource_quantity.cpython-313.pyc,, +ifcopenshell/api/resource/__pycache__/unassign_resource.cpython-313.pyc,, +ifcopenshell/api/resource/add_resource.py,sha256=OE7v5ou3iKfwenGI5Ec1j5BvJtK9fXSCBmgE-2DrOEw,3871 +ifcopenshell/api/resource/add_resource_quantity.py,sha256=HwiprsT-38mU3ShmBPq196-j5WsDh5ildhe6iczPEHs,3534 +ifcopenshell/api/resource/add_resource_time.py,sha256=mRBI_WSYC-YlAcaARcywxFcXApHi2dqpfstIqmVH09Y,2500 +ifcopenshell/api/resource/assign_resource.py,sha256=fO61_nQSMcaCze1oqBRcRSCdObxQDX1KlrBCqNcoSp4,4496 +ifcopenshell/api/resource/calculate_resource_usage.py,sha256=_8QJg_1c_nm6AxHzPXYplH5_7ZmENPdjpE0ObnlaORI,2115 +ifcopenshell/api/resource/calculate_resource_work.py,sha256=aeXTabgIYGoOSu2ySeHEhFJCuYkno8I1kZW4nwkO_7U,2697 +ifcopenshell/api/resource/edit_resource.py,sha256=L424Epnx0QuW2R4bNRLqhxbIrc9lcuijoWD6h2io01I,1679 +ifcopenshell/api/resource/edit_resource_quantity.py,sha256=E_oOmr35jVagHyDxR980rlw0WeLFtKcjmtcDE9cwTL8,2080 +ifcopenshell/api/resource/edit_resource_time.py,sha256=HHuZjQZUVZurYGIPluILlfbCJJ-OX-YkgHxiKP24CN0,4298 +ifcopenshell/api/resource/remove_resource.py,sha256=nXwtf1Ya8N5O-7hptabgqv4zsen_NmmsDxmzvxKMZgo,3413 +ifcopenshell/api/resource/remove_resource_quantity.py,sha256=CkwkMm2NPDb4bMv5jpDpe4EZBIxsNm0LaZQcSV__pJo,1969 +ifcopenshell/api/resource/unassign_resource.py,sha256=7w9rtE0T0J1yP9ym0XSY_LmT3tnwrVP2yOpS_4VFTCc,2832 +ifcopenshell/api/root/__init__.py,sha256=RnXLQb_bSvT9snEp4KbCSDWNB6kMYC4X6Q9CIdc75H4,1517 +ifcopenshell/api/root/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/root/__pycache__/copy_class.cpython-313.pyc,, +ifcopenshell/api/root/__pycache__/create_entity.cpython-313.pyc,, +ifcopenshell/api/root/__pycache__/reassign_class.cpython-313.pyc,, +ifcopenshell/api/root/__pycache__/remove_product.cpython-313.pyc,, +ifcopenshell/api/root/copy_class.py,sha256=YiSm8TWE_5YGcSZwKjMlgSmIyOfk-ZXO4cMFC7fcuSc,9509 +ifcopenshell/api/root/create_entity.py,sha256=XLjcI3XoYDx_H-2isj__T4gcWk1SzkAl58cVdZHMCT0,5799 +ifcopenshell/api/root/reassign_class.py,sha256=MvM6483BJ1Y9tN4auO05pTvGzlMi_qdsVLEeGGiToCk,10221 +ifcopenshell/api/root/remove_product.py,sha256=zEhu1bEglDUyFkV77UUnG5P1nK7Vn7Mdhx2ToWHi3hM,9995 +ifcopenshell/api/sequence/__init__.py,sha256=ffF7qnXNkey0Gya6xZKGxAjKGzJFUEQZIGq55N1OIGk,4070 +ifcopenshell/api/sequence/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/add_date_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/add_task.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/add_task_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/add_time_period.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/add_work_calendar.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/add_work_plan.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/add_work_schedule.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/add_work_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/assign_lag_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/assign_process.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/assign_product.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/assign_recurrence_pattern.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/assign_sequence.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/assign_work_plan.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/calculate_task_duration.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/cascade_schedule.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/copy_work_schedule.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/create_baseline.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/duplicate_task.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_lag_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_recurrence_pattern.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_sequence.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_task.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_task_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_work_calendar.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_work_plan.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_work_schedule.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/edit_work_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/recalculate_schedule.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/remove_task.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/remove_time_period.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/remove_work_calendar.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/remove_work_plan.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/remove_work_schedule.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/remove_work_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/unassign_lag_time.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/unassign_process.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/unassign_product.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/unassign_recurrence_pattern.cpython-313.pyc,, +ifcopenshell/api/sequence/__pycache__/unassign_sequence.cpython-313.pyc,, +ifcopenshell/api/sequence/add_date_time.py,sha256=HdXtF0C4uzeCzW41K30x4jGRi3j4LYiVeVTfKUkc4WA,2222 +ifcopenshell/api/sequence/add_task.py,sha256=LM-WLg7dcBqlU8k_SHZ707uDHjAAT_E1GwBIbRaddkw,7673 +ifcopenshell/api/sequence/add_task_time.py,sha256=yL0WcSAymfum2P8SzrwfAi6-9HdgL1QC2Tz5blURQXQ,2987 +ifcopenshell/api/sequence/add_time_period.py,sha256=xOP2JRwuhMsgW5VRuiQ_cxIbLGy717T7jKy9jH5Omq4,3966 +ifcopenshell/api/sequence/add_work_calendar.py,sha256=b9xDbJT8L-TPYJxBe2DigtEU4cNStC15EonnIsJypB4,4086 +ifcopenshell/api/sequence/add_work_plan.py,sha256=tWAT0zV8fqw2CGZvmUrhMKo27DftiUasx2h9dVBRifo,3198 +ifcopenshell/api/sequence/add_work_schedule.py,sha256=VbqJEogkDHByj8SgDStS0QMXeVWlOwScemvpWK5PMl8,4522 +ifcopenshell/api/sequence/add_work_time.py,sha256=_N-1YlFYTwfPg-xi_dbEHkeKCHFELYfLxlLVJD0Hesk,3645 +ifcopenshell/api/sequence/assign_lag_time.py,sha256=NtWbOLzjwXc4OLn1J4zArpjW3vJGkmfuqvMHWShQWac,4453 +ifcopenshell/api/sequence/assign_process.py,sha256=RFhmjoEodKCytEz8iG9w64-a5-WGwzAAmZJuBnZvofk,4685 +ifcopenshell/api/sequence/assign_product.py,sha256=rWyTSu55HdkyI2abwZsl-gmaRKETK8oUwl0ZyYjkipM,3671 +ifcopenshell/api/sequence/assign_recurrence_pattern.py,sha256=rRvNJZf3KtPOrC-wvom_wr3UHLPTi9w1RQx0_qDYv9U,5512 +ifcopenshell/api/sequence/assign_sequence.py,sha256=qVyY1j9f37n391Q3a8Zy-M3xKfsaa3FPtRk4YcmEN6g,5785 +ifcopenshell/api/sequence/assign_work_plan.py,sha256=5sk0hnYrgo3cKlib0YNoBMAGmvJKyhKd0gSXQhEaTzo,2570 +ifcopenshell/api/sequence/calculate_task_duration.py,sha256=giJ5jZhQzPCyrw0DjvOj95Fhi8Obfr0rqS418QRH0S0,6513 +ifcopenshell/api/sequence/cascade_schedule.py,sha256=ZDS6h8Ag7z7k9z2iCi94Vi7cZaC7wLlZRCGhi4cVB-8,15205 +ifcopenshell/api/sequence/copy_work_schedule.py,sha256=i8yEaZYpVfSPx2P4_3CwIveSOe75OUPDvXC2IqaDZ7M,2063 +ifcopenshell/api/sequence/create_baseline.py,sha256=z8zoasWwOU1NkZgpoLeVmB7JuIQlFNMUtpnDAsTqVyM,4496 +ifcopenshell/api/sequence/duplicate_task.py,sha256=rLhhwKZn45TYuWIELWnf5OPcD1jjZyzY_KuPB96L_1s,9058 +ifcopenshell/api/sequence/edit_lag_time.py,sha256=8m01EWynkYuLyODuJ0EkhGsa5s2GYDY1qjMrJxzORYg,4002 +ifcopenshell/api/sequence/edit_recurrence_pattern.py,sha256=hn8YoXbbPYiUUzGCukPVkJSPv8LEIqQIDqKEdndvtIE,2351 +ifcopenshell/api/sequence/edit_sequence.py,sha256=EBKJaA4dy1Z8OxfrMPPG2SNnBXZuU84TPQmFBuD6uJI,2709 +ifcopenshell/api/sequence/edit_task.py,sha256=svbiUTOk83wuxxRAHQ1TvBFiubM1iu0AFl9vjlovw3g,1961 +ifcopenshell/api/sequence/edit_task_time.py,sha256=7tJnXsHE9eJv0XUUDREoNZcpaQDsv5FDIQBTg5dv3J8,7181 +ifcopenshell/api/sequence/edit_work_calendar.py,sha256=ppPnNjKu6_EzgathbogL8yhCYr7ajuZH8eAlKZxHNvw,1761 +ifcopenshell/api/sequence/edit_work_plan.py,sha256=2S4sb0y2jcopovsHL7hfBrrxIxlPV1zYgM3cW3fwJmM,2040 +ifcopenshell/api/sequence/edit_work_schedule.py,sha256=518PBPktFI_9vA8JuYPVCWJYdV3RTCjLgCJs2jqxNXg,2285 +ifcopenshell/api/sequence/edit_work_time.py,sha256=tvjXQ31XNfJxgD_09bS9V7fbf_PSylRfCrSTyEDKjT8,2505 +ifcopenshell/api/sequence/recalculate_schedule.py,sha256=_tmJTMfbavhew6GDkBQGKeQSwYtGXqGU8ojht9xB9Ls,22477 +ifcopenshell/api/sequence/remove_task.py,sha256=aAsI7svOjFI6Y0XgADRwX_7bm2M468usFWopW3sSiJ0,5637 +ifcopenshell/api/sequence/remove_time_period.py,sha256=-MWgUYWUUFXoXx0AVZFoXXS25eoFZAjBPxHiwdvw-yA,2308 +ifcopenshell/api/sequence/remove_work_calendar.py,sha256=Rbdzfha_PxnjNrw6wiTQK7MOIQ47JsxPMesQ1EkQqYk,2633 +ifcopenshell/api/sequence/remove_work_plan.py,sha256=9wcELV8u-DXI61Izq0UBFvxGg-KpqPDaB7vGkBLbGvM,1996 +ifcopenshell/api/sequence/remove_work_schedule.py,sha256=mgisjkLnY52FRL-NkKYmBU-uSRojZTCusRESa7lRpHo,3290 +ifcopenshell/api/sequence/remove_work_time.py,sha256=LBWhUWilL55UN2MIDZngJDXX99HQxACW4ZoT_GIUDwM,1829 +ifcopenshell/api/sequence/unassign_lag_time.py,sha256=zXJA35ENIXYracOGxFUNmLdomXzCngwsjTeia6mqH-g,2607 +ifcopenshell/api/sequence/unassign_process.py,sha256=Sk4MkV1ng_FyD5V55_6JvbmEQZjpSu_rw0ZQ2dBp4vw,2872 +ifcopenshell/api/sequence/unassign_product.py,sha256=VTs7VMjIShazka5pZPNSJ0faui54FtEQknc-rlh4BkM,2870 +ifcopenshell/api/sequence/unassign_recurrence_pattern.py,sha256=4fb8hx_uT-HGyuw_9TCIhYN0V3M7N6Y09NuCWTXaWHQ,2171 +ifcopenshell/api/sequence/unassign_sequence.py,sha256=inFCEwJi0vMdy9lEBAaZ8wihzvqiiV7mJRR9-7gd0kQ,2687 +ifcopenshell/api/spatial/__init__.py,sha256=na-NuvB3MaI59dOJ3vMgF20E8OQdRiOhqtNjoteTCec,1392 +ifcopenshell/api/spatial/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/spatial/__pycache__/assign_container.cpython-313.pyc,, +ifcopenshell/api/spatial/__pycache__/dereference_structure.cpython-313.pyc,, +ifcopenshell/api/spatial/__pycache__/reference_structure.cpython-313.pyc,, +ifcopenshell/api/spatial/__pycache__/unassign_container.cpython-313.pyc,, +ifcopenshell/api/spatial/assign_container.py,sha256=cttLKbbLrloTYYuiei8foYPCQGzFHiOcOruB0BpYBEA,8015 +ifcopenshell/api/spatial/dereference_structure.py,sha256=rx5iCK74PgU-6G0Tyz6QXmn5egJV_VOiI_dJjZkXwFs,3854 +ifcopenshell/api/spatial/reference_structure.py,sha256=O6zg06Ha3AdkOa1NQP716Ymm4tSZpGBmyLT7j7Rkf7A,4997 +ifcopenshell/api/spatial/unassign_container.py,sha256=fFXeJaxLnyywjnReCpZWvwaeOeRc3szwUpqrAz0pQ-8,2904 +ifcopenshell/api/structural/__init__.py,sha256=KHxbIwyiAHryZ8CMO3EfVnM_uJ2yma3_haznLBu4ZWI,3363 +ifcopenshell/api/structural/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/add_structural_activity.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/add_structural_analysis_model.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/add_structural_boundary_condition.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/add_structural_load.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/add_structural_load_case.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/add_structural_load_group.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/add_structural_member_connection.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/assign_structural_analysis_model.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/edit_structural_analysis_model.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/edit_structural_boundary_condition.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/edit_structural_connection_cs.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/edit_structural_item_axis.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/edit_structural_load.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/edit_structural_load_case.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/remove_structural_analysis_model.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/remove_structural_boundary_condition.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/remove_structural_connection_condition.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/remove_structural_load.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/remove_structural_load_case.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/remove_structural_load_group.cpython-313.pyc,, +ifcopenshell/api/structural/__pycache__/unassign_structural_analysis_model.cpython-313.pyc,, +ifcopenshell/api/structural/add_structural_activity.py,sha256=EuDfpCqsF9RUv_grH8OQ3ZUrkkFdx8DX4xgOXhK6WtQ,2764 +ifcopenshell/api/structural/add_structural_analysis_model.py,sha256=8_FZN3LsvtV2V9TBuhl4KUhABsRDseXJNlznjuVwBMw,1579 +ifcopenshell/api/structural/add_structural_boundary_condition.py,sha256=Qys5AojCzaHF4Cu8DP27sxPrUg5m_1DAtEwFIUQ5al0,2995 +ifcopenshell/api/structural/add_structural_load.py,sha256=HSSdjs0boJLoEltO19JVxi1ctQYOGjGlNZIOvbSmNYk,1722 +ifcopenshell/api/structural/add_structural_load_case.py,sha256=Fssl61JwE56H6bdNoJfEQiLp8B8_x3zd-QEMT2vMp0A,1760 +ifcopenshell/api/structural/add_structural_load_group.py,sha256=QIoXZdNo2EZAmzJIq8Z0Jj5w0mwsEkBrLn66AqWj4l4,1788 +ifcopenshell/api/structural/add_structural_member_connection.py,sha256=vzRBQTAdvJqTyE3gTd5TP-FPIq_ChzpQ5NaiYOITFbU,1866 +ifcopenshell/api/structural/assign_structural_analysis_model.py,sha256=HtGu_6PRny_pR1h6Dawd6wnOd4rOkKajt2fwvkhUdbE,1567 +ifcopenshell/api/structural/edit_structural_analysis_model.py,sha256=ccJKr82XdrHAHP1w5qTGiqIIuICJnY48UrteyVFIkKs,1482 +ifcopenshell/api/structural/edit_structural_boundary_condition.py,sha256=f4LVlqDOfd8x2zf_c5jhKtijp6kIPnrhSU1fJbJlj8s,1929 +ifcopenshell/api/structural/edit_structural_connection_cs.py,sha256=noUFaiYwU0UiR1vLTYOb-BOHRnp7RbI4I8RfY5xLpa8,2215 +ifcopenshell/api/structural/edit_structural_item_axis.py,sha256=P8CXcZEW3XgqkLZd6atWH4lxLavzUEk5Kg9vrc2k5mw,1515 +ifcopenshell/api/structural/edit_structural_load.py,sha256=n0J8du0ZMtOlSg-ZfHZAw233eAVb6HssOLJAqOVaUO8,1415 +ifcopenshell/api/structural/edit_structural_load_case.py,sha256=yWi88XokDMeDZon-UFyTZBB12LpKGdRt0adp0bUvot8,1414 +ifcopenshell/api/structural/remove_structural_analysis_model.py,sha256=ktdp5Ds9oJD3_UPcvkF7yTgsCHeQXg8rtMCcfY1pBEo,1591 +ifcopenshell/api/structural/remove_structural_boundary_condition.py,sha256=BfhmK0dmGOB-JyaLQcPsHzJIx0r-R6TMAp7t6Yx6YtE,2006 +ifcopenshell/api/structural/remove_structural_connection_condition.py,sha256=FAm3LSbATG6Ty604ClxQ2RAD1J1Rh-NdGJaIh1VHmZI,1560 +ifcopenshell/api/structural/remove_structural_load.py,sha256=laZKZt7-r8zwQ6qxKpHidBEyK-iqO1WC4pCUuE24ByU,1083 +ifcopenshell/api/structural/remove_structural_load_case.py,sha256=5FdRhvnfTkF8a2cKTELn2CGvprfRFHcYa-zhWogQS6c,1450 +ifcopenshell/api/structural/remove_structural_load_group.py,sha256=QjNG_73PDyzwlJBTdaOqgc3tRNxTep-7JAFJ7i-PcGg,1592 +ifcopenshell/api/structural/unassign_structural_analysis_model.py,sha256=emuxDSNKhK5NCd7A9iKmFwz5yMXA6BiCHfGvzyCwEWc,1495 +ifcopenshell/api/style/__init__.py,sha256=5zM5te_lPyCGxZqM7b9hU_5BT5D5x-RpYAo88uRKUp8,2236 +ifcopenshell/api/style/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/add_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/add_surface_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/add_surface_textures.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/assign_item_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/assign_material_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/assign_representation_styles.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/edit_presentation_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/edit_surface_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/remove_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/remove_styled_representation.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/remove_surface_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/unassign_material_style.cpython-313.pyc,, +ifcopenshell/api/style/__pycache__/unassign_representation_styles.cpython-313.pyc,, +ifcopenshell/api/style/add_style.py,sha256=Mh5StIMtPVoWi5RQ_IMfSg2Y04JXVqBMkcL9V4qF3_I,2626 +ifcopenshell/api/style/add_surface_style.py,sha256=HY7icEQowtFq_pG8l4vSLBBOAh44FNKHqvYnUym-PVs,6634 +ifcopenshell/api/style/add_surface_textures.py,sha256=mdqDtoSxU1yOTkvvrOL8UsZqjFABlQ1xHnokrBq9tBw,9536 +ifcopenshell/api/style/assign_item_style.py,sha256=Dt7CYNPPXZVBTOgsNMU9IO5Ay-Ja3_eUJlvqiCdfHWA,5407 +ifcopenshell/api/style/assign_material_style.py,sha256=m2e-M4PKmqSo2Gq6SBYxbjImnhaqDEKa6bsj9SpO7PI,10767 +ifcopenshell/api/style/assign_representation_styles.py,sha256=wBbI_ef4u3z_Nl11o0DbNrwVEXzhX-qVVvmcDgLLjJs,9830 +ifcopenshell/api/style/edit_presentation_style.py,sha256=R4Cx3FvGhCPi0NxjkluAKuKsXxMO1u5irQ7fmdjX4Bc,1679 +ifcopenshell/api/style/edit_surface_style.py,sha256=rW3mTPRNyMQXoAvtU5NsNHOVxO9FYWALlM97NUVrj_0,6056 +ifcopenshell/api/style/remove_style.py,sha256=F8wSGZMrRjmZcgGfqftOkRDEczK1wF098F5ILr9VNQg,3872 +ifcopenshell/api/style/remove_styled_representation.py,sha256=KE1L-wk6p15d8RjHYrLJybVynaoOx2VUpfHTQwVEfgE,1888 +ifcopenshell/api/style/remove_surface_style.py,sha256=6wVHUT-Go5X4KawvEyPG2h5Aljgf67gphpoUjG1O4-s,2413 +ifcopenshell/api/style/unassign_material_style.py,sha256=-TmkBYEpOAo5plODIy_7tvLj6Ak1JedFd1U3dnXpdcw,3882 +ifcopenshell/api/style/unassign_representation_styles.py,sha256=uy87hR-EWTEHibe7USOlGyIcy_1otWnNQfN1rdZsNcs,3823 +ifcopenshell/api/system/__init__.py,sha256=U-BkvmTldRJVmVf1PENlFIHpt2kACMiMXlx1wwpx2ec,1965 +ifcopenshell/api/system/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/add_port.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/add_system.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/assign_flow_control.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/assign_port.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/assign_system.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/connect_port.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/disconnect_port.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/edit_system.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/remove_system.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/unassign_flow_control.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/unassign_port.cpython-313.pyc,, +ifcopenshell/api/system/__pycache__/unassign_system.cpython-313.pyc,, +ifcopenshell/api/system/add_port.py,sha256=F5qeY--6wQDomNm4W1P5B7UMrbFnGWgLYyVWrB78n9U,2253 +ifcopenshell/api/system/add_system.py,sha256=Vqx2cKrEAkMgm2tUETtJtNtYsNAgzVoYiBey_yYE5g8,2254 +ifcopenshell/api/system/assign_flow_control.py,sha256=RtO8cYDwa87n-KTD-xfaEKq-SM5_Nc_NqueBSPKvvYo,3255 +ifcopenshell/api/system/assign_port.py,sha256=LIBRaM6WAfdZjg6eGZTSpfR5-hCB8v7OGnCyQluey4c,4412 +ifcopenshell/api/system/assign_system.py,sha256=TwIGTIg2kDu_6pfIYFkfusd-r4qeNEwkZSG4pX3QGSQ,2206 +ifcopenshell/api/system/connect_port.py,sha256=HLp89nttq7KOsZmco9gGHi4dN52nT1vodfUQRUx4nOw,9516 +ifcopenshell/api/system/disconnect_port.py,sha256=nHPy_NFpdKJt3wMgTgIrOTBxBWpC17EU15_IshG8low,3058 +ifcopenshell/api/system/edit_system.py,sha256=Xy2SrXXyu3ZanQXd4SpDeqJMvD0IPpscIDY4nKekyDg,1650 +ifcopenshell/api/system/remove_system.py,sha256=7wWlPJcpZYcCB7wpYxAd4SXCM08Qj7OVHGbi4Uvvb6A,2429 +ifcopenshell/api/system/unassign_flow_control.py,sha256=Q66ciwgQF1RJCP-RvL3ISWsJS6WK2Me_rbDBTFPwmJs,2543 +ifcopenshell/api/system/unassign_port.py,sha256=Im22RdaFEzP54lmlV6LK7VTJ_2QKzs3s2-GVRy7ctZk,3279 +ifcopenshell/api/system/unassign_system.py,sha256=-b3v_Z_y8wECaFGvhMluL9yaZu2MP72KwSCSAC6mG8s,1891 +ifcopenshell/api/type/__init__.py,sha256=5nIzool6E7RAg2RxJp9UB0hHzezMwBzUzu-X-2y_Bls,1353 +ifcopenshell/api/type/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/type/__pycache__/assign_type.cpython-313.pyc,, +ifcopenshell/api/type/__pycache__/map_type_representations.cpython-313.pyc,, +ifcopenshell/api/type/__pycache__/unassign_type.cpython-313.pyc,, +ifcopenshell/api/type/assign_type.py,sha256=sE-jg2mgwqugTbciRvN2u9cfXbYLMQheaYKLbYT5-w0,13588 +ifcopenshell/api/type/map_type_representations.py,sha256=kDh5ujZcZ129lw14dvqtFOK4KTE5wad_F3img23YpZ4,4851 +ifcopenshell/api/type/unassign_type.py,sha256=KF3vHP0KVQHYKsejmzJlcoW7-OrW0q24CC_0g5628Uc,2854 +ifcopenshell/api/unit/__init__.py,sha256=I2V_wyuboigHRZ4BCL6jMbnXomBEHHU1tJClpGUf4nQ,1900 +ifcopenshell/api/unit/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/add_context_dependent_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/add_conversion_based_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/add_derived_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/add_monetary_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/add_si_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/assign_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/edit_derived_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/edit_monetary_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/edit_named_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/remove_unit.cpython-313.pyc,, +ifcopenshell/api/unit/__pycache__/unassign_unit.cpython-313.pyc,, +ifcopenshell/api/unit/add_context_dependent_unit.py,sha256=rue0a-1QufcXgFCSTp_A7db_si9pKHP20Ip0Z2oaHNg,2750 +ifcopenshell/api/unit/add_conversion_based_unit.py,sha256=WticODyxEW535SF3SHuCDfonCGg_5pOBb17GnyYw6i8,3617 +ifcopenshell/api/unit/add_derived_unit.py,sha256=DTgYHhiuDkj29GBEf1Xdx6ONAeb0qk0r3vY9JxVo8Ts,3771 +ifcopenshell/api/unit/add_monetary_unit.py,sha256=P6vmBxyLC34bIMCUGLgZb1FagBpZIMma57l0MP6TkCo,1623 +ifcopenshell/api/unit/add_si_unit.py,sha256=eUxhx17Hgm37Qz3v6pIuyq1tZcRfbMaVsrwRLSF3DrA,2551 +ifcopenshell/api/unit/assign_unit.py,sha256=NtXbAST1xz0Uk7y1i0wS2fhxpzz6m6nrTbaj5C1SmHU,7033 +ifcopenshell/api/unit/edit_derived_unit.py,sha256=AuABtGZrMUYKl78XcTp4DzvpncLJtxUk7bNQktL5zw0,1364 +ifcopenshell/api/unit/edit_monetary_unit.py,sha256=Ha_DZwkqXcjwhr_X5Omld0gHBDfXqpYcK7XTP6QSZOc,1733 +ifcopenshell/api/unit/edit_named_unit.py,sha256=T8v57beqW6ahy8urzEL7D1xfxH13I6n0d14IYHp2V_Y,2091 +ifcopenshell/api/unit/remove_unit.py,sha256=B6kyP5Ovxy6htI9bL20dqdKfs_LCqCi56LrMZs6iALk,1783 +ifcopenshell/api/unit/unassign_unit.py,sha256=TeyqreB_d7RpGZccmcKgzdMwvYfcnLYb-3zV0OQwGr4,2099 +ifcopenshell/draw.py,sha256=eCXtgaMqoT5T_DPQXSnoW0bbIaLDwrJUJrmaQRcSBCU,29099 +ifcopenshell/entity_instance.py,sha256=CUI4QEd1EBKiuY_ohExALk1EF8SoffIIrAGrqJyGsrg,25794 +ifcopenshell/express/DocAttribute.csv,sha256=DVfYWZ7epXGuORUeyCNSH7KRtcIGO-K-RmhS-uhMCNg,321801 +ifcopenshell/express/DocDefined.csv,sha256=7aR2n31QHqy6FshzgCSL4M9FUXrDPNbZ66GFwmEPL-8,69912 +ifcopenshell/express/DocEntity.csv,sha256=rdWTzPql2hieokuk-PgvpVqD_Q_YJr5el8dbiTy1Tyg,2371594 +ifcopenshell/express/DocEntityAttributes.csv,sha256=Xhh1yeuSuNvZlwndms8PuXCIMZpWLs2Lf4RThskdTOw,19105 +ifcopenshell/express/DocEnumeration.csv,sha256=26boTMWw3tkpvikmLte5FlI1JB6S9jSarWMXygLhC28,290854 +ifcopenshell/express/DocSelect.csv,sha256=p_TcDdqPW7FRRhw3PvPF06hGJQO5nzOpPI1qo9YK1SE,43748 +ifcopenshell/express/README.md,sha256=HeBNd8tj9WM1jMnGZAqk6qoZnehU25De1B3QnwdJ4cw,1592 +ifcopenshell/express/__init__.py,sha256=ok_0mlSi5IflolT_CKCk5pFCjJWr2bQFj-RAFEbta-c,1461 +ifcopenshell/express/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/express/__pycache__/bootstrap.cpython-313.pyc,, +ifcopenshell/express/__pycache__/cat.cpython-313.pyc,, +ifcopenshell/express/__pycache__/codegen.cpython-313.pyc,, +ifcopenshell/express/__pycache__/definitions.cpython-313.pyc,, +ifcopenshell/express/__pycache__/documentation.cpython-313.pyc,, +ifcopenshell/express/__pycache__/express_parser.cpython-313.pyc,, +ifcopenshell/express/__pycache__/header.cpython-313.pyc,, +ifcopenshell/express/__pycache__/implementation.cpython-313.pyc,, +ifcopenshell/express/__pycache__/mapping.cpython-313.pyc,, +ifcopenshell/express/__pycache__/nodes.cpython-313.pyc,, +ifcopenshell/express/__pycache__/rule_compiler.cpython-313.pyc,, +ifcopenshell/express/__pycache__/rule_executor.cpython-313.pyc,, +ifcopenshell/express/__pycache__/schema.cpython-313.pyc,, +ifcopenshell/express/__pycache__/schema_class.cpython-313.pyc,, +ifcopenshell/express/__pycache__/templates.cpython-313.pyc,, +ifcopenshell/express/bootstrap.py,sha256=3OkFzE24Ci2qiJw2cB3mfG93yUelAKCeBh29ZO-Aa_I,7683 +ifcopenshell/express/cat.py,sha256=R6RugVfItVQr38N5CpLX4y6iyZduSClpS_63XkadzGw,386 +ifcopenshell/express/codegen.py,sha256=pBtpXU9fse5Px5Js7df8MPPSRUVR-CV5EQJ9ClZv5yw,1731 +ifcopenshell/express/definitions.py,sha256=A3SM3PBWmjFmavN-OPzbeyJgZ2R6_-ZMD4Dta1ztPHk,2417 +ifcopenshell/express/documentation.py,sha256=VxuUmrjlgBxUCOlfDCF2bE5IoQGv4Y7_10bzLy1h204,3350 +ifcopenshell/express/express.bnf,sha256=JLUCVG2Y5s3SQg0k1MAgGHtcetqpwq7pHKryQaiS95U,15563 +ifcopenshell/express/express_parser.py,sha256=Dribfwxfatbu4XWVjybFHhbLJg2_LXSUSQuZX-98Wpc,59214 +ifcopenshell/express/header.py,sha256=n3xu3hNJhKTDCy3WL4DjNguRad81ZTMIEHZQeTrTCA0,11671 +ifcopenshell/express/header_schema.exp,sha256=RM3-kb_x4sLZP0V1MxzIrpzk8BMKl1G9Ki8gR20t0tI,700 +ifcopenshell/express/implementation.py,sha256=2AAKSeONTk0SHYDCbkqt2aRLODwQ24SF5Rd99XmW8kM,19414 +ifcopenshell/express/mapping.py,sha256=01u7dAZDmvYOxrb2AImyRgE92-o9CQZR8FBAiWo_6-M,12240 +ifcopenshell/express/nodes.py,sha256=8Avsqza4njIymYqNK95xf0kVQ9XLBroWRdCdnLtRsWw,19770 +ifcopenshell/express/rule_compiler.py,sha256=YrqATZde306K3u9ZDB6yMf_wpc4nnvuejFcLZ1miHyY,33286 +ifcopenshell/express/rule_executor.py,sha256=U2KlZ9PVmjN8FOdjGEH2cz5I-zIBF7woBJ-BhTN-Udk,10220 +ifcopenshell/express/rules/IFC2X3.py,sha256=K0SohiJ1cjZOmgSOGra2cuLT8fIethkRj0uTGIyBrPc,380964 +ifcopenshell/express/rules/IFC4.py,sha256=2aOACYSw0ejlboRU7Y4n2E1-5yi2cKCy59uuj8Xjo8Y,603951 +ifcopenshell/express/rules/IFC4X1.py,sha256=Dt1aXjUEL1nQ17loyPxEofrtli9r_kwmosNcwqVRBiw,613378 +ifcopenshell/express/rules/IFC4X2.py,sha256=1rA_wW9B3cXbFGNUFyQxnwsqcqTt5RYSJbzR56t47H4,629874 +ifcopenshell/express/rules/IFC4X3.py,sha256=1AJx0NGUJVLEsYLSSqaBOCKPk60R9aIWwfaWAX910FM,713769 +ifcopenshell/express/rules/IFC4X3_ADD1.py,sha256=NMaFQ5OTAq-GXXPkApckZ_F2yWOq3Enn80zTLtFOpeg,714415 +ifcopenshell/express/rules/IFC4X3_ADD2.py,sha256=x-mv8Lhgtc0sm5OrK1x4LVwSiss2M-RJDZ6mIDUZ9NU,715433 +ifcopenshell/express/rules/IFC4X3_RC1.py,sha256=cx9FYwC6_tI03i2qiAvd10NTx2-EKRM3DOOAUqGBEgw,695943 +ifcopenshell/express/rules/IFC4X3_RC2.py,sha256=IBlzUvKIj6YxE7ctEah__ywL_QIKyiJw3OdGX4vXuy4,700633 +ifcopenshell/express/rules/IFC4X3_RC3.py,sha256=wZvLVs_-zqQQnKWHqT4LybvEV9bwMOZtNp1Hbvm-TLI,711297 +ifcopenshell/express/rules/IFC4X3_RC4.py,sha256=ePYLH8wqw4aF70bBraTaPPvelCEfvxBvDqEKEKLd5ks,712976 +ifcopenshell/express/rules/IFC4X3_TC1.py,sha256=-Y8loe9hure-KWEeohMXe9hpoIn8bt8mf2shHs2zyy4,711280 +ifcopenshell/express/rules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ifcopenshell/express/rules/__pycache__/IFC2X3.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X1.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X2.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X3.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X3_ADD1.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X3_ADD2.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X3_RC1.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X3_RC2.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X3_RC3.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X3_RC4.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/IFC4X3_TC1.cpython-313.pyc,, +ifcopenshell/express/rules/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/express/run.bat,sha256=W51LY9p2ys51iScvd8ancAiJ22oxS1XM3mh-IwdzuRs,8502 +ifcopenshell/express/schema.py,sha256=rjvJE-NjXFGQkrS8ZReOINeuLWH6j0pYhweHyNNDUDg,4659 +ifcopenshell/express/schema_class.py,sha256=KGrPO0Lfo7KqPIrLhOJ62IwaMQrRwJjxMpx_Kdcid-I,22467 +ifcopenshell/express/templates.py,sha256=7xgsBbmVr_rZ5SIW0631mC99GFh6DEhyJpxCIyTsh2I,12143 +ifcopenshell/express/txt/endif.txt,sha256=mjSbvRohEE8FHjSyyKnnDMf7tQvBmmd4HyoUDDhtlDg,7 +ifcopenshell/express/txt/header_ifc2x3.txt,sha256=dnzYg4fSF1IDlIjayQjruOetadcKxBu0tCvdgNUm3F0,1971 +ifcopenshell/express/txt/header_ifc4.txt,sha256=Ye1XU3AMM4Vplp9JFjA_3ULpfX2Hr3JF-QTSKcZcjYk,1971 +ifcopenshell/express/txt/header_ifc4x1.txt,sha256=iEETfAy_byX2mB5Ga9sBSTWIjKqlxTMMjf6DBo56Vcw,1971 +ifcopenshell/express/txt/header_ifc4x2.txt,sha256=WA-AKfL4xBI6Aid-nwNqPsA9zpZIyzInTE8Bv3CChLA,1971 +ifcopenshell/express/txt/header_ifc4x3_add1.txt,sha256=ajjeSseORMiXvrQiQ84spUMMzPddiONhXig3gIcXVYk,1971 +ifcopenshell/express/txt/header_ifc4x3_add2.txt,sha256=_KRsg4ywDdXkFpxEGV_QUFD9NVBUJGMYuVLDJzM4axs,1971 +ifcopenshell/express/txt/header_ifc4x3_rc1.txt,sha256=U_SvGSLzD7O7l6NSMFDNyaL477wjjXoHm6pf3486xno,1971 +ifcopenshell/express/txt/header_ifc4x3_rc2.txt,sha256=_ZFM0zmlXh6gFeEOJu5OhT1GCSQvrmi8j2ZH7muiJR0,1971 +ifcopenshell/express/txt/header_ifc4x3_tc1.txt,sha256=_aDmb6QhIWEJOYjLS9iM-WfS7J73h2ZMo9lIiZZOXOA,1971 +ifcopenshell/express/txt/ifdef_ifc4.txt,sha256=X9clEzyGIzJlNEuB9arXUI8mwSdljREYDx90yxGh_c4,17 +ifcopenshell/express/txt/ifdef_ifc4x1.txt,sha256=Lu15CK-gO-tY0B6pyEWQLZbaEKmhilfX-uFDO19IpZ4,19 +ifcopenshell/express/txt/ifndef_ifc4.txt,sha256=oIIBW7jDbE0gA4ORsUBKFO76gWdqWZR8m4nJN6le46A,18 +ifcopenshell/express/txt/ifndef_ifc4x1 - Copy.txt,sha256=3BFoyLDkC9LYH8tJd1Y-2acspFrFpchzfLl_JHV4qKg,20 +ifcopenshell/express/txt/ifndef_ifc4x1.txt,sha256=3BFoyLDkC9LYH8tJd1Y-2acspFrFpchzfLl_JHV4qKg,20 +ifcopenshell/file.py,sha256=9Xpp-4s867ZP8gpTiJVHZ_F8hSOxRetYYrGM3WUTbi8,40735 +ifcopenshell/geom/__init__.py,sha256=ise1Z5jwUwZvO1peBsAP4DMfjYWJzHkhnI0B_rILNz4,1703 +ifcopenshell/geom/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/geom/__pycache__/app.cpython-313.pyc,, +ifcopenshell/geom/__pycache__/code_editor_pane.cpython-313.pyc,, +ifcopenshell/geom/__pycache__/main.cpython-313.pyc,, +ifcopenshell/geom/__pycache__/occ_utils.cpython-313.pyc,, +ifcopenshell/geom/__pycache__/stats.cpython-313.pyc,, +ifcopenshell/geom/app.py,sha256=qvC4ZpHi2AL7c6f_yQM8Wdm7_l_2eOyDk7FMMseMs0A,25667 +ifcopenshell/geom/code_editor_pane.py,sha256=Sls04PGj41afmWVPpIfJ7vNEJfYr-SlRSV7jE1Eu-FI,6222 +ifcopenshell/geom/main.py,sha256=Zc2RKRfDqmGasVizh1EqcAehCjsIq04fxH93LiL-WE4,26923 +ifcopenshell/geom/occ_utils.py,sha256=N32WpFrPXhFu_y43mUawTeC-DnXs5MwqQRjVEbi-ytI,10347 +ifcopenshell/geom/stats.py,sha256=tiTKUZ-6NVA4cf1uMg-_r619UkE--ePG4_TWmn7mszg,7770 +ifcopenshell/guid.py,sha256=K7Lhz7CcG-Jv2g94FcIqixByCNV3zwWCJYWt2_fafY8,4368 +ifcopenshell/ifcopenshell_wrapper.py,sha256=E7AF0Sa_tJNhagDpLtZZXVuoBfS1w8nu-6Cv6-tFErg,325206 +ifcopenshell/ifcopenshell_wrapper.pyi,sha256=LCZc6WRrqV6GnRHNBdoLSKo55wbdjIfKt99YPV7_Hqw,45703 +ifcopenshell/mvd/README.md,sha256=nk0W3pE3W_b0tQ_2jYoxumGBPhENIrW2G-vQxulg5mY,3163 +ifcopenshell/mvd/__init__.py,sha256=sqPFUEcOV5-Fkk6LCRAXlkki1fW9OVYSieCJVf7Cyak,7893 +ifcopenshell/mvd/__main__.py,sha256=NjLcOUT0b1T428nRU33mLwwtVReRwAgyi_2_WG9TbB0,1057 +ifcopenshell/mvd/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/mvd/__pycache__/__main__.cpython-313.pyc,, +ifcopenshell/mvd/__pycache__/mvd.cpython-313.pyc,, +ifcopenshell/mvd/__pycache__/mvdxml_expression.cpython-313.pyc,, +ifcopenshell/mvd/__pycache__/sparql.cpython-313.pyc,, +ifcopenshell/mvd/mvd.py,sha256=wGwUSzco7vJPKnFNon2fIMdpHv1rH6Ws9aUvKzE8jTE,14893 +ifcopenshell/mvd/mvd_examples/Example-CV100.mvdxml,sha256=QgKf7HlT6FDfO0VPWifldEKy8mCDXZva3wBNlVrUQDA,10997 +ifcopenshell/mvd/mvd_examples/Example-CV104.mvdxml,sha256=cNH_FqIeYvus3tgHMVW2wmsmIm8q3H1Gcc4GbevnXGY,4609 +ifcopenshell/mvd/mvd_examples/Example-CV106.mvdxml,sha256=4OsqhCoMGnvTi_CY_MhF3EF_yUK3vdsCtGuFbPA7zSQ,5856 +ifcopenshell/mvd/mvd_examples/building.mvdxml,sha256=dCl2RbxNja3gCYfKnMwMaqaRsujg0yG82l9QTKizsT0,83148 +ifcopenshell/mvd/mvd_examples/officials/ReferenceView_V1-2.mvdxml,sha256=C26rHm2HiHQADFGh3roexxG4EVLhAjBZBg8zmrQeT7U,792777 +ifcopenshell/mvd/mvd_examples/wall_extraction.mvdxml,sha256=7X_PIsTtE40y4Lgn_w5DGMEZLkE56q0op67cCp8XxWo,10700 +ifcopenshell/mvd/mvd_examples/xset.mvdxml,sha256=ZMywvpbbsMR1XBqLkI1ARIdwDqei7l3eV6WXXIB3qVg,27163 +ifcopenshell/mvd/mvdxml_expression.py,sha256=5N43ydV0JsySRX982q7y1PxAymwccJYB3p9-zKSmm6U,1129 +ifcopenshell/mvd/sparql.py,sha256=gRhLKdbgkZfhTsrlVYUb7XJ7zqd_I-oq9xe04y2ZYn0,19082 +ifcopenshell/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ifcopenshell/requirements.txt,sha256=yBOe0D2VaVG8WW96e2xU5uuKsHFYWo8Dx-ixYBSMYVo,58 +ifcopenshell/settings.py,sha256=zLTwdhs1_4eFJZziuBVESbADP4DzSRY4OH_c3a8ZziU,1341 +ifcopenshell/simple_spf/README.md,sha256=5Zdk9VKtsAoGqX2EorQule0A8FBkTtD1_Rqph0Ziokw,1159 +ifcopenshell/simple_spf/__init__.py,sha256=vpSOMAoYo0dX0ljVl92Pdl8tS9C_nhOnj0DlxnJW8N8,544 +ifcopenshell/simple_spf/__main__.py,sha256=zGGyM9Be-I9mDE6pS7I5N3Fx5TbkrVsa1jTXRW0kEwY,1128 +ifcopenshell/simple_spf/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/simple_spf/__pycache__/__main__.cpython-313.pyc,, +ifcopenshell/simple_spf/__pycache__/ifcgraph.cpython-313.pyc,, +ifcopenshell/simple_spf/__pycache__/test_parser.cpython-313.pyc,, +ifcopenshell/simple_spf/fixtures/extended_mvd.ifc,sha256=uWBO4k8AyIJTYsw53gs6RsHJpn8SQ6L_6voq3L59zYY,1444 +ifcopenshell/simple_spf/fixtures/fail_double_comma.ifc,sha256=g96xGbSG_lg4d1b2qtgRASLIbYJjfuvJlqijnbe7idU,1141 +ifcopenshell/simple_spf/fixtures/fail_double_semi.ifc,sha256=YL2FVUZMF0JxXLv_6wWiCjqST0O2t4UXqCuYiXjw2qU,1143 +ifcopenshell/simple_spf/fixtures/fail_duplicate_id.ifc,sha256=5TMh9T38FURbhf2BvTvc5K8R_oEwcnufMX9DUaPsBzc,1142 +ifcopenshell/simple_spf/fixtures/fail_invalid_header_entity.ifc,sha256=0b__zCx8FljnMEXDysvw7c4R6upbIvZMDLv2g7fnGZ4,1790 +ifcopenshell/simple_spf/fixtures/fail_multiple_duplicate_ids.ifc,sha256=SOko99ELywiZzTMN367KfQ96-0liojOWtGs_1A1px2Y,1142 +ifcopenshell/simple_spf/fixtures/fail_multiple_wrong_header_fields.ifc,sha256=u3PP7t-cjL36VO8XXJP6v023w9GyP5bw92jBpHsSsYg,1313 +ifcopenshell/simple_spf/fixtures/fail_no_header.ifc,sha256=NvyeXUQ7H4CCsghHDp09dabHSwjcgTSZeaeKwiYqXLk,1134 +ifcopenshell/simple_spf/fixtures/fail_reverse_string.ifc,sha256=AWrD16mPaOEClRxBCZPcyagCX1-gXQIXJOdMYhBmj4g,1147 +ifcopenshell/simple_spf/fixtures/fail_too_many_header_entity_fields.ifc,sha256=-S9cZrtLkdE36h0eCPbpgbDlA9bRqzqdemVfN0My-xQ,1319 +ifcopenshell/simple_spf/fixtures/fail_utf_encoding.ifc,sha256=W4XGpWYMX-kl8VUjDBPFZ70OzWKr5DScLi4DdEfZZT4,1151 +ifcopenshell/simple_spf/fixtures/pass_1.ifc,sha256=GZm3zXQVvj5gjcZ0YqG5auYrThsPt0dKKBUv18tDsHs,1198 +ifcopenshell/simple_spf/fixtures/pass_double_reverse.ifc,sha256=7llB0Yst8EVD9yyI_G446KIdsfOTcYPFZqKavD_OG0I,1148 +ifcopenshell/simple_spf/fixtures/pass_page_encoding.ifc,sha256=YeaoJC_M7gqhTTiLpMk28b9CjuwiEwRDaUkPDq6QZwU,1150 +ifcopenshell/simple_spf/fixtures/pass_reverse_comment.ifc,sha256=qgDnQCP7BqGrwe3SluiMXrKQIRHig3PrWcDZHlzQr2Q,1166 +ifcopenshell/simple_spf/fixtures/passing_header.ifc,sha256=LE5LiR9Wrlh_1zft3uPJ-UehofBxAE0ftMQqRGMKWL4,1313 +ifcopenshell/simple_spf/ifcgraph.py,sha256=ml8Gke_sUXigU4CMqZYIbCoGWezGA_0Y4fHc6YZ1tA0,2225 +ifcopenshell/simple_spf/parser/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ifcopenshell/simple_spf/parser/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/simple_spf/parser/__pycache__/errors.cpython-313.pyc,, +ifcopenshell/simple_spf/parser/__pycache__/file.cpython-313.pyc,, +ifcopenshell/simple_spf/parser/__pycache__/grammar.cpython-313.pyc,, +ifcopenshell/simple_spf/parser/__pycache__/mvd_info.cpython-313.pyc,, +ifcopenshell/simple_spf/parser/__pycache__/parse.cpython-313.pyc,, +ifcopenshell/simple_spf/parser/__pycache__/transformer.cpython-313.pyc,, +ifcopenshell/simple_spf/parser/errors.py,sha256=l9LuH8OiupDP9NiRGfHg2NU6MFKJk9yfDKhIOtr_xMc,3801 +ifcopenshell/simple_spf/parser/file.py,sha256=FRzmYUukZjjmyQEf436ActNATXNPIg-1SLClXvQqohc,3421 +ifcopenshell/simple_spf/parser/grammar.py,sha256=AG2gjd7pmhg17vv-vNKL0vaa5nu6EdGjm-r1x0NPRXQ,3343 +ifcopenshell/simple_spf/parser/mvd_info.py,sha256=_KFM8DotbpV-B8xg1Hm21xSHMG17rqNj6eBAqlQPcM4,10472 +ifcopenshell/simple_spf/parser/parse.py,sha256=VobBzNyKTHezbXiRAO6IiOdwIfsVHsdXlIp2vde8QK8,6049 +ifcopenshell/simple_spf/parser/transformer.py,sha256=7g1CX4nPZzs8s1_RtXbshuLjb72pBzOLdQWweI8BLrQ,2345 +ifcopenshell/simple_spf/requirements.in,sha256=44yX6FLINCddnrvHfe7EJnMAsL8u5FxvvXEx_6Y9J-U,12 +ifcopenshell/simple_spf/test_parser.py,sha256=NZBbH3NakwRphOxMX1ljvEZ8nT_rk337FjxK8yCVbnY,5636 +ifcopenshell/sql.py,sha256=i_pBHvOVgHthAwwRpzZXfdhgrLP8cyleH9-ZbSmNeRo,22291 +ifcopenshell/stream.py,sha256=jRUc0UdFU4C6d1GJjQp3LRZeEU6vlXDkwD4RmMHDnFQ,18401 +ifcopenshell/template.py,sha256=vzcxfOrjiUxD_wMcwUWW4tJTfB2tmnqBefnX24DELXY,4135 +ifcopenshell/util/__init__.py,sha256=gXfClYgBnglUff4B63BE5iR6LsUd52WaaOMXDKbSvT8,2051 +ifcopenshell/util/__pycache__/__init__.cpython-313.pyc,, +ifcopenshell/util/__pycache__/alignment.cpython-313.pyc,, +ifcopenshell/util/__pycache__/attribute.cpython-313.pyc,, +ifcopenshell/util/__pycache__/brick.cpython-313.pyc,, +ifcopenshell/util/__pycache__/classification.cpython-313.pyc,, +ifcopenshell/util/__pycache__/constraint.cpython-313.pyc,, +ifcopenshell/util/__pycache__/cost.cpython-313.pyc,, +ifcopenshell/util/__pycache__/data.cpython-313.pyc,, +ifcopenshell/util/__pycache__/date.cpython-313.pyc,, +ifcopenshell/util/__pycache__/doc.cpython-313.pyc,, +ifcopenshell/util/__pycache__/element.cpython-313.pyc,, +ifcopenshell/util/__pycache__/file.cpython-313.pyc,, +ifcopenshell/util/__pycache__/fm.cpython-313.pyc,, +ifcopenshell/util/__pycache__/generate_pset_templates.cpython-313.pyc,, +ifcopenshell/util/__pycache__/geolocation.cpython-313.pyc,, +ifcopenshell/util/__pycache__/ifc4x3dev_scrape_data_for_docs.cpython-313.pyc,, +ifcopenshell/util/__pycache__/mvd_info.cpython-313.pyc,, +ifcopenshell/util/__pycache__/placement.cpython-313.pyc,, +ifcopenshell/util/__pycache__/profiler.cpython-313.pyc,, +ifcopenshell/util/__pycache__/pset.cpython-313.pyc,, +ifcopenshell/util/__pycache__/representation.cpython-313.pyc,, +ifcopenshell/util/__pycache__/resource.cpython-313.pyc,, +ifcopenshell/util/__pycache__/schema.cpython-313.pyc,, +ifcopenshell/util/__pycache__/selector.cpython-313.pyc,, +ifcopenshell/util/__pycache__/sequence.cpython-313.pyc,, +ifcopenshell/util/__pycache__/shape.cpython-313.pyc,, +ifcopenshell/util/__pycache__/shape_builder.cpython-313.pyc,, +ifcopenshell/util/__pycache__/system.cpython-313.pyc,, +ifcopenshell/util/__pycache__/type.cpython-313.pyc,, +ifcopenshell/util/__pycache__/unit.cpython-313.pyc,, +ifcopenshell/util/alignment.py,sha256=qzNBwHQ8YApbUSJKZACGhuJHhkvjzrebfRK2UmxP8h4,4257 +ifcopenshell/util/attribute.py,sha256=WgQVgYv8rsykS_Bgdzk3go1plZM0OyEIc0rYNpooFl8,3426 +ifcopenshell/util/attribute_4_to_2x3.json,sha256=KcDZjgwgq8ZtwJgNBNVfve6X95FrXva4URsYEnatbFQ,7673 +ifcopenshell/util/attribute_4x3_to_4.json,sha256=QdNB1TSH-zdyI5KZddcCSvqhjWOvo-kOYsvi3lK8fnE,709 +ifcopenshell/util/brick.py,sha256=P70oHt5WStW4NLgdFvaXKVfRDHYIK85lhHwg-MV41gY,4198 +ifcopenshell/util/class_2x3_to_4.json,sha256=JtaDcH8St14u_3ZoSvrvoLXo8m6vNRChII7IGBOy5qc,409 +ifcopenshell/util/class_4_to_2x3.json,sha256=Rcwvw7p0jLWW44KdCCmzKyhI56aTsvw3A3BUXNGLGHQ,6575 +ifcopenshell/util/classification.py,sha256=DfMRXHz0aVSzec_ygwk9FB3lzlv_In-ubB6gAvQuS_4,4253 +ifcopenshell/util/constraint.py,sha256=Hw08vuyDzbqFBRK5KSnJhzARe_P23VLdPaK6piz9Lew,3783 +ifcopenshell/util/cost.py,sha256=7xMmNbdSICXyVTKXFPQzRI-eITamPcDixWGTy4OxXMU,17987 +ifcopenshell/util/data.py,sha256=7XrDXYHUShgcRY00fJ_AEjUqDsK0yDi1yB2l8IDCJaQ,4429 +ifcopenshell/util/date.py,sha256=0ib2TiW42L0vPIG5LMtGCJbKD4kUnDwLyiP_QbkvVFc,9435 +ifcopenshell/util/doc.py,sha256=wSF2sLTBc-bLrGmxzINMAUpOJl95zyZ6njt7Pt4oglg,55887 +ifcopenshell/util/element.py,sha256=C31m4prcCJrRBTZP_OtDOpqv0-ZcBqRcII30IgXWSoo,71281 +ifcopenshell/util/entity_to_type_map_2x3.json,sha256=fRbFIIZz2Fbn4e_mraqfUw1448TpUFSNPq7DdxMJql8,10679 +ifcopenshell/util/entity_to_type_map_4.json,sha256=0MGD39UsSuJ108B02E44tvY-iqS1h1i5C46tp7Z1fHs,7953 +ifcopenshell/util/entity_to_type_map_4x3.json,sha256=BbeJ5nBCCkOKbhBiYRrza515PBeq9S5zfl-Y1uAcly8,8920 +ifcopenshell/util/file.py,sha256=8d5pHuZs5RGNeZPmL4wDGh0nRkN6u2lLOfisqfW-Q-A,4226 +ifcopenshell/util/fm.py,sha256=KsAnmuC1LR3ivofspFaO6j1QFf9Y8MP16eZl5rRNG1Q,5513 +ifcopenshell/util/generate_pset_templates.py,sha256=5nM1JBKSa0Io96KiVfFp-g8UKzWkqeiNX38OHCkCkbQ,19893 +ifcopenshell/util/geolocation.py,sha256=dTVpZ27ihvs451nMbW8svWk_bQgUWRIIgbScq43iYuE,28346 +ifcopenshell/util/ifc4_to_brick.json,sha256=0l-gq50tU-JnuiixynFIgY8CsHjBYuEA-qz3_EGmjro,1397 +ifcopenshell/util/ifc4x3dev_scrape_data_for_docs.py,sha256=il3JerQ9rDOSn2C08_fBE7-Xlgpr7nxO3xJ4-XC2O1M,8721 +ifcopenshell/util/mvd_info.py,sha256=M3S0dOdh4sfWxWCKy8tQSrBykfXmMc9sjQ_OYQ_AMRA,11150 +ifcopenshell/util/placement.py,sha256=Z69H3lIiY2iF3ij_KtVadnNi2b1YIJkE675_eTsimZA,8136 +ifcopenshell/util/profiler.py,sha256=d9889u0tYwb5vT6lmReg17J8rqsymOWczfRRvh4eMTQ,1166 +ifcopenshell/util/pset.py,sha256=ltznXodAcPZlpBzmm_126OxISC5oWfyYoJdYAKI-iDE,9943 +ifcopenshell/util/representation.py,sha256=HlxgicjgbHPqNsS6FAcURsqammGWZ6hdUN-56gYy8pI,20268 +ifcopenshell/util/resource.py,sha256=Jgw5HiL0xk9j0zhL44c2SCxYqwIVHg4LqIzMYbVYu9I,7225 +ifcopenshell/util/schema.py,sha256=Fj83vmFE7F0POJW908QCxyzXvuhEUBQgmPI-y3A9ukc,22972 +ifcopenshell/util/schema/Pset_IFC2X3.ifc,sha256=YahzL7w1xekR13UOK-DpPOdyTn7udR6aa_1x685-9Ac,613615 +ifcopenshell/util/schema/Pset_IFC4X3.ifc,sha256=QcWxgeq9VtoMKYya3rycbzruurtB8ckWhIaB95iqhFU,1435670 +ifcopenshell/util/schema/Pset_IFC4_ADD2.ifc,sha256=UiTLgr6oWtQWjkqXL-QQ0eSnJ7Va4hJ6-_L2I8Q3K7E,3153156 +ifcopenshell/util/schema/ifc2x3_entities.json,sha256=t2wbMWc1RDcKiFMhmTVZw4V3I8cLhA5B21AyeTG9JdE,586810 +ifcopenshell/util/schema/ifc2x3_properties.json,sha256=1WvTwMT38lFOR3rlSpDNknXN0jLKusVOIVeimxqvIig,419692 +ifcopenshell/util/schema/ifc2x3_property_sets_site_domains.json,sha256=B6689AtbzdfdRJDDUN-CXg24FkonmEr2G-9kjh6KkWk,19236 +ifcopenshell/util/schema/ifc2x3_types.json,sha256=MBgPAjGZkZoiPfxJZsH6tau3e4AgWOYJnfQOor5O0b4,107944 +ifcopenshell/util/schema/ifc4_entities.json,sha256=8WTenjTdSWTO5WBcy14fQeSGghNtWu0xR9j2ed8Lgu0,826405 +ifcopenshell/util/schema/ifc4_properties.json,sha256=2VM70eQl2OGK50O6_Wgw0msnv_PucQ73uQ_hAMpc6Ns,722448 +ifcopenshell/util/schema/ifc4_property_sets_site_domains.json,sha256=MsTjpuvhHYyCyJQcs9-PzTPJD6UTE5A8zfDSOCFOxKg,31303 +ifcopenshell/util/schema/ifc4_types.json,sha256=JbnEq07d8U5o1XGRqo149KWiCup2BLSooo3woQJA_Ok,137745 +ifcopenshell/util/schema/ifc4x3_entities.json,sha256=wTNMU0xDPENsERax1z6ETKgibfJ2wkcP3QWOKFM-6XY,959334 +ifcopenshell/util/schema/ifc4x3_properties.json,sha256=99GUH00IjF2rzMQ9Do5uoaFIyEWxRMIlhDNwHplFyw8,1107569 +ifcopenshell/util/schema/ifc4x3_types.json,sha256=A1GZc3F1t8wWwDJ9YaHd4Dw03jqcGmhn6UqeSYoeIr4,139659 +ifcopenshell/util/schema/ifc_classes_suggestions.json,sha256=u2omuVNZaPNbBvX26HL-UwnnkQKfIEstC2C08NW7UR8,3798 +ifcopenshell/util/scripts/__pycache__/validate_stub.cpython-313.pyc,, +ifcopenshell/util/scripts/validate_stub.py,sha256=w3FT9s2vhM8bh-GPZ5e8UPuD3gBHwqDyufT4nqNg42M,10207 +ifcopenshell/util/selector.py,sha256=xBuR2NCrL_1VyShbrGaRipCNcG74k6MClWn5WbAuKPc,47224 +ifcopenshell/util/sequence.py,sha256=HCZ8Q-HArzLQd3s_eGKXJiZY2t3Ts0Igukk7KmdMR5Y,17522 +ifcopenshell/util/shape.py,sha256=NVatj4GjZyMJ1bvqwOy5ZZbHyOEOcqsjjjvJPmEDPYI,29148 +ifcopenshell/util/shape_builder.py,sha256=CibFYK08IerZA4bQ_IoYJitxrS-kCeuo513yCMxPP7c,87191 +ifcopenshell/util/system.py,sha256=w60gkvoXxP9k68BpVUIhVAVwhJoHZL8dKYvThnK0ke4,5694 +ifcopenshell/util/type.py,sha256=YLbPJxtYq-8DiDup-tJCAjteRyjlHW8thcM1tHxYb5M,3876 +ifcopenshell/util/unit.py,sha256=uPZ63cl97W6O95-kaqpGoWDaCvKxB2VkYpWp2hsOBnE,32769 +ifcopenshell/validate.py,sha256=l0xcTtb7kMk0aLn75QFHKqsRcyDTij6T13P2YlrqCX8,33512 diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..90116865704a6db4777af5f75b879df42ed47bf0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/direct_url.json @@ -0,0 +1 @@ +{"archive_info": {"hash": "sha256=af94394224a1dab0516219ef7dd31d74b764cfee0c6ea5b35728530457e3740e", "hashes": {"sha256": "af94394224a1dab0516219ef7dd31d74b764cfee0c6ea5b35728530457e3740e"}}, "url": "file:///tmp/ifc_src/ifcopenshell-0.8.4-py313-none-manylinux_2_31_x86_64.whl"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3e3b59b2884ab89a5cd2f3d19c59f34de031145e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell-0.8.4.dist-info/top_level.txt @@ -0,0 +1 @@ +ifcopenshell diff --git a/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..05dfa36958ec7df2d25d01105c97dbc8750cadda --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/METADATA @@ -0,0 +1,61 @@ +Metadata-Version: 2.4 +Name: jaraco.classes +Version: 3.4.0 +Summary: Utility functions for Python class constructs +Home-page: https://github.com/jaraco/jaraco.classes +Author: Jason R. Coombs +Author-email: jaraco@jaraco.com +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.8 +License-File: LICENSE +Requires-Dist: more_itertools +Provides-Extra: testing +Requires-Dist: pytest>=6; extra == "testing" +Requires-Dist: pytest-checkdocs>=2.4; extra == "testing" +Requires-Dist: pytest-cov; extra == "testing" +Requires-Dist: pytest-mypy; extra == "testing" +Requires-Dist: pytest-enabler>=2.2; extra == "testing" +Requires-Dist: pytest-ruff>=0.2.1; extra == "testing" +Provides-Extra: docs +Requires-Dist: sphinx>=3.5; extra == "docs" +Requires-Dist: jaraco.packaging>=9.3; extra == "docs" +Requires-Dist: rst.linker>=1.9; extra == "docs" +Requires-Dist: furo; extra == "docs" +Requires-Dist: sphinx-lint; extra == "docs" +Requires-Dist: jaraco.tidelift>=1.4; extra == "docs" +Dynamic: license-file + +.. image:: https://img.shields.io/pypi/v/jaraco.classes.svg + :target: https://pypi.org/project/jaraco.classes + +.. image:: https://img.shields.io/pypi/pyversions/jaraco.classes.svg + +.. image:: https://github.com/jaraco/jaraco.classes/actions/workflows/main.yml/badge.svg + :target: https://github.com/jaraco/jaraco.classes/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/jaracoclasses/badge/?version=latest + :target: https://jaracoclasses.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2024-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/jaraco.classes + :target: https://tidelift.com/subscription/pkg/pypi-jaraco.classes?utm_source=pypi-jaraco.classes&utm_medium=readme + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d4da390407dfaf1e02bcdd12b8d7677728972099 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/RECORD @@ -0,0 +1,17 @@ +jaraco/classes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco/classes/__pycache__/__init__.cpython-313.pyc,, +jaraco/classes/__pycache__/ancestry.cpython-313.pyc,, +jaraco/classes/__pycache__/meta.cpython-313.pyc,, +jaraco/classes/__pycache__/properties.cpython-313.pyc,, +jaraco/classes/ancestry.py,sha256=FkU7kyOO-TOMgwR3obcpqB93Ht-f0yxjGnTxcvfBLB0,1787 +jaraco/classes/meta.py,sha256=uz1zmtse_0n7cs2M2hfz8iIqoe2_2vZI-_JiFvQuDwE,2198 +jaraco/classes/properties.py,sha256=f-88KCSBeeCliwxfXOwe7Uqk9_elEmi9ZSwOh6_yBq4,6191 +jaraco/classes/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco_classes-3.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jaraco_classes-3.4.0.dist-info/METADATA,sha256=f6sl0OIs0kbrc8WuNcRSSrXfKtxsaLSgWg2GzbZmvCQ,2625 +jaraco_classes-3.4.0.dist-info/RECORD,, +jaraco_classes-3.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaraco_classes-3.4.0.dist-info/WHEEL,sha256=lTU6B6eIfYoiQJTZNc-fyaR6BpL6ehTzU3xGYxn2n8k,91 +jaraco_classes-3.4.0.dist-info/direct_url.json,sha256=f1mNHPCJ5c3UGfzA6lB_KEdE4VWMOY-QouTozSUoitQ,74 +jaraco_classes-3.4.0.dist-info/licenses/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +jaraco_classes-3.4.0.dist-info/top_level.txt,sha256=0JnN3LfXH4LIRfXL-QFOGCJzQWZO3ELx4R1d_louoQM,7 diff --git a/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..370ec5f1aa3524bfd31a19fd21e907335f48a7f6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (78.1.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..a4cfa5138921cf6d2e0c570f8a1110b8bb108aaa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/jaraco.classes_1755516327832/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6205a5f19a533fd30f90a433e610325ff02f989 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jaraco_classes-3.4.0.dist-info/top_level.txt @@ -0,0 +1 @@ +jaraco diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/LICENSE b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0ae9dbc262b5f7ed4cb6f964cfb5eb5c0d0b0be --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Thomas Kluyver + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9a1648ad3e2062e83263fbeff7d9927e834cc91e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/METADATA @@ -0,0 +1,36 @@ +Metadata-Version: 2.1 +Name: jeepney +Version: 0.7.1 +Summary: Low-level, pure Python DBus protocol wrapper. +Home-page: https://gitlab.com/takluyver/jeepney +Author: Thomas Kluyver +Author-email: thomas@kluyver.me.uk +Requires-Python: >=3.6 +Description-Content-Type: text/x-rst +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Desktop Environment +Requires-Dist: pytest ; extra == "test" +Requires-Dist: pytest-trio ; extra == "test" +Requires-Dist: pytest-asyncio ; extra == "test" +Requires-Dist: testpath ; extra == "test" +Requires-Dist: trio ; extra == "test" +Requires-Dist: async-timeout ; extra == "test" +Requires-Dist: trio ; extra == "trio" +Requires-Dist: async_generator ; extra == "trio" and ( python_version == '3.6') +Project-URL: Documentation, https://jeepney.readthedocs.io/en/latest/ +Provides-Extra: test +Provides-Extra: trio + +Jeepney is a pure Python implementation of D-Bus messaging. It has an `I/O-free +`__ core, and integration modules for different +event loops. + +D-Bus is an inter-process communication system, mainly used in Linux. + +To install Jeepney:: + + pip install jeepney + +`Jeepney docs on Readthedocs `__ + diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..49e6a3b45dcece59e17f5be056731868231d7dbd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/RECORD @@ -0,0 +1,82 @@ +jeepney-0.7.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jeepney-0.7.1.dist-info/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081 +jeepney-0.7.1.dist-info/METADATA,sha256=uLcNS_Qm9Bb2t88yWP4SrjdH5n9pmcCWshfHemiqU3w,1273 +jeepney-0.7.1.dist-info/RECORD,, +jeepney-0.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jeepney-0.7.1.dist-info/WHEEL,sha256=o-Q2E8s7BKkCJ1EC2uQdaymZVVu2aUt1e8uTTFpzHVs,81 +jeepney-0.7.1.dist-info/direct_url.json,sha256=N6ohBFdS2iU9jGUgRmGJODgSfiiH3AaVmpZmXK_Tx8k,80 +jeepney/__init__.py,sha256=sIy2YNifElpRMfOou0FT_cQ2QL37e7yJLx_hO0Fwn9E,408 +jeepney/__pycache__/__init__.cpython-39.pyc,, +jeepney/__pycache__/auth.cpython-39.pyc,, +jeepney/__pycache__/bindgen.cpython-39.pyc,, +jeepney/__pycache__/bus.cpython-39.pyc,, +jeepney/__pycache__/bus_messages.cpython-39.pyc,, +jeepney/__pycache__/fds.cpython-39.pyc,, +jeepney/__pycache__/low_level.cpython-39.pyc,, +jeepney/__pycache__/routing.cpython-39.pyc,, +jeepney/__pycache__/wrappers.cpython-39.pyc,, +jeepney/auth.py,sha256=Dh3ntzuCc0raeIcWDM_GDALNwLqUueJM4oEHH_pCQTA,4933 +jeepney/bindgen.py,sha256=6vLI1T_7rEN98fA8CEs3qG3Lk3zJsy8M2EEv9JnDbC0,4054 +jeepney/bus.py,sha256=KUiSr3ECzdbe-S9tNKm6kvf3oZi4RYnJWkZUXK7tE2k,1817 +jeepney/bus_messages.py,sha256=naa9p0PdEAvqJ-xZ9-V37B3-7-1xfLtAabKEeTZ6oQU,8140 +jeepney/fds.py,sha256=ZYzN_c_7rkBT0wU7dYUmQRijpSzCv-DATCYEklpXxUU,5056 +jeepney/integrate/__init__.py,sha256=9QvrpFjWp0chRHlDLmgVTMbC8O4mntAd1uEEA8b8_E4,41 +jeepney/integrate/__pycache__/__init__.cpython-39.pyc,, +jeepney/integrate/__pycache__/asyncio.cpython-39.pyc,, +jeepney/integrate/__pycache__/blocking.cpython-39.pyc,, +jeepney/integrate/__pycache__/tornado.cpython-39.pyc,, +jeepney/integrate/asyncio.py,sha256=zhmlfp55_QJCL2TQysw5zZF9EuOhm7Pecy84PTzf6ks,3081 +jeepney/integrate/blocking.py,sha256=UbNu5uH9LAOgtZGAu1ZbbYxwBls_DQmuFO0oHaeZbnI,515 +jeepney/integrate/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jeepney/integrate/tests/__pycache__/__init__.cpython-39.pyc,, +jeepney/integrate/tests/__pycache__/test_asyncio.cpython-39.pyc,, +jeepney/integrate/tests/test_asyncio.py,sha256=Ak3fID9rRtB82krevCWSdRvkqLKQpFMvUv48MAbDC8c,1357 +jeepney/integrate/tornado.py,sha256=mad24L_SuS8nDMJOLrPHIxZjbFVZYSK0a5E2kyZkW4o,523 +jeepney/io/__init__.py,sha256=inJI_1U-ATymLcAVYs-LD2aUwgl-tihW8-oVFUxYRgA,33 +jeepney/io/__pycache__/__init__.cpython-39.pyc,, +jeepney/io/__pycache__/asyncio.cpython-39.pyc,, +jeepney/io/__pycache__/blocking.cpython-39.pyc,, +jeepney/io/__pycache__/common.cpython-39.pyc,, +jeepney/io/__pycache__/threading.cpython-39.pyc,, +jeepney/io/__pycache__/tornado.cpython-39.pyc,, +jeepney/io/__pycache__/trio.cpython-39.pyc,, +jeepney/io/asyncio.py,sha256=qfWi_1pWCXSP1LNRafHBuvrxHx4tX96b52KBa4sUFMc,7622 +jeepney/io/blocking.py,sha256=yK700jKxjLRrG3uzo8wTaswl7AISg80DpiqMJlR3mhQ,11967 +jeepney/io/common.py,sha256=l8lbFUgQmBxfqSC-hqHYmPUYCVFMKbOGB1k5ZWPKXfs,2696 +jeepney/io/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jeepney/io/tests/__pycache__/__init__.cpython-39.pyc,, +jeepney/io/tests/__pycache__/conftest.cpython-39.pyc,, +jeepney/io/tests/__pycache__/test_asyncio.cpython-39.pyc,, +jeepney/io/tests/__pycache__/test_blocking.cpython-39.pyc,, +jeepney/io/tests/__pycache__/test_threading.cpython-39.pyc,, +jeepney/io/tests/__pycache__/test_trio.cpython-39.pyc,, +jeepney/io/tests/__pycache__/utils.cpython-39.pyc,, +jeepney/io/tests/conftest.py,sha256=o7JrYypYE-0jNFUndsQ4Ek5dNYM0ofh1sYcIVeCZMj0,2730 +jeepney/io/tests/test_asyncio.py,sha256=dpCKz8Xwl9CKWvv2Q7pv783kNwg_5ZAR6LeL537dNR0,2598 +jeepney/io/tests/test_blocking.py,sha256=P002_n6oUrp_QIBqmzP0JpUg4P76hBqL6nCN9l6fqfA,2981 +jeepney/io/tests/test_threading.py,sha256=RALwy-aI64TBoFmBnSU63HLcwRnStLVtnewOtoaBl3o,2699 +jeepney/io/tests/test_trio.py,sha256=DPY1V_K2qLTyBTrbrxZeLTA5dmca3Ye3e6pz08UxbO8,3892 +jeepney/io/tests/utils.py,sha256=i7VJYT-axefzS8mWcvv-9DeHEB6LdP9M82H3Hx6fyC4,79 +jeepney/io/threading.py,sha256=mwGCNlun_baX8Y4eienCGDKdZD4SKdTMvBTkIE0EMKo,9391 +jeepney/io/tornado.py,sha256=h-MuinThHWVom1hfL5xrzho5chB28yM4qLi6jhsm_xw,6858 +jeepney/io/trio.py,sha256=PkvkqBXkGF3NAn1ipD8eePznq2DZ3kf_kZblt2XcK2c,14848 +jeepney/low_level.py,sha256=TkgVsLQE1bdVwa684QeIhQ8m53IjJt7_2mxTsH66JYs,19119 +jeepney/routing.py,sha256=70ujcmGyvKKPp6vUn5WLlvYwM7PFiH-XRT2upa538cg,2827 +jeepney/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jeepney/tests/__pycache__/__init__.cpython-39.pyc,, +jeepney/tests/__pycache__/test_auth.cpython-39.pyc,, +jeepney/tests/__pycache__/test_bindgen.cpython-39.pyc,, +jeepney/tests/__pycache__/test_bus.cpython-39.pyc,, +jeepney/tests/__pycache__/test_bus_messages.cpython-39.pyc,, +jeepney/tests/__pycache__/test_fds.cpython-39.pyc,, +jeepney/tests/__pycache__/test_low_level.cpython-39.pyc,, +jeepney/tests/__pycache__/test_routing.cpython-39.pyc,, +jeepney/tests/secrets_introspect.xml,sha256=9cfNs1aGLtIAykcQVsycwIwCLmEeorKkFjqJCLAknRQ,4575 +jeepney/tests/test_auth.py,sha256=Ee79vsedCwveukudAZTwqYTXHWV3PYnXkmMl0MBMZEE,611 +jeepney/tests/test_bindgen.py,sha256=Ez99zr9TIV3mlZdH-2A_dz4LbvxCqzWDIadhOCbbaoc,1098 +jeepney/tests/test_bus.py,sha256=ApOxd3AcYQB14G1XsiFGBYtQ4xSKw52y9YvmPz700gc,847 +jeepney/tests/test_bus_messages.py,sha256=Fh7Ub4sFWZbsXGqBKYoS6DM_GS1kHxTOA0ydkL5PYBo,3228 +jeepney/tests/test_fds.py,sha256=-gyvQpfsXtPaIEeqbwhrNPOcIAN0DsrQ7MXZu4nMvvQ,1821 +jeepney/tests/test_low_level.py,sha256=Ry2Fme4i9XVAFcK0CL0B_-031njsVBVQ2YnT2yEaxwM,2554 +jeepney/tests/test_routing.py,sha256=ahDksymGQz3qllB_378EvTl0IvxLBXEhBwpdWp0SZDs,959 +jeepney/wrappers.py,sha256=Tr1tJ-KbTZuDzLvjZwL2HyKlhUqhCcD4-UZDCKIEW4E,7979 diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..c71ae61dfbc9845ad7b75bb6ee7d227c7e63ad8d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.2.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..306e3c02becca85e469c72952ca8b4ab7d875611 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney-0.7.1.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///tmp/build/80754af9/jeepney_1627537048313/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/__init__.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dbb05c1e2b6f5c1d67be0847ede8231cd37b4a9f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/__init__.py @@ -0,0 +1,13 @@ +"""Low-level, pure Python DBus protocol wrapper. +""" +from .auth import AuthenticationError, FDNegotiationError +from .low_level import ( + Endianness, Header, HeaderFields, Message, MessageFlag, MessageType, + Parser, SizeLimitError, +) +from .bus import find_session_bus, find_system_bus +from .bus_messages import * +from .fds import FileDescriptor, NoFDError +from .wrappers import * + +__version__ = '0.7.1' diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/auth.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c8c549534b9e61261b93beda817d3b8bb3fc17 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/auth.py @@ -0,0 +1,136 @@ +from binascii import hexlify +from enum import Enum +import os +from typing import Optional + +def make_auth_external() -> bytes: + """Prepare an AUTH command line with the current effective user ID. + + This is the preferred authentication method for typical D-Bus connections + over a Unix domain socket. + """ + hex_uid = hexlify(str(os.geteuid()).encode('ascii')) + return b'AUTH EXTERNAL %b\r\n' % hex_uid + +def make_auth_anonymous() -> bytes: + """Format an AUTH command line for the ANONYMOUS mechanism + + Jeepney's higher-level wrappers don't currently use this mechanism, + but third-party code may choose to. + + See for details. + """ + from . import __version__ + trace = hexlify(('Jeepney %s' % __version__).encode('ascii')) + return b'AUTH ANONYMOUS %s\r\n' % trace + +BEGIN = b'BEGIN\r\n' +NEGOTIATE_UNIX_FD = b'NEGOTIATE_UNIX_FD\r\n' + +class ClientState(Enum): + # States from the D-Bus spec (plus 'Success'). Not all used in Jeepney. + WaitingForData = 1 + WaitingForOk = 2 + WaitingForReject = 3 + WaitingForAgreeUnixFD = 4 + Success = 5 + +class AuthenticationError(ValueError): + """Raised when DBus authentication fails""" + def __init__(self, data, msg="Authentication failed"): + self.msg = msg + self.data = data + + def __str__(self): + return f"{self.msg}. Bus sent: {self.data!r}" + +class FDNegotiationError(AuthenticationError): + """Raised when file descriptor support is requested but not available""" + def __init__(self, data): + super().__init__(data, msg="File descriptor support not available") + + +class Authenticator: + """Process data for the SASL authentication conversation + + If enable_fds is True, this includes negotiating support for passing + file descriptors. + """ + def __init__(self, enable_fds=False): + self.enable_fds = enable_fds + self.buffer = bytearray() + self._to_send = b'\0' + make_auth_external() + self.state = ClientState.WaitingForOk + self.error = None + + @property + def authenticated(self): + return self.state is ClientState.Success + + def __iter__(self): + return iter(self.data_to_send, None) + + def data_to_send(self) -> Optional[bytes]: + """Get a line of data to send to the server + + The data returned should be sent before waiting to receive data. + Returns empty bytes if waiting for more data from the server, and None + if authentication is finished (success or error). + + Iterating over the Authenticator object will also yield these lines; + :meth:`feed` should be called with received data inside the loop. + """ + if self.authenticated or self.error: + return None + self._to_send, to_send = b'', self._to_send + return to_send + + def process_line(self, line): + if self.state is ClientState.WaitingForOk: + if line.startswith(b'OK '): + if self.enable_fds: + return NEGOTIATE_UNIX_FD, ClientState.WaitingForAgreeUnixFD + else: + return BEGIN, ClientState.Success + # We only support EXTERNAL authentication, but if we allow others, + # 'REJECTED ' would tell us to try another one. + + elif self.state is ClientState.WaitingForAgreeUnixFD: + if line.startswith(b'AGREE_UNIX_FD'): + return BEGIN, ClientState.Success + # The protocol allows us to continue if FD passing is rejected, + # but Jeepney assumes that if you enable FD support you need it, + # so we fail rather + self.error = line + raise FDNegotiationError(line) + + self.error = line + raise AuthenticationError(line) + + def feed(self, data: bytes): + """Process received data + + Raises AuthenticationError if the incoming data is not as expected for + successful authentication. The connection should then be abandoned. + """ + self.buffer += data + if b'\r\n' in self.buffer: + line, self.buffer = self.buffer.split(b'\r\n', 1) + if self.buffer: + # We only expect one line before we reply + raise AuthenticationError(self.buffer, "Unexpected data received") + + self._to_send, self.state = self.process_line(line) + + # Avoid consuming lots of memory if the server is not sending what we + # expect. There doesn't appear to be a specified maximum line length, + # but 8192 bytes leaves a sizeable margin over all the examples in the + # spec (all < 100 bytes per line). + elif len(self.buffer) > 8192: + raise AuthenticationError( + self.buffer, "Too much data received without line ending" + ) + + +# Old name (behaviour on errors has changed, but should work for standard case) +SASLParser = Authenticator diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/bindgen.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/bindgen.py new file mode 100644 index 0000000000000000000000000000000000000000..7da6e833ffbd4118bb41b4bf5c9c3d8eb1932ffc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/bindgen.py @@ -0,0 +1,126 @@ +"""Generate a wrapper class from DBus introspection data""" +import argparse +from textwrap import indent +import xml.etree.ElementTree as ET + +from jeepney.wrappers import Introspectable +from jeepney.io.blocking import open_dbus_connection, Proxy +from jeepney import __version__ + +class Method: + def __init__(self, xml_node): + self.name = xml_node.attrib['name'] + self.in_args = [] + self.signature = [] + for arg in xml_node.findall("arg[@direction='in']"): + try: + name = arg.attrib['name'] + except KeyError: + name = 'arg{}'.format(len(self.in_args)) + self.in_args.append(name) + self.signature.append(arg.attrib['type']) + + def _make_code_noargs(self): + return ("def {name}(self):\n" + " return new_method_call(self, '{name}')\n").format( + name=self.name) + + def make_code(self): + if not self.in_args: + return self._make_code_noargs() + + args = ', '.join(self.in_args) + signature = ''.join(self.signature) + tuple = ('({},)' if len(self.in_args) == 1 else '({})').format(args) + return ("def {name}(self, {args}):\n" + " return new_method_call(self, '{name}', '{signature}',\n" + " {tuple})\n").format( + name=self.name, args=args, signature=signature, tuple=tuple + ) + +INTERFACE_CLASS_TEMPLATE = """ +class {cls_name}(MessageGenerator): + interface = {interface!r} + + def __init__(self, object_path={path!r}, + bus_name={bus_name!r}): + super().__init__(object_path=object_path, bus_name=bus_name) +""" + +class Interface: + def __init__(self, xml_node, path, bus_name): + self.name = xml_node.attrib['name'] + self.path = path + self.bus_name = bus_name + self.methods = [Method(node) for node in xml_node.findall('method')] + + def make_code(self): + cls_name = self.name.split('.')[-1] + chunks = [INTERFACE_CLASS_TEMPLATE.format(cls_name=cls_name, + interface=self.name, path=self.path, bus_name=self.bus_name)] + for method in self.methods: + chunks.append(indent(method.make_code(), ' ' * 4)) + return '\n'.join(chunks) + +MODULE_TEMPLATE = '''\ +"""Auto-generated DBus bindings + +Generated by jeepney version {version} + +Object path: {path} +Bus name : {bus_name} +""" + +from jeepney.wrappers import MessageGenerator, new_method_call + +''' + +# Jeepney already includes bindings for these common interfaces +IGNORE_INTERFACES = { + 'org.freedesktop.DBus.Introspectable', + 'org.freedesktop.DBus.Properties', + 'org.freedesktop.DBus.Peer', +} + +def code_from_xml(xml, path, bus_name, fh): + if isinstance(fh, (bytes, str)): + with open(fh, 'w') as f: + return code_from_xml(xml, path, bus_name, f) + + root = ET.fromstring(xml) + fh.write(MODULE_TEMPLATE.format(version=__version__, path=path, + bus_name=bus_name)) + + i = 0 + for interface_node in root.findall('interface'): + if interface_node.attrib['name'] in IGNORE_INTERFACES: + continue + fh.write(Interface(interface_node, path, bus_name).make_code()) + i += 1 + + return i + +def generate(path, name, output_file, bus='SESSION'): + conn = open_dbus_connection(bus) + introspectable = Proxy(Introspectable(path, name), conn) + xml, = introspectable.Introspect() + # print(xml) + + n_interfaces = code_from_xml(xml, path, name, output_file) + print("Written {} interface wrappers to {}".format(n_interfaces, output_file)) + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('-n', '--name', required=True) + ap.add_argument('-p', '--path', required=True) + ap.add_argument('--bus', default='SESSION') + ap.add_argument('-o', '--output') + args = ap.parse_args() + + output = args.output or (args.path[1:].replace('/', '_') + '.py') + + generate(args.path, args.name, output, args.bus) + + +if __name__ == '__main__': + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/bus.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/bus.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc10ee1287b1151d323cfac1a4821ccb5fb7d22 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/bus.py @@ -0,0 +1,62 @@ +import os +import re + +_escape_pat = re.compile(r'%([0-9A-Fa-f]{2})') +def unescape(v): + def repl(match): + n = int(match.group(1), base=16) + return chr(n) + return _escape_pat.sub(repl, v) + +def parse_addresses(s): + for addr in s.split(';'): + transport, info = addr.split(':', 1) + kv = {} + for x in info.split(','): + k, v = x.split('=', 1) + kv[k] = unescape(v) + yield (transport, kv) + +SUPPORTED_TRANSPORTS = ('unix',) + +def get_connectable_addresses(addr): + unsupported_transports = set() + found = False + for transport, kv in parse_addresses(addr): + if transport not in SUPPORTED_TRANSPORTS: + unsupported_transports.add(transport) + + elif transport == 'unix': + if 'abstract' in kv: + yield '\0' + kv['abstract'] + found = True + elif 'path' in kv: + yield kv['path'] + found = True + + if not found: + raise RuntimeError("DBus transports ({}) not supported. Supported: {}" + .format(unsupported_transports, SUPPORTED_TRANSPORTS)) + +def find_session_bus(): + addr = os.environ['DBUS_SESSION_BUS_ADDRESS'] + return next(get_connectable_addresses(addr)) + # TODO: fallbacks to X, filesystem + +def find_system_bus(): + addr = os.environ.get('DBUS_SYSTEM_BUS_ADDRESS', '') \ + or 'unix:path=/var/run/dbus/system_bus_socket' + return next(get_connectable_addresses(addr)) + +def get_bus(addr): + if addr == 'SESSION': + return find_session_bus() + elif addr == 'SYSTEM': + return find_system_bus() + else: + return next(get_connectable_addresses(addr)) + + +if __name__ == '__main__': + print('System bus at:', find_system_bus()) + print('Session bus at:', find_session_bus()) diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/bus_messages.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/bus_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..9245d19cda40054d96e40443cfa0fc12864c3dc4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/bus_messages.py @@ -0,0 +1,235 @@ +"""Messages for talking to the DBus daemon itself + +Generated by jeepney.bindgen and modified by hand. +""" +from .low_level import Message, MessageType, HeaderFields +from .wrappers import MessageGenerator, new_method_call + +__all__ = [ + 'DBusNameFlags', + 'DBus', + 'message_bus', + 'Monitoring', + 'Stats', + 'MatchRule', +] + +class DBusNameFlags: + allow_replacement = 1 + replace_existing = 2 + do_not_queue = 4 + +class DBus(MessageGenerator): + """Messages to talk to the message bus + """ + interface = 'org.freedesktop.DBus' + + def __init__(self, object_path='/org/freedesktop/DBus', + bus_name='org.freedesktop.DBus'): + super().__init__(object_path=object_path, bus_name=bus_name) + + def Hello(self): + return new_method_call(self, 'Hello') + + def RequestName(self, name, flags=0): + return new_method_call(self, 'RequestName', 'su', (name, flags)) + + def ReleaseName(self, name): + return new_method_call(self, 'ReleaseName', 's', (name,)) + + def StartServiceByName(self, name): + return new_method_call(self, 'StartServiceByName', 'su', + (name, 0)) + + def UpdateActivationEnvironment(self, env): + return new_method_call(self, 'UpdateActivationEnvironment', 'a{ss}', + (env,)) + + def NameHasOwner(self, name): + return new_method_call(self, 'NameHasOwner', 's', (name,)) + + def ListNames(self): + return new_method_call(self, 'ListNames') + + def ListActivatableNames(self): + return new_method_call(self, 'ListActivatableNames') + + def AddMatch(self, rule): + """*rule* can be a str or a :class:`MatchRule` instance""" + if isinstance(rule, MatchRule): + rule = rule.serialise() + return new_method_call(self, 'AddMatch', 's', (rule,)) + + def RemoveMatch(self, rule): + if isinstance(rule, MatchRule): + rule = rule.serialise() + return new_method_call(self, 'RemoveMatch', 's', (rule,)) + + def GetNameOwner(self, name): + return new_method_call(self, 'GetNameOwner', 's', (name,)) + + def ListQueuedOwners(self, name): + return new_method_call(self, 'ListQueuedOwners', 's', (name,)) + + def GetConnectionUnixUser(self, name): + return new_method_call(self, 'GetConnectionUnixUser', 's', (name,)) + + def GetConnectionUnixProcessID(self, name): + return new_method_call(self, 'GetConnectionUnixProcessID', 's', (name,)) + + def GetAdtAuditSessionData(self, name): + return new_method_call(self, 'GetAdtAuditSessionData', 's', (name,)) + + def GetConnectionSELinuxSecurityContext(self, name): + return new_method_call(self, 'GetConnectionSELinuxSecurityContext', 's', + (name,)) + + def ReloadConfig(self): + return new_method_call(self, 'ReloadConfig') + + def GetId(self): + return new_method_call(self, 'GetId') + + def GetConnectionCredentials(self, name): + return new_method_call(self, 'GetConnectionCredentials', 's', (name,)) + +message_bus = DBus() + +class Monitoring(MessageGenerator): + interface = 'org.freedesktop.DBus.Monitoring' + + def __init__(self, object_path='/org/freedesktop/DBus', + bus_name='org.freedesktop.DBus'): + super().__init__(object_path=object_path, bus_name=bus_name) + + def BecomeMonitor(self, rules): + """Convert this connection to a monitor connection (advanced)""" + return new_method_call(self, 'BecomeMonitor', 'asu', (rules, 0)) + +class Stats(MessageGenerator): + interface = 'org.freedesktop.DBus.Debug.Stats' + + def __init__(self, object_path='/org/freedesktop/DBus', + bus_name='org.freedesktop.DBus'): + super().__init__(object_path=object_path, bus_name=bus_name) + + def GetStats(self): + return new_method_call(self, 'GetStats') + + def GetConnectionStats(self, arg0): + return new_method_call(self, 'GetConnectionStats', 's', + (arg0,)) + + def GetAllMatchRules(self): + return new_method_call(self, 'GetAllMatchRules') + + +class MatchRule: + """Construct a match rule to subscribe to DBus messages. + + e.g.:: + + mr = MatchRule( + interface='org.freedesktop.DBus', + member='NameOwnerChanged', + type='signal' + ) + msg = message_bus.AddMatch(mr) + # Send this message to subscribe to the signal + """ + def __init__(self, *, type=None, sender=None, interface=None, member=None, + path=None, path_namespace=None, destination=None, + eavesdrop=False): + if isinstance(type, str): + type = MessageType[type] + self.message_type = type + fields = { + 'sender': sender, + 'interface': interface, + 'member': member, + 'path': path, + 'destination': destination, + } + self.header_fields = { + k: v for (k, v) in fields.items() if (v is not None) + } + self.path_namespace = path_namespace + self.eavesdrop = eavesdrop + self.arg_conditions = {} + + def add_arg_condition(self, argno: int, value: str, kind='string'): + """Add a condition for a particular argument + + argno: int, 0-63 + kind: 'string', 'path', 'namespace' + """ + if kind not in {'string', 'path', 'namespace'}: + raise ValueError("kind={!r}".format(kind)) + if kind == 'namespace' and argno != 0: + raise ValueError("argno must be 0 for kind='namespace'") + self.arg_conditions[argno] = (value, kind) + + def serialise(self) -> str: + """Convert to a string to use in an AddMatch call to the message bus""" + pairs = list(self.header_fields.items()) + + if self.message_type: + pairs.append(('type', self.message_type.name)) + + if self.eavesdrop: + pairs.append(('eavesdrop', 'true')) + + for argno, (val, kind) in self.arg_conditions.items(): + if kind == 'string': + kind = '' + pairs.append((f'arg{argno}{kind}', val)) + + # Quoting rules: single quotes ('') needed if the value contains a comma. + # A literal ' can only be represented outside single quotes, by + # backslash-escaping it. No escaping inside the quotes. + # The simplest way to handle this is to use '' around every value, and + # use '\'' (end quote, escaped ', restart quote) for literal ' . + return ','.join( + "{}='{}'".format(k, v.replace("'", r"'\''")) for (k, v) in pairs + ) + + def matches(self, msg: Message) -> bool: + """Returns True if msg matches this rule""" + h = msg.header + if (self.message_type is not None) and h.message_type != self.message_type: + return False + + for field, expected in self.header_fields.items(): + if h.fields.get(HeaderFields[field], None) != expected: + return False + + if self.path_namespace is not None: + path = h.fields.get(HeaderFields.path, '\0') + path_ns = self.path_namespace.rstrip('/') + if not ((path == path_ns) or path.startswith(path_ns + '/')): + return False + + for argno, (expected, kind) in self.arg_conditions.items(): + if argno >= len(msg.body): + return False + arg = msg.body[argno] + if not isinstance(arg, str): + return False + if kind == 'string': + if arg != expected: + return False + elif kind == 'path': + if not ( + (arg == expected) + or (expected.endswith('/') and arg.startswith(expected)) + or (arg.endswith('/') and expected.startswith(arg)) + ): + return False + elif kind == 'namespace': + if not ( + (arg == expected) + or arg.startswith(expected + '.') + ): + return False + + return True diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/fds.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/fds.py new file mode 100644 index 0000000000000000000000000000000000000000..233c3aa996f635f1175b1428eb476a715e6bcd1c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/fds.py @@ -0,0 +1,158 @@ +import array +import os +import socket +from warnings import warn + + +class NoFDError(RuntimeError): + """Raised by :class:`FileDescriptor` methods if it was already closed/converted + """ + pass + + +class FileDescriptor: + """A file descriptor received in a D-Bus message + + This wrapper helps ensure that the file descriptor is closed exactly once. + If you don't explicitly convert or close the FileDescriptor object, it will + close its file descriptor when it goes out of scope, and emit a + ResourceWarning. + """ + __slots__ = ('_fd',) + _CLOSED = -1 + _CONVERTED = -2 + + def __init__(self, fd): + self._fd = fd + + def __repr__(self): + detail = self._fd + if self._fd == self._CLOSED: + detail = 'closed' + elif self._fd == self._CONVERTED: + detail = 'converted' + return f"" + + def close(self): + """Close the file descriptor + + This can safely be called multiple times, but will raise RuntimeError + if called after converting it with one of the ``to_*`` methods. + + This object can also be used in a ``with`` block, to close it on + leaving the block. + """ + if self._fd == self._CLOSED: + pass + elif self._fd == self._CONVERTED: + raise NoFDError("Can't close FileDescriptor after converting it") + else: + self._fd, fd = self._CLOSED, self._fd + os.close(fd) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self): + if self._fd >= 0: + warn( + f'FileDescriptor ({self._fd}) was neither closed nor converted', + ResourceWarning, stacklevel=2, source=self + ) + self.close() + + def _check(self): + if self._fd < 0: + detail = 'closed' if self._fd == self._CLOSED else 'converted' + raise NoFDError(f'FileDescriptor object was already {detail}') + + def fileno(self): + """Get the integer file descriptor + + This does not change the state of the :class:`FileDescriptor` object, + unlike the ``to_*`` methods. + """ + self._check() + return self._fd + + def to_raw_fd(self): + """Convert to the low-level integer file descriptor:: + + raw_fd = fd.to_raw_fd() + os.write(raw_fd, b'xyz') + os.close(raw_fd) + + The :class:`FileDescriptor` can't be used after calling this. The caller + is responsible for closing the file descriptor. + """ + self._check() + self._fd, fd = self._CONVERTED, self._fd + return fd + + def to_file(self, mode, buffering=-1, encoding=None, errors=None, newline=None): + """Convert to a Python file object:: + + with fd.to_file('w') as f: + f.write('xyz') + + The arguments are the same as for the builtin :func:`open` function. + + The :class:`FileDescriptor` can't be used after calling this. Closing + the file object will also close the file descriptor. + """ + self._check() + f = open( + self._fd, mode, buffering=buffering, + encoding=encoding, errors=errors, newline=newline + ) + self._fd = self._CONVERTED + return f + + def to_socket(self): + """Convert to a socket object + + This returns a standard library :func:`socket.socket` object:: + + with fd.to_socket() as sock: + b = sock.sendall(b'xyz') + + The wrapper object can't be used after calling this. Closing the socket + object will also close the file descriptor. + """ + from socket import socket + + self._check() + s = socket(fileno=self._fd) + self._fd = self._CONVERTED + return s + + @classmethod + def from_ancdata(cls, ancdata) -> ['FileDescriptor']: + """Make a list of FileDescriptor from received file descriptors + + ancdata is a list of ancillary data tuples as returned by socket.recvmsg() + """ + fds = array.array("i") # Array of ints + for cmsg_level, cmsg_type, data in ancdata: + if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS: + # Append data, ignoring any truncated integers at the end. + fds.frombytes(data[:len(data) - (len(data) % fds.itemsize)]) + return [cls(i) for i in fds] + + +_fds_buf_size_cache = None + +def fds_buf_size(): + # If there may be file descriptors, we try to read 1 message at a time. + # The reference implementation of D-Bus defaults to allowing 16 FDs per + # message, and the Linux kernel currently allows 253 FDs per sendmsg() + # call. So hopefully allowing 256 FDs per recvmsg() will always suffice. + global _fds_buf_size_cache + if _fds_buf_size_cache is None: + maxfds = 256 + fd_size = array.array('i').itemsize + _fds_buf_size_cache = socket.CMSG_SPACE(maxfds * fd_size) + return _fds_buf_size_cache diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/low_level.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/low_level.py new file mode 100644 index 0000000000000000000000000000000000000000..cd6de316c7e169ceffa7cc1f2dcacd7b9a086262 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/low_level.py @@ -0,0 +1,585 @@ +from collections import deque +from enum import Enum, IntEnum, IntFlag +import struct +from typing import Optional + +class SizeLimitError(ValueError): + """Raised when trying to (de-)serialise data exceeding D-Bus' size limit. + + This is currently only implemented for arrays, where the maximum size is + 64 MiB. + """ + pass + +class Endianness(Enum): + little = 1 + big = 2 + + def struct_code(self): + return '<' if (self is Endianness.little) else '>' + + def dbus_code(self): + return b'l' if (self is Endianness.little) else b'B' + + +endian_map = {b'l': Endianness.little, b'B': Endianness.big} + + +class MessageType(Enum): + method_call = 1 + method_return = 2 + error = 3 + signal = 4 + + +class MessageFlag(IntFlag): + no_reply_expected = 1 + no_auto_start = 2 + allow_interactive_authorization = 4 + + +class HeaderFields(IntEnum): + path = 1 + interface = 2 + member = 3 + error_name = 4 + reply_serial = 5 + destination = 6 + sender = 7 + signature = 8 + unix_fds = 9 + + +def padding(pos, step): + pad = step - (pos % step) + if pad == step: + return 0 + return pad + + +class FixedType: + def __init__(self, size, struct_code): + self.size = self.alignment = size + self.struct_code = struct_code + + def parse_data(self, buf, pos, endianness, fds=()): + pos += padding(pos, self.alignment) + code = endianness.struct_code() + self.struct_code + val = struct.unpack(code, buf[pos:pos + self.size])[0] + return val, pos + self.size + + def serialise(self, data, pos, endianness, fds=None): + pad = b'\0' * padding(pos, self.alignment) + code = endianness.struct_code() + self.struct_code + return pad + struct.pack(code, data) + + def __repr__(self): + return 'FixedType({!r}, {!r})'.format(self.size, self.struct_code) + + def __eq__(self, other): + return (type(other) is FixedType) and (self.size == other.size) \ + and (self.struct_code == other.struct_code) + + +class Boolean(FixedType): + def __init__(self): + super().__init__(4, 'I') # D-Bus booleans take 4 bytes + + def parse_data(self, buf, pos, endianness, fds=()): + val, new_pos = super().parse_data(buf, pos, endianness) + return bool(val), new_pos + + def __repr__(self): + return 'Boolean()' + + def __eq__(self, other): + return type(other) is Boolean + + +class FileDescriptor(FixedType): + def __init__(self): + super().__init__(4, 'I') + + def parse_data(self, buf, pos, endianness, fds=()): + idx, new_pos = super().parse_data(buf, pos, endianness) + return fds[idx], new_pos + + def serialise(self, data, pos, endianness, fds=None): + if fds is None: + raise RuntimeError("Sending FDs is not supported or not enabled") + + if hasattr(data, 'fileno'): + data = data.fileno() + if isinstance(data, bool) or not isinstance(data, int): + raise TypeError("Cannot use {data!r} as file descriptor. Expected " + "an int or an object with fileno() method") + + if data < 0: + raise ValueError(f"File descriptor can't be negative ({data})") + + fds.append(data) + return super().serialise(len(fds) - 1, pos, endianness) + + def __repr__(self): + return 'FileDescriptor()' + + def __eq__(self, other): + return type(other) is FileDescriptor + + +simple_types = { + 'y': FixedType(1, 'B'), # unsigned 8 bit + 'n': FixedType(2, 'h'), # signed 16 bit + 'q': FixedType(2, 'H'), # unsigned 16 bit + 'b': Boolean(), # bool (32-bit) + 'i': FixedType(4, 'i'), # signed 32-bit + 'u': FixedType(4, 'I'), # unsigned 32-bit + 'x': FixedType(8, 'q'), # signed 64-bit + 't': FixedType(8, 'Q'), # unsigned 64-bit + 'd': FixedType(8, 'd'), # double + 'h': FileDescriptor(), # file descriptor (uint32 index in a separate list) +} + + +class StringType: + def __init__(self, length_type): + self.length_type = length_type + + @property + def alignment(self): + return self.length_type.size + + def parse_data(self, buf, pos, endianness, fds=()): + length, pos = self.length_type.parse_data(buf, pos, endianness) + end = pos + length + val = buf[pos:end].decode('utf-8') + assert buf[end:end + 1] == b'\0' + return val, end + 1 + + def serialise(self, data, pos, endianness, fds=None): + if not isinstance(data, str): + raise TypeError("Expected str, not {!r}".format(data)) + encoded = data.encode('utf-8') + len_data = self.length_type.serialise(len(encoded), pos, endianness) + return len_data + encoded + b'\0' + + def __repr__(self): + return 'StringType({!r})'.format(self.length_type) + + def __eq__(self, other): + return (type(other) is StringType) \ + and (self.length_type == other.length_type) + + +simple_types.update({ + 's': StringType(simple_types['u']), # String + 'o': StringType(simple_types['u']), # Object path + 'g': StringType(simple_types['y']), # Signature +}) + + +class Struct: + alignment = 8 + + def __init__(self, fields): + if any(isinstance(f, DictEntry) for f in fields): + raise TypeError("Found dict entry outside array") + self.fields = fields + + def parse_data(self, buf, pos, endianness, fds=()): + pos += padding(pos, 8) + res = [] + for field in self.fields: + v, pos = field.parse_data(buf, pos, endianness, fds=fds) + res.append(v) + return tuple(res), pos + + def serialise(self, data, pos, endianness, fds=None): + if not isinstance(data, tuple): + raise TypeError("Expected tuple, not {!r}".format(data)) + if len(data) != len(self.fields): + raise ValueError("{} entries for {} fields".format( + len(data), len(self.fields) + )) + pad = b'\0' * padding(pos, self.alignment) + pos += len(pad) + res_pieces = [] + for item, field in zip(data, self.fields): + res_pieces.append(field.serialise(item, pos, endianness, fds=fds)) + pos += len(res_pieces[-1]) + return pad + b''.join(res_pieces) + + def __repr__(self): + return "{}({!r})".format(type(self).__name__, self.fields) + + def __eq__(self, other): + return (type(other) is type(self)) and (self.fields == other.fields) + + +class DictEntry(Struct): + def __init__(self, fields): + if len(fields) != 2: + raise TypeError( + "Dict entry must have 2 fields, not %d" % len(fields)) + if not isinstance(fields[0], (FixedType, StringType)): + raise TypeError( + "First field in dict entry must be simple type, not {}" + .format(type(fields[0]))) + super().__init__(fields) + +class Array: + alignment = 4 + length_type = FixedType(4, 'I') + + def __init__(self, elt_type): + self.elt_type = elt_type + + def parse_data(self, buf, pos, endianness, fds=()): + # print('Array start', pos) + length, pos = self.length_type.parse_data(buf, pos, endianness) + pos += padding(pos, self.elt_type.alignment) + end = pos + length + if self.elt_type == simple_types['y']: # Array of bytes + return buf[pos:end], end + + res = [] + while pos < end: + # print('Array elem', pos) + v, pos = self.elt_type.parse_data(buf, pos, endianness, fds=fds) + res.append(v) + if isinstance(self.elt_type, DictEntry): + # Convert list of 2-tuples to dict + res = dict(res) + return res, pos + + def serialise(self, data, pos, endianness, fds=None): + data_is_bytes = False + if isinstance(self.elt_type, DictEntry) and isinstance(data, dict): + data = data.items() + elif (self.elt_type == simple_types['y']) and isinstance(data, bytes): + data_is_bytes = True + elif not isinstance(data, list): + raise TypeError("Not suitable for array: {!r}".format(data)) + + # Fail fast if we know in advance that the data is too big: + if isinstance(self.elt_type, FixedType): + if (self.elt_type.size * len(data)) > 2**26: + raise SizeLimitError("Array size exceeds 64 MiB limit") + + pad1 = padding(pos, self.alignment) + pos_after_length = pos + pad1 + 4 + pad2 = padding(pos_after_length, self.elt_type.alignment) + + if data_is_bytes: + buf = data + else: + data_pos = pos_after_length + pad2 + limit_pos = data_pos + 2 ** 26 + chunks = [] + for item in data: + chunks.append(self.elt_type.serialise( + item, data_pos, endianness, fds=fds + )) + data_pos += len(chunks[-1]) + if data_pos > limit_pos: + raise SizeLimitError("Array size exceeds 64 MiB limit") + buf = b''.join(chunks) + + len_data = self.length_type.serialise(len(buf), pos+pad1, endianness) + # print('Array ser: pad1={!r}, len_data={!r}, pad2={!r}, buf={!r}'.format( + # pad1, len_data, pad2, buf)) + return (b'\0' * pad1) + len_data + (b'\0' * pad2) + buf + + def __repr__(self): + return 'Array({!r})'.format(self.elt_type) + + def __eq__(self, other): + return (type(other) is Array) and (self.elt_type == other.elt_type) + + +class Variant: + alignment = 1 + + def parse_data(self, buf, pos, endianness, fds=()): + # print('variant', pos) + sig, pos = simple_types['g'].parse_data(buf, pos, endianness) + # print('variant sig:', repr(sig), pos) + valtype = parse_signature(list(sig)) + val, pos = valtype.parse_data(buf, pos, endianness, fds=fds) + # print('variant done', (sig, val), pos) + return (sig, val), pos + + def serialise(self, data, pos, endianness, fds=None): + sig, data = data + valtype = parse_signature(list(sig)) + sig_buf = simple_types['g'].serialise(sig, pos, endianness) + return sig_buf + valtype.serialise( + data, pos + len(sig_buf), endianness, fds=fds + ) + + def __repr__(self): + return 'Variant()' + + def __eq__(self, other): + return type(other) is Variant + +def parse_signature(sig): + """Parse a symbolic signature into objects. + """ + # Based on http://norvig.com/lispy.html + token = sig.pop(0) + if token == 'a': + return Array(parse_signature(sig)) + if token == 'v': + return Variant() + elif token == '(': + fields = [] + while sig[0] != ')': + fields.append(parse_signature(sig)) + sig.pop(0) # ) + return Struct(fields) + elif token == '{': + de = [] + while sig[0] != '}': + de.append(parse_signature(sig)) + sig.pop(0) # } + return DictEntry(de) + elif token in ')}': + raise ValueError('Unexpected end of struct') + else: + return simple_types[token] + + +def calc_msg_size(buf): + endian, = struct.unpack('c', buf[:1]) + endian = endian_map[endian] + body_length, = struct.unpack(endian.struct_code() + 'I', buf[4:8]) + fields_array_len, = struct.unpack(endian.struct_code() + 'I', buf[12:16]) + header_len = 16 + fields_array_len + return header_len + padding(header_len, 8) + body_length + + +_header_fields_type = Array(Struct([simple_types['y'], Variant()])) + + +def parse_header_fields(buf, endianness): + l, pos = _header_fields_type.parse_data(buf, 12, endianness) + return {HeaderFields(k): v[1] for (k, v) in l}, pos + + +header_field_codes = { + 1: 'o', + 2: 's', + 3: 's', + 4: 's', + 5: 'u', + 6: 's', + 7: 's', + 8: 'g', + 9: 'u', +} + + +def serialise_header_fields(d, endianness): + l = [(i.value, (header_field_codes[i], v)) for (i, v) in sorted(d.items())] + return _header_fields_type.serialise(l, 12, endianness) + + +class Header: + def __init__(self, endianness, message_type, flags, protocol_version, + body_length, serial, fields): + """A D-Bus message header + + It's not normally necessary to construct this directly: use higher level + functions and methods instead. + """ + self.endianness = endianness + self.message_type = MessageType(message_type) + self.flags = MessageFlag(flags) + self.protocol_version = protocol_version + self.body_length = body_length + self.serial = serial + self.fields = fields + + def __repr__(self): + return 'Header({!r}, {!r}, {!r}, {!r}, {!r}, {!r}, fields={!r})'.format( + self.endianness, self.message_type, self.flags, + self.protocol_version, self.body_length, self.serial, self.fields) + + def serialise(self, serial=None): + s = self.endianness.struct_code() + 'cBBBII' + if serial is None: + serial = self.serial + return struct.pack(s, self.endianness.dbus_code(), + self.message_type.value, self.flags, + self.protocol_version, + self.body_length, serial) \ + + serialise_header_fields(self.fields, self.endianness) + + @classmethod + def from_buffer(cls, buf): + endian, msgtype, flags, pv = struct.unpack('cBBB', buf[:4]) + endian = endian_map[endian] + bodylen, serial = struct.unpack(endian.struct_code() + 'II', buf[4:12]) + fields, pos = parse_header_fields(buf, endian) + return cls(endian, msgtype, flags, pv, bodylen, serial, fields), pos + + +class Message: + """Object representing a DBus message. + + It's not normally necessary to construct this directly: use higher level + functions and methods instead. + """ + def __init__(self, header, body): + self.header = header + self.body = body + + def __repr__(self): + return "{}({!r}, {!r})".format(type(self).__name__, self.header, self.body) + + @classmethod + def from_buffer(cls, buf: bytes, fds=()) -> 'Message': + header, pos = Header.from_buffer(buf) + n_fds = header.fields.get(HeaderFields.unix_fds, 0) + if n_fds > len(fds): + raise ValueError( + f"Message expects {n_fds} FDs, but only {len(fds)} were received" + ) + fds = fds[:n_fds] + body = () + if HeaderFields.signature in header.fields: + sig = header.fields[HeaderFields.signature] + body_type = parse_signature(list('(%s)' % sig)) + body = body_type.parse_data(buf, pos, header.endianness, fds=fds)[0] + return Message(header, body) + + def serialise(self, serial=None, fds=None) -> bytes: + """Convert this message to bytes. + + Specifying *serial* overrides the ``msg.header.serial`` field, so a + connection can use its own serial number without modifying the message. + + If file-descriptor support is in use, *fds* should be a + :class:`array.array` object with type ``'i'``. Any file descriptors in + the message will be added to the array. If the message contains FDs, + it can't be serialised without this array. + """ + endian = self.header.endianness + + if HeaderFields.signature in self.header.fields: + sig = self.header.fields[HeaderFields.signature] + body_type = parse_signature(list('(%s)' % sig)) + body_buf = body_type.serialise(self.body, 0, endian, fds=fds) + else: + body_buf = b'' + + self.header.body_length = len(body_buf) + if fds: + self.header.fields[HeaderFields.unix_fds] = len(fds) + + header_buf = self.header.serialise(serial=serial) + pad = b'\0' * padding(len(header_buf), 8) + return header_buf + pad + body_buf + + +class Parser: + """Parse DBus messages from a stream of incoming data. + """ + def __init__(self): + self.buf = BufferPipe() + self.fds = [] + self.next_msg_size = None + + def add_data(self, data: bytes, fds=()): + """Provide newly received data to the parser""" + self.buf.write(data) + self.fds.extend(fds) + + def feed(self, data): + """Feed the parser newly read data. + + Returns a list of messages completed by the new data. + """ + self.add_data(data) + return list(iter(self.get_next_message, None)) + + def bytes_desired(self): + """How many bytes can be received without going beyond the next message? + + This is only used with file-descriptor passing, so we don't get too many + FDs in a single recvmsg call. + """ + got = self.buf.bytes_buffered + if got < 16: # The first 16 bytes tell us the message size + return 16 - got + + if self.next_msg_size is None: + self.next_msg_size = calc_msg_size(self.buf.peek(16)) + return self.next_msg_size - got + + def get_next_message(self) -> Optional[Message]: + """Parse one message, if there is enough data. + + Returns None if it doesn't have a complete message. + """ + if self.next_msg_size is None: + if self.buf.bytes_buffered >= 16: + self.next_msg_size = calc_msg_size(self.buf.peek(16)) + nms = self.next_msg_size + if (nms is not None) and self.buf.bytes_buffered >= nms: + raw_msg = self.buf.read(nms) + msg = Message.from_buffer(raw_msg, fds=self.fds) + self.next_msg_size = None + fds_consumed = msg.header.fields.get(HeaderFields.unix_fds, 0) + self.fds = self.fds[fds_consumed:] + return msg + + +class BufferPipe: + """A place to store received data until we can parse a complete message + + The main difference from io.BytesIO is that read & write operate at + opposite ends, like a pipe. + """ + def __init__(self): + self.chunks = deque() + self.bytes_buffered = 0 + + def write(self, b: bytes): + self.chunks.append(b) + self.bytes_buffered += len(b) + + def _peek_iter(self, nbytes: int): + assert nbytes <= self.bytes_buffered + for chunk in self.chunks: + chunk = chunk[:nbytes] + nbytes -= len(chunk) + yield chunk + if nbytes <= 0: + break + + def peek(self, nbytes: int) -> bytes: + """Get exactly nbytes bytes from the front without removing them""" + return b''.join(self._peek_iter(nbytes)) + + def _read_iter(self, nbytes: int): + assert nbytes <= self.bytes_buffered + while True: + chunk = self.chunks.popleft() + self.bytes_buffered -= len(chunk) + if nbytes <= len(chunk): + break + nbytes -= len(chunk) + yield chunk + + # Final chunk + chunk, rem = chunk[:nbytes], chunk[nbytes:] + if rem: + self.chunks.appendleft(rem) + self.bytes_buffered += len(rem) + yield chunk + + def read(self, nbytes: int) -> bytes: + """Take & return exactly nbytes bytes from the front""" + return b''.join(self._read_iter(nbytes)) diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/routing.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/routing.py new file mode 100644 index 0000000000000000000000000000000000000000..64d3a5009273def78438671d607acfb68cec0f3e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/routing.py @@ -0,0 +1,76 @@ +from warnings import warn + +from .low_level import MessageType, HeaderFields +from .wrappers import DBusErrorResponse + +class Router: + """Routing for messages coming back to a client application. + + :param handle_factory: Constructor for an object like asyncio.Future, + with methods *set_result* and *set_exception*. Outgoing method call + messages will get a handle associated with them. + :param on_unhandled: Callback for messages not otherwise dispatched. + """ + def __init__(self, handle_factory, on_unhandled=None): + self.handle_factory = handle_factory + self._on_unhandled = on_unhandled + self.outgoing_serial = 0 + self.awaiting_reply = {} + self.signal_callbacks = {} + + @property + def on_unhandled(self): + return self._on_unhandled + + @on_unhandled.setter + def on_unhandled(self, value): + warn("Setting on_unhandled is deprecated. Please use the filter() " + "method or simple receive() calls instead.", stacklevel=2) + self._on_unhandled = value + + def outgoing(self, msg): + """Set the serial number in the message & make a handle if a method call + """ + self.outgoing_serial += 1 + msg.header.serial = self.outgoing_serial + + if msg.header.message_type is MessageType.method_call: + self.awaiting_reply[msg.header.serial] = handle = self.handle_factory() + return handle + + def subscribe_signal(self, callback, path, interface, member): + """Add a callback for a signal. + """ + warn("The subscribe_signal() method is deprecated. " + "Please use the filter() API instead.", stacklevel=2) + self.signal_callbacks[(path, interface, member)] = callback + + def incoming(self, msg): + """Route an incoming message. + """ + hdr = msg.header + + # Signals: + if hdr.message_type is MessageType.signal: + key = (hdr.fields.get(HeaderFields.path, None), + hdr.fields.get(HeaderFields.interface, None), + hdr.fields.get(HeaderFields.member, None) + ) + cb = self.signal_callbacks.get(key, None) + if cb is not None: + cb(msg.body) + return + + # Method returns & errors + reply_serial = hdr.fields.get(HeaderFields.reply_serial, -1) + reply_handle = self.awaiting_reply.pop(reply_serial, None) + if reply_handle is not None: + if hdr.message_type is MessageType.method_return: + reply_handle.set_result(msg.body) + return + elif hdr.message_type is MessageType.error: + reply_handle.set_exception(DBusErrorResponse(msg)) + return + + if self.on_unhandled: + self.on_unhandled(msg) diff --git a/data/miniconda3/lib/python3.13/site-packages/jeepney/wrappers.py b/data/miniconda3/lib/python3.13/site-packages/jeepney/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..816a40b0e739f4795530c5b07ea0936a3adf6a25 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jeepney/wrappers.py @@ -0,0 +1,216 @@ +from typing import Union +from warnings import warn + +from .low_level import * + +__all__ = [ + 'DBusAddress', + 'new_method_call', + 'new_method_return', + 'new_error', + 'new_signal', + 'MessageGenerator', + 'Properties', + 'Introspectable', + 'DBusErrorResponse', +] + +class DBusAddress: + """This identifies the object and interface a message is for. + + e.g. messages to display desktop notifications would have this address:: + + DBusAddress('/org/freedesktop/Notifications', + bus_name='org.freedesktop.Notifications', + interface='org.freedesktop.Notifications') + """ + def __init__(self, object_path, bus_name=None, interface=None): + self.object_path = object_path + self.bus_name = bus_name + self.interface = interface + + def __repr__(self): + return '{}({!r}, bus_name={!r}, interface={!r})'.format(type(self).__name__, + self.object_path, self.bus_name, self.interface) + + def with_interface(self, interface): + return type(self)(self.object_path, self.bus_name, interface) + +class DBusObject(DBusAddress): + def __init__(self, object_path, bus_name=None, interface=None): + super().__init__(object_path, bus_name, interface) + warn('Deprecated alias, use DBusAddress instead', stacklevel=2) + +def new_header(msg_type): + return Header(Endianness.little, msg_type, flags=0, protocol_version=1, + body_length=-1, serial=-1, fields={}) + +def new_method_call(remote_obj, method, signature=None, body=()): + """Construct a new method call message + + This is a relatively low-level method. In many cases, this will be called + from a :class:`MessageGenerator` subclass which provides a more convenient + API. + + :param DBusAddress remote_obj: The object to call a method on + :param str method: The name of the method to call + :param str signature: The DBus signature of the body data + :param tuple body: Body data (i.e. method parameters) + """ + header = new_header(MessageType.method_call) + header.fields[HeaderFields.path] = remote_obj.object_path + if remote_obj.bus_name is None: + raise ValueError("remote_obj.bus_name cannot be None for method calls") + header.fields[HeaderFields.destination] = remote_obj.bus_name + if remote_obj.interface is not None: + header.fields[HeaderFields.interface] = remote_obj.interface + header.fields[HeaderFields.member] = method + if signature is not None: + header.fields[HeaderFields.signature] = signature + + return Message(header, body) + +def new_method_return(parent_msg, signature=None, body=()): + """Construct a new response message + + :param Message parent_msg: The method call this is a reply to + :param str signature: The DBus signature of the body data + :param tuple body: Body data + """ + header = new_header(MessageType.method_return) + header.fields[HeaderFields.reply_serial] = parent_msg.header.serial + sender = parent_msg.header.fields.get(HeaderFields.sender, None) + if sender is not None: + header.fields[HeaderFields.destination] = sender + if signature is not None: + header.fields[HeaderFields.signature] = signature + return Message(header, body) + +def new_error(parent_msg, error_name, signature=None, body=()): + """Construct a new error response message + + :param Message parent_msg: The method call this is a reply to + :param str error_name: The name of the error + :param str signature: The DBus signature of the body data + :param tuple body: Body data + """ + header = new_header(MessageType.error) + header.fields[HeaderFields.reply_serial] = parent_msg.header.serial + header.fields[HeaderFields.error_name] = error_name + sender = parent_msg.header.fields.get(HeaderFields.sender, None) + if sender is not None: + header.fields[HeaderFields.destination] = sender + if signature is not None: + header.fields[HeaderFields.signature] = signature + return Message(header, body) + +def new_signal(emitter, signal, signature=None, body=()): + """Construct a new signal message + + :param DBusAddress emitter: The object sending the signal + :param str signal: The name of the signal + :param str signature: The DBus signature of the body data + :param tuple body: Body data + """ + header = new_header(MessageType.signal) + header.fields[HeaderFields.path] = emitter.object_path + if emitter.interface is None: + raise ValueError("emitter.interface cannot be None for signals") + header.fields[HeaderFields.interface] = emitter.interface + header.fields[HeaderFields.member] = signal + if signature is not None: + header.fields[HeaderFields.signature] = signature + return Message(header, body) + + +class MessageGenerator: + """Subclass this to define the methods available on a DBus interface. + + jeepney.bindgen can automatically create subclasses using introspection. + """ + def __init__(self, object_path, bus_name): + self.object_path = object_path + self.bus_name = bus_name + + def __repr__(self): + return "{}({!r}, bus_name={!r})".format(type(self).__name__, + self.object_path, self.bus_name) + + +class ProxyBase: + """A proxy is an IO-aware wrapper around a MessageGenerator + + Calling methods on a proxy object will send a message and wait for the + reply. This is a base class for proxy implementations in jeepney.io. + """ + def __init__(self, msggen): + self._msggen = msggen + + def __getattr__(self, item): + if item.startswith('__'): + raise AttributeError(item) + + make_msg = getattr(self._msggen, item, None) + if callable(make_msg): + return self._method_call(make_msg) + + raise AttributeError(item) + + def _method_call(self, make_msg): + raise NotImplementedError("Needs to be implemented in subclass") + +class Properties: + """Build messages for accessing object properties + + If a D-Bus object has multiple interfaces, each interface has its own + set of properties. + + This uses the standard DBus interface ``org.freedesktop.DBus.Properties`` + """ + def __init__(self, obj: Union[DBusAddress, MessageGenerator]): + self.obj = obj + self.props_if = DBusAddress(obj.object_path, bus_name=obj.bus_name, + interface='org.freedesktop.DBus.Properties') + + def get(self, name): + """Get the value of the property *name*""" + return new_method_call(self.props_if, 'Get', 'ss', + (self.obj.interface, name)) + + def get_all(self): + """Get all property values for this interface""" + return new_method_call(self.props_if, 'GetAll', 's', + (self.obj.interface,)) + + def set(self, name, signature, value): + """Set the property *name* to *value* (with appropriate signature)""" + return new_method_call(self.props_if, 'Set', 'ssv', + (self.obj.interface, name, (signature, value))) + +class Introspectable(MessageGenerator): + interface = 'org.freedesktop.DBus.Introspectable' + + def Introspect(self): + """Request D-Bus introspection XML for a remote object""" + return new_method_call(self, 'Introspect') + +class DBusErrorResponse(Exception): + """Raised by proxy method calls when the reply is an error message""" + def __init__(self, msg): + self.name = msg.header.fields.get(HeaderFields.error_name) + self.data = msg.body + + def __str__(self): + return '[{}] {}'.format(self.name, self.data) + + +def unwrap_msg(msg: Message): + """Get the body of a message, raising DBusErrorResponse for error messages + + This is to be used with replies to method_call messages, which may be + method_return or error. + """ + if msg.header.message_type == MessageType.error: + raise DBusErrorResponse(msg) + + return msg.body diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/__init__.py b/data/miniconda3/lib/python3.13/site-packages/jwt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..457a4e3580ccc21cb69317008478d20d600abcbc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/__init__.py @@ -0,0 +1,75 @@ +from .api_jwk import PyJWK, PyJWKSet +from .api_jws import ( + PyJWS, + get_algorithm_by_name, + get_unverified_header, + register_algorithm, + unregister_algorithm, +) +from .api_jwt import PyJWT, decode, decode_complete, encode +from .exceptions import ( + DecodeError, + ExpiredSignatureError, + ImmatureSignatureError, + InvalidAlgorithmError, + InvalidAudienceError, + InvalidIssuedAtError, + InvalidIssuerError, + InvalidKeyError, + InvalidSignatureError, + InvalidTokenError, + MissingRequiredClaimError, + PyJWKClientConnectionError, + PyJWKClientError, + PyJWKError, + PyJWKSetError, + PyJWTError, +) +from .jwks_client import PyJWKClient + +__version__ = "2.10.1" + +__title__ = "PyJWT" +__description__ = "JSON Web Token implementation in Python" +__url__ = "https://pyjwt.readthedocs.io" +__uri__ = __url__ +__doc__ = f"{__description__} <{__uri__}>" + +__author__ = "José Padilla" +__email__ = "hello@jpadilla.com" + +__license__ = "MIT" +__copyright__ = "Copyright 2015-2022 José Padilla" + + +__all__ = [ + "PyJWS", + "PyJWT", + "PyJWKClient", + "PyJWK", + "PyJWKSet", + "decode", + "decode_complete", + "encode", + "get_unverified_header", + "register_algorithm", + "unregister_algorithm", + "get_algorithm_by_name", + # Exceptions + "DecodeError", + "ExpiredSignatureError", + "ImmatureSignatureError", + "InvalidAlgorithmError", + "InvalidAudienceError", + "InvalidIssuedAtError", + "InvalidIssuerError", + "InvalidKeyError", + "InvalidSignatureError", + "InvalidTokenError", + "MissingRequiredClaimError", + "PyJWKClientConnectionError", + "PyJWKClientError", + "PyJWKError", + "PyJWKSetError", + "PyJWTError", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/algorithms.py b/data/miniconda3/lib/python3.13/site-packages/jwt/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb1500fcf827b8a2c1eed0e0acf8c1699c0dbf6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/algorithms.py @@ -0,0 +1,875 @@ +from __future__ import annotations + +import hashlib +import hmac +import json +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, ClassVar, Literal, NoReturn, cast, overload + +from .exceptions import InvalidKeyError +from .types import HashlibHash, JWKDict +from .utils import ( + base64url_decode, + base64url_encode, + der_to_raw_signature, + force_bytes, + from_base64url_uint, + is_pem_format, + is_ssh_key, + raw_to_der_signature, + to_base64url_uint, +) + +try: + from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives.asymmetric import padding + from cryptography.hazmat.primitives.asymmetric.ec import ( + ECDSA, + SECP256K1, + SECP256R1, + SECP384R1, + SECP521R1, + EllipticCurve, + EllipticCurvePrivateKey, + EllipticCurvePrivateNumbers, + EllipticCurvePublicKey, + EllipticCurvePublicNumbers, + ) + from cryptography.hazmat.primitives.asymmetric.ed448 import ( + Ed448PrivateKey, + Ed448PublicKey, + ) + from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PrivateKey, + Ed25519PublicKey, + ) + from cryptography.hazmat.primitives.asymmetric.rsa import ( + RSAPrivateKey, + RSAPrivateNumbers, + RSAPublicKey, + RSAPublicNumbers, + rsa_crt_dmp1, + rsa_crt_dmq1, + rsa_crt_iqmp, + rsa_recover_prime_factors, + ) + from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, + PublicFormat, + load_pem_private_key, + load_pem_public_key, + load_ssh_public_key, + ) + + has_crypto = True +except ModuleNotFoundError: + has_crypto = False + + +if TYPE_CHECKING: + # Type aliases for convenience in algorithms method signatures + AllowedRSAKeys = RSAPrivateKey | RSAPublicKey + AllowedECKeys = EllipticCurvePrivateKey | EllipticCurvePublicKey + AllowedOKPKeys = ( + Ed25519PrivateKey | Ed25519PublicKey | Ed448PrivateKey | Ed448PublicKey + ) + AllowedKeys = AllowedRSAKeys | AllowedECKeys | AllowedOKPKeys + AllowedPrivateKeys = ( + RSAPrivateKey | EllipticCurvePrivateKey | Ed25519PrivateKey | Ed448PrivateKey + ) + AllowedPublicKeys = ( + RSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey + ) + + +requires_cryptography = { + "RS256", + "RS384", + "RS512", + "ES256", + "ES256K", + "ES384", + "ES521", + "ES512", + "PS256", + "PS384", + "PS512", + "EdDSA", +} + + +def get_default_algorithms() -> dict[str, Algorithm]: + """ + Returns the algorithms that are implemented by the library. + """ + default_algorithms = { + "none": NoneAlgorithm(), + "HS256": HMACAlgorithm(HMACAlgorithm.SHA256), + "HS384": HMACAlgorithm(HMACAlgorithm.SHA384), + "HS512": HMACAlgorithm(HMACAlgorithm.SHA512), + } + + if has_crypto: + default_algorithms.update( + { + "RS256": RSAAlgorithm(RSAAlgorithm.SHA256), + "RS384": RSAAlgorithm(RSAAlgorithm.SHA384), + "RS512": RSAAlgorithm(RSAAlgorithm.SHA512), + "ES256": ECAlgorithm(ECAlgorithm.SHA256), + "ES256K": ECAlgorithm(ECAlgorithm.SHA256), + "ES384": ECAlgorithm(ECAlgorithm.SHA384), + "ES521": ECAlgorithm(ECAlgorithm.SHA512), + "ES512": ECAlgorithm( + ECAlgorithm.SHA512 + ), # Backward compat for #219 fix + "PS256": RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256), + "PS384": RSAPSSAlgorithm(RSAPSSAlgorithm.SHA384), + "PS512": RSAPSSAlgorithm(RSAPSSAlgorithm.SHA512), + "EdDSA": OKPAlgorithm(), + } + ) + + return default_algorithms + + +class Algorithm(ABC): + """ + The interface for an algorithm used to sign and verify tokens. + """ + + def compute_hash_digest(self, bytestr: bytes) -> bytes: + """ + Compute a hash digest using the specified algorithm's hash algorithm. + + If there is no hash algorithm, raises a NotImplementedError. + """ + # lookup self.hash_alg if defined in a way that mypy can understand + hash_alg = getattr(self, "hash_alg", None) + if hash_alg is None: + raise NotImplementedError + + if ( + has_crypto + and isinstance(hash_alg, type) + and issubclass(hash_alg, hashes.HashAlgorithm) + ): + digest = hashes.Hash(hash_alg(), backend=default_backend()) + digest.update(bytestr) + return bytes(digest.finalize()) + else: + return bytes(hash_alg(bytestr).digest()) + + @abstractmethod + def prepare_key(self, key: Any) -> Any: + """ + Performs necessary validation and conversions on the key and returns + the key value in the proper format for sign() and verify(). + """ + + @abstractmethod + def sign(self, msg: bytes, key: Any) -> bytes: + """ + Returns a digital signature for the specified message + using the specified key value. + """ + + @abstractmethod + def verify(self, msg: bytes, key: Any, sig: bytes) -> bool: + """ + Verifies that the specified digital signature is valid + for the specified message and key values. + """ + + @overload + @staticmethod + @abstractmethod + def to_jwk(key_obj, as_dict: Literal[True]) -> JWKDict: ... # pragma: no cover + + @overload + @staticmethod + @abstractmethod + def to_jwk(key_obj, as_dict: Literal[False] = False) -> str: ... # pragma: no cover + + @staticmethod + @abstractmethod + def to_jwk(key_obj, as_dict: bool = False) -> JWKDict | str: + """ + Serializes a given key into a JWK + """ + + @staticmethod + @abstractmethod + def from_jwk(jwk: str | JWKDict) -> Any: + """ + Deserializes a given key from JWK back into a key object + """ + + +class NoneAlgorithm(Algorithm): + """ + Placeholder for use when no signing or verification + operations are required. + """ + + def prepare_key(self, key: str | None) -> None: + if key == "": + key = None + + if key is not None: + raise InvalidKeyError('When alg = "none", key value must be None.') + + return key + + def sign(self, msg: bytes, key: None) -> bytes: + return b"" + + def verify(self, msg: bytes, key: None, sig: bytes) -> bool: + return False + + @staticmethod + def to_jwk(key_obj: Any, as_dict: bool = False) -> NoReturn: + raise NotImplementedError() + + @staticmethod + def from_jwk(jwk: str | JWKDict) -> NoReturn: + raise NotImplementedError() + + +class HMACAlgorithm(Algorithm): + """ + Performs signing and verification operations using HMAC + and the specified hash function. + """ + + SHA256: ClassVar[HashlibHash] = hashlib.sha256 + SHA384: ClassVar[HashlibHash] = hashlib.sha384 + SHA512: ClassVar[HashlibHash] = hashlib.sha512 + + def __init__(self, hash_alg: HashlibHash) -> None: + self.hash_alg = hash_alg + + def prepare_key(self, key: str | bytes) -> bytes: + key_bytes = force_bytes(key) + + if is_pem_format(key_bytes) or is_ssh_key(key_bytes): + raise InvalidKeyError( + "The specified key is an asymmetric key or x509 certificate and" + " should not be used as an HMAC secret." + ) + + return key_bytes + + @overload + @staticmethod + def to_jwk( + key_obj: str | bytes, as_dict: Literal[True] + ) -> JWKDict: ... # pragma: no cover + + @overload + @staticmethod + def to_jwk( + key_obj: str | bytes, as_dict: Literal[False] = False + ) -> str: ... # pragma: no cover + + @staticmethod + def to_jwk(key_obj: str | bytes, as_dict: bool = False) -> JWKDict | str: + jwk = { + "k": base64url_encode(force_bytes(key_obj)).decode(), + "kty": "oct", + } + + if as_dict: + return jwk + else: + return json.dumps(jwk) + + @staticmethod + def from_jwk(jwk: str | JWKDict) -> bytes: + try: + if isinstance(jwk, str): + obj: JWKDict = json.loads(jwk) + elif isinstance(jwk, dict): + obj = jwk + else: + raise ValueError + except ValueError: + raise InvalidKeyError("Key is not valid JSON") from None + + if obj.get("kty") != "oct": + raise InvalidKeyError("Not an HMAC key") + + return base64url_decode(obj["k"]) + + def sign(self, msg: bytes, key: bytes) -> bytes: + return hmac.new(key, msg, self.hash_alg).digest() + + def verify(self, msg: bytes, key: bytes, sig: bytes) -> bool: + return hmac.compare_digest(sig, self.sign(msg, key)) + + +if has_crypto: + + class RSAAlgorithm(Algorithm): + """ + Performs signing and verification operations using + RSASSA-PKCS-v1_5 and the specified hash function. + """ + + SHA256: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA256 + SHA384: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA384 + SHA512: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA512 + + def __init__(self, hash_alg: type[hashes.HashAlgorithm]) -> None: + self.hash_alg = hash_alg + + def prepare_key(self, key: AllowedRSAKeys | str | bytes) -> AllowedRSAKeys: + if isinstance(key, (RSAPrivateKey, RSAPublicKey)): + return key + + if not isinstance(key, (bytes, str)): + raise TypeError("Expecting a PEM-formatted key.") + + key_bytes = force_bytes(key) + + try: + if key_bytes.startswith(b"ssh-rsa"): + return cast(RSAPublicKey, load_ssh_public_key(key_bytes)) + else: + return cast( + RSAPrivateKey, load_pem_private_key(key_bytes, password=None) + ) + except ValueError: + try: + return cast(RSAPublicKey, load_pem_public_key(key_bytes)) + except (ValueError, UnsupportedAlgorithm): + raise InvalidKeyError( + "Could not parse the provided public key." + ) from None + + @overload + @staticmethod + def to_jwk( + key_obj: AllowedRSAKeys, as_dict: Literal[True] + ) -> JWKDict: ... # pragma: no cover + + @overload + @staticmethod + def to_jwk( + key_obj: AllowedRSAKeys, as_dict: Literal[False] = False + ) -> str: ... # pragma: no cover + + @staticmethod + def to_jwk(key_obj: AllowedRSAKeys, as_dict: bool = False) -> JWKDict | str: + obj: dict[str, Any] | None = None + + if hasattr(key_obj, "private_numbers"): + # Private key + numbers = key_obj.private_numbers() + + obj = { + "kty": "RSA", + "key_ops": ["sign"], + "n": to_base64url_uint(numbers.public_numbers.n).decode(), + "e": to_base64url_uint(numbers.public_numbers.e).decode(), + "d": to_base64url_uint(numbers.d).decode(), + "p": to_base64url_uint(numbers.p).decode(), + "q": to_base64url_uint(numbers.q).decode(), + "dp": to_base64url_uint(numbers.dmp1).decode(), + "dq": to_base64url_uint(numbers.dmq1).decode(), + "qi": to_base64url_uint(numbers.iqmp).decode(), + } + + elif hasattr(key_obj, "verify"): + # Public key + numbers = key_obj.public_numbers() + + obj = { + "kty": "RSA", + "key_ops": ["verify"], + "n": to_base64url_uint(numbers.n).decode(), + "e": to_base64url_uint(numbers.e).decode(), + } + else: + raise InvalidKeyError("Not a public or private key") + + if as_dict: + return obj + else: + return json.dumps(obj) + + @staticmethod + def from_jwk(jwk: str | JWKDict) -> AllowedRSAKeys: + try: + if isinstance(jwk, str): + obj = json.loads(jwk) + elif isinstance(jwk, dict): + obj = jwk + else: + raise ValueError + except ValueError: + raise InvalidKeyError("Key is not valid JSON") from None + + if obj.get("kty") != "RSA": + raise InvalidKeyError("Not an RSA key") from None + + if "d" in obj and "e" in obj and "n" in obj: + # Private key + if "oth" in obj: + raise InvalidKeyError( + "Unsupported RSA private key: > 2 primes not supported" + ) + + other_props = ["p", "q", "dp", "dq", "qi"] + props_found = [prop in obj for prop in other_props] + any_props_found = any(props_found) + + if any_props_found and not all(props_found): + raise InvalidKeyError( + "RSA key must include all parameters if any are present besides d" + ) from None + + public_numbers = RSAPublicNumbers( + from_base64url_uint(obj["e"]), + from_base64url_uint(obj["n"]), + ) + + if any_props_found: + numbers = RSAPrivateNumbers( + d=from_base64url_uint(obj["d"]), + p=from_base64url_uint(obj["p"]), + q=from_base64url_uint(obj["q"]), + dmp1=from_base64url_uint(obj["dp"]), + dmq1=from_base64url_uint(obj["dq"]), + iqmp=from_base64url_uint(obj["qi"]), + public_numbers=public_numbers, + ) + else: + d = from_base64url_uint(obj["d"]) + p, q = rsa_recover_prime_factors( + public_numbers.n, d, public_numbers.e + ) + + numbers = RSAPrivateNumbers( + d=d, + p=p, + q=q, + dmp1=rsa_crt_dmp1(d, p), + dmq1=rsa_crt_dmq1(d, q), + iqmp=rsa_crt_iqmp(p, q), + public_numbers=public_numbers, + ) + + return numbers.private_key() + elif "n" in obj and "e" in obj: + # Public key + return RSAPublicNumbers( + from_base64url_uint(obj["e"]), + from_base64url_uint(obj["n"]), + ).public_key() + else: + raise InvalidKeyError("Not a public or private key") + + def sign(self, msg: bytes, key: RSAPrivateKey) -> bytes: + return key.sign(msg, padding.PKCS1v15(), self.hash_alg()) + + def verify(self, msg: bytes, key: RSAPublicKey, sig: bytes) -> bool: + try: + key.verify(sig, msg, padding.PKCS1v15(), self.hash_alg()) + return True + except InvalidSignature: + return False + + class ECAlgorithm(Algorithm): + """ + Performs signing and verification operations using + ECDSA and the specified hash function + """ + + SHA256: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA256 + SHA384: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA384 + SHA512: ClassVar[type[hashes.HashAlgorithm]] = hashes.SHA512 + + def __init__(self, hash_alg: type[hashes.HashAlgorithm]) -> None: + self.hash_alg = hash_alg + + def prepare_key(self, key: AllowedECKeys | str | bytes) -> AllowedECKeys: + if isinstance(key, (EllipticCurvePrivateKey, EllipticCurvePublicKey)): + return key + + if not isinstance(key, (bytes, str)): + raise TypeError("Expecting a PEM-formatted key.") + + key_bytes = force_bytes(key) + + # Attempt to load key. We don't know if it's + # a Signing Key or a Verifying Key, so we try + # the Verifying Key first. + try: + if key_bytes.startswith(b"ecdsa-sha2-"): + crypto_key = load_ssh_public_key(key_bytes) + else: + crypto_key = load_pem_public_key(key_bytes) # type: ignore[assignment] + except ValueError: + crypto_key = load_pem_private_key(key_bytes, password=None) # type: ignore[assignment] + + # Explicit check the key to prevent confusing errors from cryptography + if not isinstance( + crypto_key, (EllipticCurvePrivateKey, EllipticCurvePublicKey) + ): + raise InvalidKeyError( + "Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for ECDSA algorithms" + ) from None + + return crypto_key + + def sign(self, msg: bytes, key: EllipticCurvePrivateKey) -> bytes: + der_sig = key.sign(msg, ECDSA(self.hash_alg())) + + return der_to_raw_signature(der_sig, key.curve) + + def verify(self, msg: bytes, key: AllowedECKeys, sig: bytes) -> bool: + try: + der_sig = raw_to_der_signature(sig, key.curve) + except ValueError: + return False + + try: + public_key = ( + key.public_key() + if isinstance(key, EllipticCurvePrivateKey) + else key + ) + public_key.verify(der_sig, msg, ECDSA(self.hash_alg())) + return True + except InvalidSignature: + return False + + @overload + @staticmethod + def to_jwk( + key_obj: AllowedECKeys, as_dict: Literal[True] + ) -> JWKDict: ... # pragma: no cover + + @overload + @staticmethod + def to_jwk( + key_obj: AllowedECKeys, as_dict: Literal[False] = False + ) -> str: ... # pragma: no cover + + @staticmethod + def to_jwk(key_obj: AllowedECKeys, as_dict: bool = False) -> JWKDict | str: + if isinstance(key_obj, EllipticCurvePrivateKey): + public_numbers = key_obj.public_key().public_numbers() + elif isinstance(key_obj, EllipticCurvePublicKey): + public_numbers = key_obj.public_numbers() + else: + raise InvalidKeyError("Not a public or private key") + + if isinstance(key_obj.curve, SECP256R1): + crv = "P-256" + elif isinstance(key_obj.curve, SECP384R1): + crv = "P-384" + elif isinstance(key_obj.curve, SECP521R1): + crv = "P-521" + elif isinstance(key_obj.curve, SECP256K1): + crv = "secp256k1" + else: + raise InvalidKeyError(f"Invalid curve: {key_obj.curve}") + + obj: dict[str, Any] = { + "kty": "EC", + "crv": crv, + "x": to_base64url_uint( + public_numbers.x, + bit_length=key_obj.curve.key_size, + ).decode(), + "y": to_base64url_uint( + public_numbers.y, + bit_length=key_obj.curve.key_size, + ).decode(), + } + + if isinstance(key_obj, EllipticCurvePrivateKey): + obj["d"] = to_base64url_uint( + key_obj.private_numbers().private_value, + bit_length=key_obj.curve.key_size, + ).decode() + + if as_dict: + return obj + else: + return json.dumps(obj) + + @staticmethod + def from_jwk(jwk: str | JWKDict) -> AllowedECKeys: + try: + if isinstance(jwk, str): + obj = json.loads(jwk) + elif isinstance(jwk, dict): + obj = jwk + else: + raise ValueError + except ValueError: + raise InvalidKeyError("Key is not valid JSON") from None + + if obj.get("kty") != "EC": + raise InvalidKeyError("Not an Elliptic curve key") from None + + if "x" not in obj or "y" not in obj: + raise InvalidKeyError("Not an Elliptic curve key") from None + + x = base64url_decode(obj.get("x")) + y = base64url_decode(obj.get("y")) + + curve = obj.get("crv") + curve_obj: EllipticCurve + + if curve == "P-256": + if len(x) == len(y) == 32: + curve_obj = SECP256R1() + else: + raise InvalidKeyError( + "Coords should be 32 bytes for curve P-256" + ) from None + elif curve == "P-384": + if len(x) == len(y) == 48: + curve_obj = SECP384R1() + else: + raise InvalidKeyError( + "Coords should be 48 bytes for curve P-384" + ) from None + elif curve == "P-521": + if len(x) == len(y) == 66: + curve_obj = SECP521R1() + else: + raise InvalidKeyError( + "Coords should be 66 bytes for curve P-521" + ) from None + elif curve == "secp256k1": + if len(x) == len(y) == 32: + curve_obj = SECP256K1() + else: + raise InvalidKeyError( + "Coords should be 32 bytes for curve secp256k1" + ) + else: + raise InvalidKeyError(f"Invalid curve: {curve}") + + public_numbers = EllipticCurvePublicNumbers( + x=int.from_bytes(x, byteorder="big"), + y=int.from_bytes(y, byteorder="big"), + curve=curve_obj, + ) + + if "d" not in obj: + return public_numbers.public_key() + + d = base64url_decode(obj.get("d")) + if len(d) != len(x): + raise InvalidKeyError( + "D should be {} bytes for curve {}", len(x), curve + ) + + return EllipticCurvePrivateNumbers( + int.from_bytes(d, byteorder="big"), public_numbers + ).private_key() + + class RSAPSSAlgorithm(RSAAlgorithm): + """ + Performs a signature using RSASSA-PSS with MGF1 + """ + + def sign(self, msg: bytes, key: RSAPrivateKey) -> bytes: + return key.sign( + msg, + padding.PSS( + mgf=padding.MGF1(self.hash_alg()), + salt_length=self.hash_alg().digest_size, + ), + self.hash_alg(), + ) + + def verify(self, msg: bytes, key: RSAPublicKey, sig: bytes) -> bool: + try: + key.verify( + sig, + msg, + padding.PSS( + mgf=padding.MGF1(self.hash_alg()), + salt_length=self.hash_alg().digest_size, + ), + self.hash_alg(), + ) + return True + except InvalidSignature: + return False + + class OKPAlgorithm(Algorithm): + """ + Performs signing and verification operations using EdDSA + + This class requires ``cryptography>=2.6`` to be installed. + """ + + def __init__(self, **kwargs: Any) -> None: + pass + + def prepare_key(self, key: AllowedOKPKeys | str | bytes) -> AllowedOKPKeys: + if isinstance(key, (bytes, str)): + key_str = key.decode("utf-8") if isinstance(key, bytes) else key + key_bytes = key.encode("utf-8") if isinstance(key, str) else key + + if "-----BEGIN PUBLIC" in key_str: + key = load_pem_public_key(key_bytes) # type: ignore[assignment] + elif "-----BEGIN PRIVATE" in key_str: + key = load_pem_private_key(key_bytes, password=None) # type: ignore[assignment] + elif key_str[0:4] == "ssh-": + key = load_ssh_public_key(key_bytes) # type: ignore[assignment] + + # Explicit check the key to prevent confusing errors from cryptography + if not isinstance( + key, + (Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey), + ): + raise InvalidKeyError( + "Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for EdDSA algorithms" + ) + + return key + + def sign( + self, msg: str | bytes, key: Ed25519PrivateKey | Ed448PrivateKey + ) -> bytes: + """ + Sign a message ``msg`` using the EdDSA private key ``key`` + :param str|bytes msg: Message to sign + :param Ed25519PrivateKey}Ed448PrivateKey key: A :class:`.Ed25519PrivateKey` + or :class:`.Ed448PrivateKey` isinstance + :return bytes signature: The signature, as bytes + """ + msg_bytes = msg.encode("utf-8") if isinstance(msg, str) else msg + return key.sign(msg_bytes) + + def verify( + self, msg: str | bytes, key: AllowedOKPKeys, sig: str | bytes + ) -> bool: + """ + Verify a given ``msg`` against a signature ``sig`` using the EdDSA key ``key`` + + :param str|bytes sig: EdDSA signature to check ``msg`` against + :param str|bytes msg: Message to sign + :param Ed25519PrivateKey|Ed25519PublicKey|Ed448PrivateKey|Ed448PublicKey key: + A private or public EdDSA key instance + :return bool verified: True if signature is valid, False if not. + """ + try: + msg_bytes = msg.encode("utf-8") if isinstance(msg, str) else msg + sig_bytes = sig.encode("utf-8") if isinstance(sig, str) else sig + + public_key = ( + key.public_key() + if isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey)) + else key + ) + public_key.verify(sig_bytes, msg_bytes) + return True # If no exception was raised, the signature is valid. + except InvalidSignature: + return False + + @overload + @staticmethod + def to_jwk( + key: AllowedOKPKeys, as_dict: Literal[True] + ) -> JWKDict: ... # pragma: no cover + + @overload + @staticmethod + def to_jwk( + key: AllowedOKPKeys, as_dict: Literal[False] = False + ) -> str: ... # pragma: no cover + + @staticmethod + def to_jwk(key: AllowedOKPKeys, as_dict: bool = False) -> JWKDict | str: + if isinstance(key, (Ed25519PublicKey, Ed448PublicKey)): + x = key.public_bytes( + encoding=Encoding.Raw, + format=PublicFormat.Raw, + ) + crv = "Ed25519" if isinstance(key, Ed25519PublicKey) else "Ed448" + + obj = { + "x": base64url_encode(force_bytes(x)).decode(), + "kty": "OKP", + "crv": crv, + } + + if as_dict: + return obj + else: + return json.dumps(obj) + + if isinstance(key, (Ed25519PrivateKey, Ed448PrivateKey)): + d = key.private_bytes( + encoding=Encoding.Raw, + format=PrivateFormat.Raw, + encryption_algorithm=NoEncryption(), + ) + + x = key.public_key().public_bytes( + encoding=Encoding.Raw, + format=PublicFormat.Raw, + ) + + crv = "Ed25519" if isinstance(key, Ed25519PrivateKey) else "Ed448" + obj = { + "x": base64url_encode(force_bytes(x)).decode(), + "d": base64url_encode(force_bytes(d)).decode(), + "kty": "OKP", + "crv": crv, + } + + if as_dict: + return obj + else: + return json.dumps(obj) + + raise InvalidKeyError("Not a public or private key") + + @staticmethod + def from_jwk(jwk: str | JWKDict) -> AllowedOKPKeys: + try: + if isinstance(jwk, str): + obj = json.loads(jwk) + elif isinstance(jwk, dict): + obj = jwk + else: + raise ValueError + except ValueError: + raise InvalidKeyError("Key is not valid JSON") from None + + if obj.get("kty") != "OKP": + raise InvalidKeyError("Not an Octet Key Pair") + + curve = obj.get("crv") + if curve != "Ed25519" and curve != "Ed448": + raise InvalidKeyError(f"Invalid curve: {curve}") + + if "x" not in obj: + raise InvalidKeyError('OKP should have "x" parameter') + x = base64url_decode(obj.get("x")) + + try: + if "d" not in obj: + if curve == "Ed25519": + return Ed25519PublicKey.from_public_bytes(x) + return Ed448PublicKey.from_public_bytes(x) + d = base64url_decode(obj.get("d")) + if curve == "Ed25519": + return Ed25519PrivateKey.from_private_bytes(d) + return Ed448PrivateKey.from_private_bytes(d) + except ValueError as err: + raise InvalidKeyError("Invalid key parameter") from err diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/api_jwk.py b/data/miniconda3/lib/python3.13/site-packages/jwt/api_jwk.py new file mode 100644 index 0000000000000000000000000000000000000000..02f4679cbb55a854419b18af322d93db1b295312 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/api_jwk.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +import json +import time +from typing import Any + +from .algorithms import get_default_algorithms, has_crypto, requires_cryptography +from .exceptions import ( + InvalidKeyError, + MissingCryptographyError, + PyJWKError, + PyJWKSetError, + PyJWTError, +) +from .types import JWKDict + + +class PyJWK: + def __init__(self, jwk_data: JWKDict, algorithm: str | None = None) -> None: + self._algorithms = get_default_algorithms() + self._jwk_data = jwk_data + + kty = self._jwk_data.get("kty", None) + if not kty: + raise InvalidKeyError(f"kty is not found: {self._jwk_data}") + + if not algorithm and isinstance(self._jwk_data, dict): + algorithm = self._jwk_data.get("alg", None) + + if not algorithm: + # Determine alg with kty (and crv). + crv = self._jwk_data.get("crv", None) + if kty == "EC": + if crv == "P-256" or not crv: + algorithm = "ES256" + elif crv == "P-384": + algorithm = "ES384" + elif crv == "P-521": + algorithm = "ES512" + elif crv == "secp256k1": + algorithm = "ES256K" + else: + raise InvalidKeyError(f"Unsupported crv: {crv}") + elif kty == "RSA": + algorithm = "RS256" + elif kty == "oct": + algorithm = "HS256" + elif kty == "OKP": + if not crv: + raise InvalidKeyError(f"crv is not found: {self._jwk_data}") + if crv == "Ed25519": + algorithm = "EdDSA" + else: + raise InvalidKeyError(f"Unsupported crv: {crv}") + else: + raise InvalidKeyError(f"Unsupported kty: {kty}") + + if not has_crypto and algorithm in requires_cryptography: + raise MissingCryptographyError( + f"{algorithm} requires 'cryptography' to be installed." + ) + + self.algorithm_name = algorithm + + if algorithm in self._algorithms: + self.Algorithm = self._algorithms[algorithm] + else: + raise PyJWKError(f"Unable to find an algorithm for key: {self._jwk_data}") + + self.key = self.Algorithm.from_jwk(self._jwk_data) + + @staticmethod + def from_dict(obj: JWKDict, algorithm: str | None = None) -> PyJWK: + return PyJWK(obj, algorithm) + + @staticmethod + def from_json(data: str, algorithm: None = None) -> PyJWK: + obj = json.loads(data) + return PyJWK.from_dict(obj, algorithm) + + @property + def key_type(self) -> str | None: + return self._jwk_data.get("kty", None) + + @property + def key_id(self) -> str | None: + return self._jwk_data.get("kid", None) + + @property + def public_key_use(self) -> str | None: + return self._jwk_data.get("use", None) + + +class PyJWKSet: + def __init__(self, keys: list[JWKDict]) -> None: + self.keys = [] + + if not keys: + raise PyJWKSetError("The JWK Set did not contain any keys") + + if not isinstance(keys, list): + raise PyJWKSetError("Invalid JWK Set value") + + for key in keys: + try: + self.keys.append(PyJWK(key)) + except PyJWTError as error: + if isinstance(error, MissingCryptographyError): + raise error + # skip unusable keys + continue + + if len(self.keys) == 0: + raise PyJWKSetError( + "The JWK Set did not contain any usable keys. Perhaps 'cryptography' is not installed?" + ) + + @staticmethod + def from_dict(obj: dict[str, Any]) -> PyJWKSet: + keys = obj.get("keys", []) + return PyJWKSet(keys) + + @staticmethod + def from_json(data: str) -> PyJWKSet: + obj = json.loads(data) + return PyJWKSet.from_dict(obj) + + def __getitem__(self, kid: str) -> PyJWK: + for key in self.keys: + if key.key_id == kid: + return key + raise KeyError(f"keyset has no key for kid: {kid}") + + +class PyJWTSetWithTimestamp: + def __init__(self, jwk_set: PyJWKSet): + self.jwk_set = jwk_set + self.timestamp = time.monotonic() + + def get_jwk_set(self) -> PyJWKSet: + return self.jwk_set + + def get_timestamp(self) -> float: + return self.timestamp diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/api_jws.py b/data/miniconda3/lib/python3.13/site-packages/jwt/api_jws.py new file mode 100644 index 0000000000000000000000000000000000000000..654ee0b744b35a81bb01fe9c4f1bccd041e2cab8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/api_jws.py @@ -0,0 +1,346 @@ +from __future__ import annotations + +import binascii +import json +import warnings +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +from .algorithms import ( + Algorithm, + get_default_algorithms, + has_crypto, + requires_cryptography, +) +from .api_jwk import PyJWK +from .exceptions import ( + DecodeError, + InvalidAlgorithmError, + InvalidSignatureError, + InvalidTokenError, +) +from .utils import base64url_decode, base64url_encode +from .warnings import RemovedInPyjwt3Warning + +if TYPE_CHECKING: + from .algorithms import AllowedPrivateKeys, AllowedPublicKeys + + +class PyJWS: + header_typ = "JWT" + + def __init__( + self, + algorithms: Sequence[str] | None = None, + options: dict[str, Any] | None = None, + ) -> None: + self._algorithms = get_default_algorithms() + self._valid_algs = ( + set(algorithms) if algorithms is not None else set(self._algorithms) + ) + + # Remove algorithms that aren't on the whitelist + for key in list(self._algorithms.keys()): + if key not in self._valid_algs: + del self._algorithms[key] + + if options is None: + options = {} + self.options = {**self._get_default_options(), **options} + + @staticmethod + def _get_default_options() -> dict[str, bool]: + return {"verify_signature": True} + + def register_algorithm(self, alg_id: str, alg_obj: Algorithm) -> None: + """ + Registers a new Algorithm for use when creating and verifying tokens. + """ + if alg_id in self._algorithms: + raise ValueError("Algorithm already has a handler.") + + if not isinstance(alg_obj, Algorithm): + raise TypeError("Object is not of type `Algorithm`") + + self._algorithms[alg_id] = alg_obj + self._valid_algs.add(alg_id) + + def unregister_algorithm(self, alg_id: str) -> None: + """ + Unregisters an Algorithm for use when creating and verifying tokens + Throws KeyError if algorithm is not registered. + """ + if alg_id not in self._algorithms: + raise KeyError( + "The specified algorithm could not be removed" + " because it is not registered." + ) + + del self._algorithms[alg_id] + self._valid_algs.remove(alg_id) + + def get_algorithms(self) -> list[str]: + """ + Returns a list of supported values for the 'alg' parameter. + """ + return list(self._valid_algs) + + def get_algorithm_by_name(self, alg_name: str) -> Algorithm: + """ + For a given string name, return the matching Algorithm object. + + Example usage: + + >>> jws_obj.get_algorithm_by_name("RS256") + """ + try: + return self._algorithms[alg_name] + except KeyError as e: + if not has_crypto and alg_name in requires_cryptography: + raise NotImplementedError( + f"Algorithm '{alg_name}' could not be found. Do you have cryptography installed?" + ) from e + raise NotImplementedError("Algorithm not supported") from e + + def encode( + self, + payload: bytes, + key: AllowedPrivateKeys | PyJWK | str | bytes, + algorithm: str | None = None, + headers: dict[str, Any] | None = None, + json_encoder: type[json.JSONEncoder] | None = None, + is_payload_detached: bool = False, + sort_headers: bool = True, + ) -> str: + segments = [] + + # declare a new var to narrow the type for type checkers + if algorithm is None: + if isinstance(key, PyJWK): + algorithm_ = key.algorithm_name + else: + algorithm_ = "HS256" + else: + algorithm_ = algorithm + + # Prefer headers values if present to function parameters. + if headers: + headers_alg = headers.get("alg") + if headers_alg: + algorithm_ = headers["alg"] + + headers_b64 = headers.get("b64") + if headers_b64 is False: + is_payload_detached = True + + # Header + header: dict[str, Any] = {"typ": self.header_typ, "alg": algorithm_} + + if headers: + self._validate_headers(headers) + header.update(headers) + + if not header["typ"]: + del header["typ"] + + if is_payload_detached: + header["b64"] = False + elif "b64" in header: + # True is the standard value for b64, so no need for it + del header["b64"] + + json_header = json.dumps( + header, separators=(",", ":"), cls=json_encoder, sort_keys=sort_headers + ).encode() + + segments.append(base64url_encode(json_header)) + + if is_payload_detached: + msg_payload = payload + else: + msg_payload = base64url_encode(payload) + segments.append(msg_payload) + + # Segments + signing_input = b".".join(segments) + + alg_obj = self.get_algorithm_by_name(algorithm_) + if isinstance(key, PyJWK): + key = key.key + key = alg_obj.prepare_key(key) + signature = alg_obj.sign(signing_input, key) + + segments.append(base64url_encode(signature)) + + # Don't put the payload content inside the encoded token when detached + if is_payload_detached: + segments[1] = b"" + encoded_string = b".".join(segments) + + return encoded_string.decode("utf-8") + + def decode_complete( + self, + jwt: str | bytes, + key: AllowedPublicKeys | PyJWK | str | bytes = "", + algorithms: Sequence[str] | None = None, + options: dict[str, Any] | None = None, + detached_payload: bytes | None = None, + **kwargs, + ) -> dict[str, Any]: + if kwargs: + warnings.warn( + "passing additional kwargs to decode_complete() is deprecated " + "and will be removed in pyjwt version 3. " + f"Unsupported kwargs: {tuple(kwargs.keys())}", + RemovedInPyjwt3Warning, + stacklevel=2, + ) + if options is None: + options = {} + merged_options = {**self.options, **options} + verify_signature = merged_options["verify_signature"] + + if verify_signature and not algorithms and not isinstance(key, PyJWK): + raise DecodeError( + 'It is required that you pass in a value for the "algorithms" argument when calling decode().' + ) + + payload, signing_input, header, signature = self._load(jwt) + + if header.get("b64", True) is False: + if detached_payload is None: + raise DecodeError( + 'It is required that you pass in a value for the "detached_payload" argument to decode a message having the b64 header set to false.' + ) + payload = detached_payload + signing_input = b".".join([signing_input.rsplit(b".", 1)[0], payload]) + + if verify_signature: + self._verify_signature(signing_input, header, signature, key, algorithms) + + return { + "payload": payload, + "header": header, + "signature": signature, + } + + def decode( + self, + jwt: str | bytes, + key: AllowedPublicKeys | PyJWK | str | bytes = "", + algorithms: Sequence[str] | None = None, + options: dict[str, Any] | None = None, + detached_payload: bytes | None = None, + **kwargs, + ) -> Any: + if kwargs: + warnings.warn( + "passing additional kwargs to decode() is deprecated " + "and will be removed in pyjwt version 3. " + f"Unsupported kwargs: {tuple(kwargs.keys())}", + RemovedInPyjwt3Warning, + stacklevel=2, + ) + decoded = self.decode_complete( + jwt, key, algorithms, options, detached_payload=detached_payload + ) + return decoded["payload"] + + def get_unverified_header(self, jwt: str | bytes) -> dict[str, Any]: + """Returns back the JWT header parameters as a dict() + + Note: The signature is not verified so the header parameters + should not be fully trusted until signature verification is complete + """ + headers = self._load(jwt)[2] + self._validate_headers(headers) + + return headers + + def _load(self, jwt: str | bytes) -> tuple[bytes, bytes, dict[str, Any], bytes]: + if isinstance(jwt, str): + jwt = jwt.encode("utf-8") + + if not isinstance(jwt, bytes): + raise DecodeError(f"Invalid token type. Token must be a {bytes}") + + try: + signing_input, crypto_segment = jwt.rsplit(b".", 1) + header_segment, payload_segment = signing_input.split(b".", 1) + except ValueError as err: + raise DecodeError("Not enough segments") from err + + try: + header_data = base64url_decode(header_segment) + except (TypeError, binascii.Error) as err: + raise DecodeError("Invalid header padding") from err + + try: + header = json.loads(header_data) + except ValueError as e: + raise DecodeError(f"Invalid header string: {e}") from e + + if not isinstance(header, dict): + raise DecodeError("Invalid header string: must be a json object") + + try: + payload = base64url_decode(payload_segment) + except (TypeError, binascii.Error) as err: + raise DecodeError("Invalid payload padding") from err + + try: + signature = base64url_decode(crypto_segment) + except (TypeError, binascii.Error) as err: + raise DecodeError("Invalid crypto padding") from err + + return (payload, signing_input, header, signature) + + def _verify_signature( + self, + signing_input: bytes, + header: dict[str, Any], + signature: bytes, + key: AllowedPublicKeys | PyJWK | str | bytes = "", + algorithms: Sequence[str] | None = None, + ) -> None: + if algorithms is None and isinstance(key, PyJWK): + algorithms = [key.algorithm_name] + try: + alg = header["alg"] + except KeyError: + raise InvalidAlgorithmError("Algorithm not specified") from None + + if not alg or (algorithms is not None and alg not in algorithms): + raise InvalidAlgorithmError("The specified alg value is not allowed") + + if isinstance(key, PyJWK): + alg_obj = key.Algorithm + prepared_key = key.key + else: + try: + alg_obj = self.get_algorithm_by_name(alg) + except NotImplementedError as e: + raise InvalidAlgorithmError("Algorithm not supported") from e + prepared_key = alg_obj.prepare_key(key) + + if not alg_obj.verify(signing_input, prepared_key, signature): + raise InvalidSignatureError("Signature verification failed") + + def _validate_headers(self, headers: dict[str, Any]) -> None: + if "kid" in headers: + self._validate_kid(headers["kid"]) + + def _validate_kid(self, kid: Any) -> None: + if not isinstance(kid, str): + raise InvalidTokenError("Key ID header parameter must be a string") + + +_jws_global_obj = PyJWS() +encode = _jws_global_obj.encode +decode_complete = _jws_global_obj.decode_complete +decode = _jws_global_obj.decode +register_algorithm = _jws_global_obj.register_algorithm +unregister_algorithm = _jws_global_obj.unregister_algorithm +get_algorithm_by_name = _jws_global_obj.get_algorithm_by_name +get_unverified_header = _jws_global_obj.get_unverified_header diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/api_jwt.py b/data/miniconda3/lib/python3.13/site-packages/jwt/api_jwt.py new file mode 100644 index 0000000000000000000000000000000000000000..3a201436c5b5064c32f117f6a1590a8af2af3b84 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/api_jwt.py @@ -0,0 +1,433 @@ +from __future__ import annotations + +import json +import warnings +from calendar import timegm +from collections.abc import Iterable, Sequence +from datetime import datetime, timedelta, timezone +from typing import TYPE_CHECKING, Any + +from . import api_jws +from .exceptions import ( + DecodeError, + ExpiredSignatureError, + ImmatureSignatureError, + InvalidAudienceError, + InvalidIssuedAtError, + InvalidIssuerError, + InvalidJTIError, + InvalidSubjectError, + MissingRequiredClaimError, +) +from .warnings import RemovedInPyjwt3Warning + +if TYPE_CHECKING: + from .algorithms import AllowedPrivateKeys, AllowedPublicKeys + from .api_jwk import PyJWK + + +class PyJWT: + def __init__(self, options: dict[str, Any] | None = None) -> None: + if options is None: + options = {} + self.options: dict[str, Any] = {**self._get_default_options(), **options} + + @staticmethod + def _get_default_options() -> dict[str, bool | list[str]]: + return { + "verify_signature": True, + "verify_exp": True, + "verify_nbf": True, + "verify_iat": True, + "verify_aud": True, + "verify_iss": True, + "verify_sub": True, + "verify_jti": True, + "require": [], + } + + def encode( + self, + payload: dict[str, Any], + key: AllowedPrivateKeys | PyJWK | str | bytes, + algorithm: str | None = None, + headers: dict[str, Any] | None = None, + json_encoder: type[json.JSONEncoder] | None = None, + sort_headers: bool = True, + ) -> str: + # Check that we get a dict + if not isinstance(payload, dict): + raise TypeError( + "Expecting a dict object, as JWT only supports " + "JSON objects as payloads." + ) + + # Payload + payload = payload.copy() + for time_claim in ["exp", "iat", "nbf"]: + # Convert datetime to a intDate value in known time-format claims + if isinstance(payload.get(time_claim), datetime): + payload[time_claim] = timegm(payload[time_claim].utctimetuple()) + + json_payload = self._encode_payload( + payload, + headers=headers, + json_encoder=json_encoder, + ) + + return api_jws.encode( + json_payload, + key, + algorithm, + headers, + json_encoder, + sort_headers=sort_headers, + ) + + def _encode_payload( + self, + payload: dict[str, Any], + headers: dict[str, Any] | None = None, + json_encoder: type[json.JSONEncoder] | None = None, + ) -> bytes: + """ + Encode a given payload to the bytes to be signed. + + This method is intended to be overridden by subclasses that need to + encode the payload in a different way, e.g. compress the payload. + """ + return json.dumps( + payload, + separators=(",", ":"), + cls=json_encoder, + ).encode("utf-8") + + def decode_complete( + self, + jwt: str | bytes, + key: AllowedPublicKeys | PyJWK | str | bytes = "", + algorithms: Sequence[str] | None = None, + options: dict[str, Any] | None = None, + # deprecated arg, remove in pyjwt3 + verify: bool | None = None, + # could be used as passthrough to api_jws, consider removal in pyjwt3 + detached_payload: bytes | None = None, + # passthrough arguments to _validate_claims + # consider putting in options + audience: str | Iterable[str] | None = None, + issuer: str | Sequence[str] | None = None, + subject: str | None = None, + leeway: float | timedelta = 0, + # kwargs + **kwargs: Any, + ) -> dict[str, Any]: + if kwargs: + warnings.warn( + "passing additional kwargs to decode_complete() is deprecated " + "and will be removed in pyjwt version 3. " + f"Unsupported kwargs: {tuple(kwargs.keys())}", + RemovedInPyjwt3Warning, + stacklevel=2, + ) + options = dict(options or {}) # shallow-copy or initialize an empty dict + options.setdefault("verify_signature", True) + + # If the user has set the legacy `verify` argument, and it doesn't match + # what the relevant `options` entry for the argument is, inform the user + # that they're likely making a mistake. + if verify is not None and verify != options["verify_signature"]: + warnings.warn( + "The `verify` argument to `decode` does nothing in PyJWT 2.0 and newer. " + "The equivalent is setting `verify_signature` to False in the `options` dictionary. " + "This invocation has a mismatch between the kwarg and the option entry.", + category=DeprecationWarning, + stacklevel=2, + ) + + if not options["verify_signature"]: + options.setdefault("verify_exp", False) + options.setdefault("verify_nbf", False) + options.setdefault("verify_iat", False) + options.setdefault("verify_aud", False) + options.setdefault("verify_iss", False) + options.setdefault("verify_sub", False) + options.setdefault("verify_jti", False) + + decoded = api_jws.decode_complete( + jwt, + key=key, + algorithms=algorithms, + options=options, + detached_payload=detached_payload, + ) + + payload = self._decode_payload(decoded) + + merged_options = {**self.options, **options} + self._validate_claims( + payload, + merged_options, + audience=audience, + issuer=issuer, + leeway=leeway, + subject=subject, + ) + + decoded["payload"] = payload + return decoded + + def _decode_payload(self, decoded: dict[str, Any]) -> Any: + """ + Decode the payload from a JWS dictionary (payload, signature, header). + + This method is intended to be overridden by subclasses that need to + decode the payload in a different way, e.g. decompress compressed + payloads. + """ + try: + payload = json.loads(decoded["payload"]) + except ValueError as e: + raise DecodeError(f"Invalid payload string: {e}") from e + if not isinstance(payload, dict): + raise DecodeError("Invalid payload string: must be a json object") + return payload + + def decode( + self, + jwt: str | bytes, + key: AllowedPublicKeys | PyJWK | str | bytes = "", + algorithms: Sequence[str] | None = None, + options: dict[str, Any] | None = None, + # deprecated arg, remove in pyjwt3 + verify: bool | None = None, + # could be used as passthrough to api_jws, consider removal in pyjwt3 + detached_payload: bytes | None = None, + # passthrough arguments to _validate_claims + # consider putting in options + audience: str | Iterable[str] | None = None, + subject: str | None = None, + issuer: str | Sequence[str] | None = None, + leeway: float | timedelta = 0, + # kwargs + **kwargs: Any, + ) -> Any: + if kwargs: + warnings.warn( + "passing additional kwargs to decode() is deprecated " + "and will be removed in pyjwt version 3. " + f"Unsupported kwargs: {tuple(kwargs.keys())}", + RemovedInPyjwt3Warning, + stacklevel=2, + ) + decoded = self.decode_complete( + jwt, + key, + algorithms, + options, + verify=verify, + detached_payload=detached_payload, + audience=audience, + subject=subject, + issuer=issuer, + leeway=leeway, + ) + return decoded["payload"] + + def _validate_claims( + self, + payload: dict[str, Any], + options: dict[str, Any], + audience=None, + issuer=None, + subject: str | None = None, + leeway: float | timedelta = 0, + ) -> None: + if isinstance(leeway, timedelta): + leeway = leeway.total_seconds() + + if audience is not None and not isinstance(audience, (str, Iterable)): + raise TypeError("audience must be a string, iterable or None") + + self._validate_required_claims(payload, options) + + now = datetime.now(tz=timezone.utc).timestamp() + + if "iat" in payload and options["verify_iat"]: + self._validate_iat(payload, now, leeway) + + if "nbf" in payload and options["verify_nbf"]: + self._validate_nbf(payload, now, leeway) + + if "exp" in payload and options["verify_exp"]: + self._validate_exp(payload, now, leeway) + + if options["verify_iss"]: + self._validate_iss(payload, issuer) + + if options["verify_aud"]: + self._validate_aud( + payload, audience, strict=options.get("strict_aud", False) + ) + + if options["verify_sub"]: + self._validate_sub(payload, subject) + + if options["verify_jti"]: + self._validate_jti(payload) + + def _validate_required_claims( + self, + payload: dict[str, Any], + options: dict[str, Any], + ) -> None: + for claim in options["require"]: + if payload.get(claim) is None: + raise MissingRequiredClaimError(claim) + + def _validate_sub(self, payload: dict[str, Any], subject=None) -> None: + """ + Checks whether "sub" if in the payload is valid ot not. + This is an Optional claim + + :param payload(dict): The payload which needs to be validated + :param subject(str): The subject of the token + """ + + if "sub" not in payload: + return + + if not isinstance(payload["sub"], str): + raise InvalidSubjectError("Subject must be a string") + + if subject is not None: + if payload.get("sub") != subject: + raise InvalidSubjectError("Invalid subject") + + def _validate_jti(self, payload: dict[str, Any]) -> None: + """ + Checks whether "jti" if in the payload is valid ot not + This is an Optional claim + + :param payload(dict): The payload which needs to be validated + """ + + if "jti" not in payload: + return + + if not isinstance(payload.get("jti"), str): + raise InvalidJTIError("JWT ID must be a string") + + def _validate_iat( + self, + payload: dict[str, Any], + now: float, + leeway: float, + ) -> None: + try: + iat = int(payload["iat"]) + except ValueError: + raise InvalidIssuedAtError( + "Issued At claim (iat) must be an integer." + ) from None + if iat > (now + leeway): + raise ImmatureSignatureError("The token is not yet valid (iat)") + + def _validate_nbf( + self, + payload: dict[str, Any], + now: float, + leeway: float, + ) -> None: + try: + nbf = int(payload["nbf"]) + except ValueError: + raise DecodeError("Not Before claim (nbf) must be an integer.") from None + + if nbf > (now + leeway): + raise ImmatureSignatureError("The token is not yet valid (nbf)") + + def _validate_exp( + self, + payload: dict[str, Any], + now: float, + leeway: float, + ) -> None: + try: + exp = int(payload["exp"]) + except ValueError: + raise DecodeError( + "Expiration Time claim (exp) must be an integer." + ) from None + + if exp <= (now - leeway): + raise ExpiredSignatureError("Signature has expired") + + def _validate_aud( + self, + payload: dict[str, Any], + audience: str | Iterable[str] | None, + *, + strict: bool = False, + ) -> None: + if audience is None: + if "aud" not in payload or not payload["aud"]: + return + # Application did not specify an audience, but + # the token has the 'aud' claim + raise InvalidAudienceError("Invalid audience") + + if "aud" not in payload or not payload["aud"]: + # Application specified an audience, but it could not be + # verified since the token does not contain a claim. + raise MissingRequiredClaimError("aud") + + audience_claims = payload["aud"] + + # In strict mode, we forbid list matching: the supplied audience + # must be a string, and it must exactly match the audience claim. + if strict: + # Only a single audience is allowed in strict mode. + if not isinstance(audience, str): + raise InvalidAudienceError("Invalid audience (strict)") + + # Only a single audience claim is allowed in strict mode. + if not isinstance(audience_claims, str): + raise InvalidAudienceError("Invalid claim format in token (strict)") + + if audience != audience_claims: + raise InvalidAudienceError("Audience doesn't match (strict)") + + return + + if isinstance(audience_claims, str): + audience_claims = [audience_claims] + if not isinstance(audience_claims, list): + raise InvalidAudienceError("Invalid claim format in token") + if any(not isinstance(c, str) for c in audience_claims): + raise InvalidAudienceError("Invalid claim format in token") + + if isinstance(audience, str): + audience = [audience] + + if all(aud not in audience_claims for aud in audience): + raise InvalidAudienceError("Audience doesn't match") + + def _validate_iss(self, payload: dict[str, Any], issuer: Any) -> None: + if issuer is None: + return + + if "iss" not in payload: + raise MissingRequiredClaimError("iss") + + if isinstance(issuer, str): + if payload["iss"] != issuer: + raise InvalidIssuerError("Invalid issuer") + else: + if payload["iss"] not in issuer: + raise InvalidIssuerError("Invalid issuer") + + +_jwt_global_obj = PyJWT() +encode = _jwt_global_obj.encode +decode_complete = _jwt_global_obj.decode_complete +decode = _jwt_global_obj.decode diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/jwt/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..9b45ae48c4e0f2c7627c152bf0059e57f17b73ca --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/exceptions.py @@ -0,0 +1,82 @@ +class PyJWTError(Exception): + """ + Base class for all exceptions + """ + + pass + + +class InvalidTokenError(PyJWTError): + pass + + +class DecodeError(InvalidTokenError): + pass + + +class InvalidSignatureError(DecodeError): + pass + + +class ExpiredSignatureError(InvalidTokenError): + pass + + +class InvalidAudienceError(InvalidTokenError): + pass + + +class InvalidIssuerError(InvalidTokenError): + pass + + +class InvalidIssuedAtError(InvalidTokenError): + pass + + +class ImmatureSignatureError(InvalidTokenError): + pass + + +class InvalidKeyError(PyJWTError): + pass + + +class InvalidAlgorithmError(InvalidTokenError): + pass + + +class MissingRequiredClaimError(InvalidTokenError): + def __init__(self, claim: str) -> None: + self.claim = claim + + def __str__(self) -> str: + return f'Token is missing the "{self.claim}" claim' + + +class PyJWKError(PyJWTError): + pass + + +class MissingCryptographyError(PyJWKError): + pass + + +class PyJWKSetError(PyJWTError): + pass + + +class PyJWKClientError(PyJWTError): + pass + + +class PyJWKClientConnectionError(PyJWKClientError): + pass + + +class InvalidSubjectError(InvalidTokenError): + pass + + +class InvalidJTIError(InvalidTokenError): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/help.py b/data/miniconda3/lib/python3.13/site-packages/jwt/help.py new file mode 100644 index 0000000000000000000000000000000000000000..8e1c2286e7ea936292f525c44bcc1b0ee30c6560 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/help.py @@ -0,0 +1,67 @@ +import json +import platform +import sys +from typing import Dict + +from . import __version__ as pyjwt_version + +try: + import cryptography + + cryptography_version = cryptography.__version__ +except ModuleNotFoundError: + cryptography_version = "" + + +def info() -> Dict[str, Dict[str, str]]: + """ + Generate information for a bug report. + Based on the requests package help utility module. + """ + try: + platform_info = { + "system": platform.system(), + "release": platform.release(), + } + except OSError: + platform_info = {"system": "Unknown", "release": "Unknown"} + + implementation = platform.python_implementation() + + if implementation == "CPython": + implementation_version = platform.python_version() + elif implementation == "PyPy": + pypy_version_info = sys.pypy_version_info # type: ignore[attr-defined] + implementation_version = ( + f"{pypy_version_info.major}." + f"{pypy_version_info.minor}." + f"{pypy_version_info.micro}" + ) + if pypy_version_info.releaselevel != "final": + implementation_version = "".join( + [ + implementation_version, + pypy_version_info.releaselevel, + ] + ) + else: + implementation_version = "Unknown" + + return { + "platform": platform_info, + "implementation": { + "name": implementation, + "version": implementation_version, + }, + "cryptography": {"version": cryptography_version}, + "pyjwt": {"version": pyjwt_version}, + } + + +def main() -> None: + """Pretty-print the bug information as JSON.""" + print(json.dumps(info(), sort_keys=True, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/jwk_set_cache.py b/data/miniconda3/lib/python3.13/site-packages/jwt/jwk_set_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..2432563056a460c59d6e615968df456da3ec49cd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/jwk_set_cache.py @@ -0,0 +1,31 @@ +import time +from typing import Optional + +from .api_jwk import PyJWKSet, PyJWTSetWithTimestamp + + +class JWKSetCache: + def __init__(self, lifespan: int) -> None: + self.jwk_set_with_timestamp: Optional[PyJWTSetWithTimestamp] = None + self.lifespan = lifespan + + def put(self, jwk_set: PyJWKSet) -> None: + if jwk_set is not None: + self.jwk_set_with_timestamp = PyJWTSetWithTimestamp(jwk_set) + else: + # clear cache + self.jwk_set_with_timestamp = None + + def get(self) -> Optional[PyJWKSet]: + if self.jwk_set_with_timestamp is None or self.is_expired(): + return None + + return self.jwk_set_with_timestamp.get_jwk_set() + + def is_expired(self) -> bool: + return ( + self.jwk_set_with_timestamp is not None + and self.lifespan > -1 + and time.monotonic() + > self.jwk_set_with_timestamp.get_timestamp() + self.lifespan + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/jwks_client.py b/data/miniconda3/lib/python3.13/site-packages/jwt/jwks_client.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8992ca6b9d2be153e203b11465a8e6e7cdc570 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/jwks_client.py @@ -0,0 +1,126 @@ +import json +import urllib.request +from functools import lru_cache +from ssl import SSLContext +from typing import Any, Dict, List, Optional +from urllib.error import URLError + +from .api_jwk import PyJWK, PyJWKSet +from .api_jwt import decode_complete as decode_token +from .exceptions import PyJWKClientConnectionError, PyJWKClientError +from .jwk_set_cache import JWKSetCache + + +class PyJWKClient: + def __init__( + self, + uri: str, + cache_keys: bool = False, + max_cached_keys: int = 16, + cache_jwk_set: bool = True, + lifespan: int = 300, + headers: Optional[Dict[str, Any]] = None, + timeout: int = 30, + ssl_context: Optional[SSLContext] = None, + ): + if headers is None: + headers = {} + self.uri = uri + self.jwk_set_cache: Optional[JWKSetCache] = None + self.headers = headers + self.timeout = timeout + self.ssl_context = ssl_context + + if cache_jwk_set: + # Init jwt set cache with default or given lifespan. + # Default lifespan is 300 seconds (5 minutes). + if lifespan <= 0: + raise PyJWKClientError( + f'Lifespan must be greater than 0, the input is "{lifespan}"' + ) + self.jwk_set_cache = JWKSetCache(lifespan) + else: + self.jwk_set_cache = None + + if cache_keys: + # Cache signing keys + # Ignore mypy (https://github.com/python/mypy/issues/2427) + self.get_signing_key = lru_cache(maxsize=max_cached_keys)( + self.get_signing_key + ) # type: ignore + + def fetch_data(self) -> Any: + jwk_set: Any = None + try: + r = urllib.request.Request(url=self.uri, headers=self.headers) + with urllib.request.urlopen( + r, timeout=self.timeout, context=self.ssl_context + ) as response: + jwk_set = json.load(response) + except (URLError, TimeoutError) as e: + raise PyJWKClientConnectionError( + f'Fail to fetch data from the url, err: "{e}"' + ) from e + else: + return jwk_set + finally: + if self.jwk_set_cache is not None: + self.jwk_set_cache.put(jwk_set) + + def get_jwk_set(self, refresh: bool = False) -> PyJWKSet: + data = None + if self.jwk_set_cache is not None and not refresh: + data = self.jwk_set_cache.get() + + if data is None: + data = self.fetch_data() + + if not isinstance(data, dict): + raise PyJWKClientError("The JWKS endpoint did not return a JSON object") + + return PyJWKSet.from_dict(data) + + def get_signing_keys(self, refresh: bool = False) -> List[PyJWK]: + jwk_set = self.get_jwk_set(refresh) + signing_keys = [ + jwk_set_key + for jwk_set_key in jwk_set.keys + if jwk_set_key.public_key_use in ["sig", None] and jwk_set_key.key_id + ] + + if not signing_keys: + raise PyJWKClientError("The JWKS endpoint did not contain any signing keys") + + return signing_keys + + def get_signing_key(self, kid: str) -> PyJWK: + signing_keys = self.get_signing_keys() + signing_key = self.match_kid(signing_keys, kid) + + if not signing_key: + # If no matching signing key from the jwk set, refresh the jwk set and try again. + signing_keys = self.get_signing_keys(refresh=True) + signing_key = self.match_kid(signing_keys, kid) + + if not signing_key: + raise PyJWKClientError( + f'Unable to find a signing key that matches: "{kid}"' + ) + + return signing_key + + def get_signing_key_from_jwt(self, token: str) -> PyJWK: + unverified = decode_token(token, options={"verify_signature": False}) + header = unverified["header"] + return self.get_signing_key(header.get("kid")) + + @staticmethod + def match_kid(signing_keys: List[PyJWK], kid: str) -> Optional[PyJWK]: + signing_key = None + + for key in signing_keys: + if key.key_id == kid: + signing_key = key + break + + return signing_key diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/py.typed b/data/miniconda3/lib/python3.13/site-packages/jwt/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/types.py b/data/miniconda3/lib/python3.13/site-packages/jwt/types.py new file mode 100644 index 0000000000000000000000000000000000000000..7d9935205688a3cb45902017884633a490d59055 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/types.py @@ -0,0 +1,5 @@ +from typing import Any, Callable, Dict + +JWKDict = Dict[str, Any] + +HashlibHash = Callable[..., Any] diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/utils.py b/data/miniconda3/lib/python3.13/site-packages/jwt/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..56e89bb7782f4b5f61c9b2197258dcbf45335d33 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/utils.py @@ -0,0 +1,142 @@ +import base64 +import binascii +import re +from typing import Optional, Union + +try: + from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve + from cryptography.hazmat.primitives.asymmetric.utils import ( + decode_dss_signature, + encode_dss_signature, + ) +except ModuleNotFoundError: + pass + + +def force_bytes(value: Union[bytes, str]) -> bytes: + if isinstance(value, str): + return value.encode("utf-8") + elif isinstance(value, bytes): + return value + else: + raise TypeError("Expected a string value") + + +def base64url_decode(input: Union[bytes, str]) -> bytes: + input_bytes = force_bytes(input) + + rem = len(input_bytes) % 4 + + if rem > 0: + input_bytes += b"=" * (4 - rem) + + return base64.urlsafe_b64decode(input_bytes) + + +def base64url_encode(input: bytes) -> bytes: + return base64.urlsafe_b64encode(input).replace(b"=", b"") + + +def to_base64url_uint(val: int, *, bit_length: Optional[int] = None) -> bytes: + if val < 0: + raise ValueError("Must be a positive integer") + + int_bytes = bytes_from_int(val, bit_length=bit_length) + + if len(int_bytes) == 0: + int_bytes = b"\x00" + + return base64url_encode(int_bytes) + + +def from_base64url_uint(val: Union[bytes, str]) -> int: + data = base64url_decode(force_bytes(val)) + return int.from_bytes(data, byteorder="big") + + +def number_to_bytes(num: int, num_bytes: int) -> bytes: + padded_hex = "%0*x" % (2 * num_bytes, num) + return binascii.a2b_hex(padded_hex.encode("ascii")) + + +def bytes_to_number(string: bytes) -> int: + return int(binascii.b2a_hex(string), 16) + + +def bytes_from_int(val: int, *, bit_length: Optional[int] = None) -> bytes: + if bit_length is None: + bit_length = val.bit_length() + byte_length = (bit_length + 7) // 8 + + return val.to_bytes(byte_length, "big", signed=False) + + +def der_to_raw_signature(der_sig: bytes, curve: "EllipticCurve") -> bytes: + num_bits = curve.key_size + num_bytes = (num_bits + 7) // 8 + + r, s = decode_dss_signature(der_sig) + + return number_to_bytes(r, num_bytes) + number_to_bytes(s, num_bytes) + + +def raw_to_der_signature(raw_sig: bytes, curve: "EllipticCurve") -> bytes: + num_bits = curve.key_size + num_bytes = (num_bits + 7) // 8 + + if len(raw_sig) != 2 * num_bytes: + raise ValueError("Invalid signature") + + r = bytes_to_number(raw_sig[:num_bytes]) + s = bytes_to_number(raw_sig[num_bytes:]) + + return bytes(encode_dss_signature(r, s)) + + +# Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252 +_PEMS = { + b"CERTIFICATE", + b"TRUSTED CERTIFICATE", + b"PRIVATE KEY", + b"PUBLIC KEY", + b"ENCRYPTED PRIVATE KEY", + b"OPENSSH PRIVATE KEY", + b"DSA PRIVATE KEY", + b"RSA PRIVATE KEY", + b"RSA PUBLIC KEY", + b"EC PRIVATE KEY", + b"DH PARAMETERS", + b"NEW CERTIFICATE REQUEST", + b"CERTIFICATE REQUEST", + b"SSH2 PUBLIC KEY", + b"SSH2 ENCRYPTED PRIVATE KEY", + b"X509 CRL", +} + +_PEM_RE = re.compile( + b"----[- ]BEGIN (" + + b"|".join(_PEMS) + + b""")[- ]----\r? +.+?\r? +----[- ]END \\1[- ]----\r?\n?""", + re.DOTALL, +) + + +def is_pem_format(key: bytes) -> bool: + return bool(_PEM_RE.search(key)) + + +# Based on https://github.com/pyca/cryptography/blob/bcb70852d577b3f490f015378c75cba74986297b/src/cryptography/hazmat/primitives/serialization/ssh.py#L40-L46 +_SSH_KEY_FORMATS = ( + b"ssh-ed25519", + b"ssh-rsa", + b"ssh-dss", + b"ecdsa-sha2-nistp256", + b"ecdsa-sha2-nistp384", + b"ecdsa-sha2-nistp521", +) + + +def is_ssh_key(key: bytes) -> bool: + return key.startswith(_SSH_KEY_FORMATS) diff --git a/data/miniconda3/lib/python3.13/site-packages/jwt/warnings.py b/data/miniconda3/lib/python3.13/site-packages/jwt/warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..8762a8cbb3408b5b30901d4dd39fc53097eb31d8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/jwt/warnings.py @@ -0,0 +1,2 @@ +class RemovedInPyjwt3Warning(DeprecationWarning): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/libmambapy/__init__.py b/data/miniconda3/lib/python3.13/site-packages/libmambapy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e780c64b3dddb08c8fa3e1557dcc8d2bafa16d32 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/libmambapy/__init__.py @@ -0,0 +1,11 @@ +# Import all submodules so that one can use them directly with `import libmambapy` +import libmambapy.utils +import libmambapy.version +import libmambapy.specs +import libmambapy.solver + +# Legacy which used to combine everything +from libmambapy.bindings.legacy import * # noqa: F403 + +# Define top-level attributes +__version__ = libmambapy.version.__version__ diff --git a/data/miniconda3/lib/python3.13/site-packages/libmambapy/specs.py b/data/miniconda3/lib/python3.13/site-packages/libmambapy/specs.py new file mode 100644 index 0000000000000000000000000000000000000000..b7c25d844a3c64f49cc69f846d4b958443c37270 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/libmambapy/specs.py @@ -0,0 +1,2 @@ +# This file exists on its own rather than in `__init__.py` to make `import libmambapy.specs` work. +from libmambapy.bindings.specs import * # noqa: F403 diff --git a/data/miniconda3/lib/python3.13/site-packages/libmambapy/utils.py b/data/miniconda3/lib/python3.13/site-packages/libmambapy/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..febe6dfedc755d07f8f9df8b7e35f179f2fcc041 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/libmambapy/utils.py @@ -0,0 +1,2 @@ +# This file exists on its own rather than in `__init__.py` to make `import libmambapy.utils` work. +from libmambapy.bindings.utils import * # noqa: F403 diff --git a/data/miniconda3/lib/python3.13/site-packages/libmambapy/version.py b/data/miniconda3/lib/python3.13/site-packages/libmambapy/version.py new file mode 100644 index 0000000000000000000000000000000000000000..07e8bcd1a955e2b33d0daae79ed59875d799dfb6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/libmambapy/version.py @@ -0,0 +1,5 @@ +version_info = ("2", "3", "2") +version_prerelease = "" +__version__ = ".".join(map(str, version_info)) +if version_prerelease != "": + __version__ = f"{__version__}.{version_prerelease}" diff --git a/data/miniconda3/lib/python3.13/site-packages/mapbox_earcut/__init__.py b/data/miniconda3/lib/python3.13/site-packages/mapbox_earcut/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6749183b6221c0170afd76ed8b0d0dda497eeda2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mapbox_earcut/__init__.py @@ -0,0 +1,22 @@ +""" +Python bindings for the mapbox earcut C++ polygon triangulation library. + +This module provides fast triangulation of 2D polygons using the Mapbox Earcut algorithm. +""" + +# Import all functions from the compiled extension module +from ._core import ( + triangulate_float32, + triangulate_float64, + triangulate_int32, + triangulate_int64, + __version__, +) + +__all__ = [ + "triangulate_float32", + "triangulate_float64", + "triangulate_int32", + "triangulate_int64", + "__version__", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/mapbox_earcut/_core.pyi b/data/miniconda3/lib/python3.13/site-packages/mapbox_earcut/_core.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0d7c9e2efec6f6bbfc4609e8a89efe6304da1a8b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mapbox_earcut/_core.pyi @@ -0,0 +1,13 @@ +from typing import Annotated + +import numpy +from numpy.typing import NDArray + + +def triangulate_int32(arg0: Annotated[NDArray[numpy.int32], dict(shape=(None, 2), device='cpu')], arg1: Annotated[NDArray[numpy.uint32], dict(shape=(None,), device='cpu')], /) -> Annotated[NDArray[numpy.uint32], dict(shape=(None,))]: ... + +def triangulate_int64(arg0: Annotated[NDArray[numpy.int64], dict(shape=(None, 2), device='cpu')], arg1: Annotated[NDArray[numpy.uint32], dict(shape=(None,), device='cpu')], /) -> Annotated[NDArray[numpy.uint32], dict(shape=(None,))]: ... + +def triangulate_float32(arg0: Annotated[NDArray[numpy.float32], dict(shape=(None, 2), device='cpu')], arg1: Annotated[NDArray[numpy.uint32], dict(shape=(None,), device='cpu')], /) -> Annotated[NDArray[numpy.uint32], dict(shape=(None,))]: ... + +def triangulate_float64(arg0: Annotated[NDArray[numpy.float64], dict(shape=(None, 2), device='cpu')], arg1: Annotated[NDArray[numpy.uint32], dict(shape=(None,), device='cpu')], /) -> Annotated[NDArray[numpy.uint32], dict(shape=(None,))]: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/mapbox_earcut/py.typed b/data/miniconda3/lib/python3.13/site-packages/mapbox_earcut/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0f2b466a638a34e304c69fb7976ab05a736d9ab8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/METADATA @@ -0,0 +1,219 @@ +Metadata-Version: 2.4 +Name: markdown-it-py +Version: 4.0.0 +Summary: Python port of markdown-it. Markdown parsing, done right! +Keywords: markdown,lexer,parser,commonmark,markdown-it +Author-email: Chris Sewell +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup +License-File: LICENSE +License-File: LICENSE.markdown-it +Requires-Dist: mdurl~=0.1 +Requires-Dist: psutil ; extra == "benchmarking" +Requires-Dist: pytest ; extra == "benchmarking" +Requires-Dist: pytest-benchmark ; extra == "benchmarking" +Requires-Dist: commonmark~=0.9 ; extra == "compare" +Requires-Dist: markdown~=3.4 ; extra == "compare" +Requires-Dist: mistletoe~=1.0 ; extra == "compare" +Requires-Dist: mistune~=3.0 ; extra == "compare" +Requires-Dist: panflute~=2.3 ; extra == "compare" +Requires-Dist: markdown-it-pyrs ; extra == "compare" +Requires-Dist: linkify-it-py>=1,<3 ; extra == "linkify" +Requires-Dist: mdit-py-plugins>=0.5.0 ; extra == "plugins" +Requires-Dist: gprof2dot ; extra == "profiling" +Requires-Dist: mdit-py-plugins>=0.5.0 ; extra == "rtd" +Requires-Dist: myst-parser ; extra == "rtd" +Requires-Dist: pyyaml ; extra == "rtd" +Requires-Dist: sphinx ; extra == "rtd" +Requires-Dist: sphinx-copybutton ; extra == "rtd" +Requires-Dist: sphinx-design ; extra == "rtd" +Requires-Dist: sphinx-book-theme~=1.0 ; extra == "rtd" +Requires-Dist: jupyter_sphinx ; extra == "rtd" +Requires-Dist: ipykernel ; extra == "rtd" +Requires-Dist: coverage ; extra == "testing" +Requires-Dist: pytest ; extra == "testing" +Requires-Dist: pytest-cov ; extra == "testing" +Requires-Dist: pytest-regressions ; extra == "testing" +Requires-Dist: requests ; extra == "testing" +Project-URL: Documentation, https://markdown-it-py.readthedocs.io +Project-URL: Homepage, https://github.com/executablebooks/markdown-it-py +Provides-Extra: benchmarking +Provides-Extra: compare +Provides-Extra: linkify +Provides-Extra: plugins +Provides-Extra: profiling +Provides-Extra: rtd +Provides-Extra: testing + +# markdown-it-py + +[![Github-CI][github-ci]][github-link] +[![Coverage Status][codecov-badge]][codecov-link] +[![PyPI][pypi-badge]][pypi-link] +[![Conda][conda-badge]][conda-link] +[![PyPI - Downloads][install-badge]][install-link] + +

+ markdown-it-py icon +

+ +> Markdown parser done right. + +- Follows the __[CommonMark spec](http://spec.commonmark.org/)__ for baseline parsing +- Configurable syntax: you can add new rules and even replace existing ones. +- Pluggable: Adds syntax extensions to extend the parser (see the [plugin list][md-plugins]). +- High speed (see our [benchmarking tests][md-performance]) +- Easy to configure for [security][md-security] +- Member of [Google's Assured Open Source Software](https://cloud.google.com/assured-open-source-software/docs/supported-packages) + +This is a Python port of [markdown-it], and some of its associated plugins. +For more details see: . + +For details on [markdown-it] itself, see: + +- The __[Live demo](https://markdown-it.github.io)__ +- [The markdown-it README][markdown-it-readme] + +**See also:** [markdown-it-pyrs](https://github.com/chrisjsewell/markdown-it-pyrs) for an experimental Rust binding, +for even more speed! + +## Installation + +### PIP + +```bash +pip install markdown-it-py[plugins] +``` + +or with extras + +```bash +pip install markdown-it-py[linkify,plugins] +``` + +### Conda + +```bash +conda install -c conda-forge markdown-it-py +``` + +or with extras + +```bash +conda install -c conda-forge markdown-it-py linkify-it-py mdit-py-plugins +``` + +## Usage + +### Python API Usage + +Render markdown to HTML with markdown-it-py and a custom configuration +with and without plugins and features: + +```python +from markdown_it import MarkdownIt +from mdit_py_plugins.front_matter import front_matter_plugin +from mdit_py_plugins.footnote import footnote_plugin + +md = ( + MarkdownIt('commonmark', {'breaks':True,'html':True}) + .use(front_matter_plugin) + .use(footnote_plugin) + .enable('table') +) +text = (""" +--- +a: 1 +--- + +a | b +- | - +1 | 2 + +A footnote [^1] + +[^1]: some details +""") +tokens = md.parse(text) +html_text = md.render(text) + +## To export the html to a file, uncomment the lines below: +# from pathlib import Path +# Path("output.html").write_text(html_text) +``` + +### Command-line Usage + +Render markdown to HTML with markdown-it-py from the +command-line: + +```console +usage: markdown-it [-h] [-v] [filenames [filenames ...]] + +Parse one or more markdown files, convert each to HTML, and print to stdout + +positional arguments: + filenames specify an optional list of files to convert + +optional arguments: + -h, --help show this help message and exit + -v, --version show program's version number and exit + +Interactive: + + $ markdown-it + markdown-it-py [version 0.0.0] (interactive) + Type Ctrl-D to complete input, or Ctrl-C to exit. + >>> # Example + ... > markdown *input* + ... +

Example

+
+

markdown input

+
+ +Batch: + + $ markdown-it README.md README.footer.md > index.html + +``` + +## References / Thanks + +Big thanks to the authors of [markdown-it]: + +- Alex Kocharin [github/rlidwka](https://github.com/rlidwka) +- Vitaly Puzrin [github/puzrin](https://github.com/puzrin) + +Also [John MacFarlane](https://github.com/jgm) for his work on the CommonMark spec and reference implementations. + +[github-ci]: https://github.com/executablebooks/markdown-it-py/actions/workflows/tests.yml/badge.svg?branch=master +[github-link]: https://github.com/executablebooks/markdown-it-py +[pypi-badge]: https://img.shields.io/pypi/v/markdown-it-py.svg +[pypi-link]: https://pypi.org/project/markdown-it-py +[conda-badge]: https://anaconda.org/conda-forge/markdown-it-py/badges/version.svg +[conda-link]: https://anaconda.org/conda-forge/markdown-it-py +[codecov-badge]: https://codecov.io/gh/executablebooks/markdown-it-py/branch/master/graph/badge.svg +[codecov-link]: https://codecov.io/gh/executablebooks/markdown-it-py +[install-badge]: https://img.shields.io/pypi/dw/markdown-it-py?label=pypi%20installs +[install-link]: https://pypistats.org/packages/markdown-it-py + +[CommonMark spec]: http://spec.commonmark.org/ +[markdown-it]: https://github.com/markdown-it/markdown-it +[markdown-it-readme]: https://github.com/markdown-it/markdown-it/blob/master/README.md +[md-security]: https://markdown-it-py.readthedocs.io/en/latest/security.html +[md-performance]: https://markdown-it-py.readthedocs.io/en/latest/performance.html +[md-plugins]: https://markdown-it-py.readthedocs.io/en/latest/plugins.html + diff --git a/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a6cf01fc5a6267cb1c7e6e1ca41aca71fac84cc2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/RECORD @@ -0,0 +1,144 @@ +../../../bin/markdown-it,sha256=dH-ej7-8p3EU8zdKJzE61u-jJx--xcy3BxYugHlB2A0,503 +markdown_it/__init__.py,sha256=R7fMvDxageYJ4Q6doBcimogy1ctcV1eBuCFu5Pr8bbA,114 +markdown_it/__pycache__/__init__.cpython-313.pyc,, +markdown_it/__pycache__/_compat.cpython-313.pyc,, +markdown_it/__pycache__/_punycode.cpython-313.pyc,, +markdown_it/__pycache__/main.cpython-313.pyc,, +markdown_it/__pycache__/parser_block.cpython-313.pyc,, +markdown_it/__pycache__/parser_core.cpython-313.pyc,, +markdown_it/__pycache__/parser_inline.cpython-313.pyc,, +markdown_it/__pycache__/renderer.cpython-313.pyc,, +markdown_it/__pycache__/ruler.cpython-313.pyc,, +markdown_it/__pycache__/token.cpython-313.pyc,, +markdown_it/__pycache__/tree.cpython-313.pyc,, +markdown_it/__pycache__/utils.cpython-313.pyc,, +markdown_it/_compat.py,sha256=U4S_2y3zgLZVfMenHRaJFBW8yqh2mUBuI291LGQVOJ8,35 +markdown_it/_punycode.py,sha256=JvSOZJ4VKr58z7unFGM0KhfTxqHMk2w8gglxae2QszM,2373 +markdown_it/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +markdown_it/cli/__pycache__/__init__.cpython-313.pyc,, +markdown_it/cli/__pycache__/parse.cpython-313.pyc,, +markdown_it/cli/parse.py,sha256=Un3N7fyGHhZAQouGVnRx-WZcpKwEK2OF08rzVAEBie8,2881 +markdown_it/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +markdown_it/common/__pycache__/__init__.cpython-313.pyc,, +markdown_it/common/__pycache__/entities.cpython-313.pyc,, +markdown_it/common/__pycache__/html_blocks.cpython-313.pyc,, +markdown_it/common/__pycache__/html_re.cpython-313.pyc,, +markdown_it/common/__pycache__/normalize_url.cpython-313.pyc,, +markdown_it/common/__pycache__/utils.cpython-313.pyc,, +markdown_it/common/entities.py,sha256=EYRCmUL7ZU1FRGLSXQlPx356lY8EUBdFyx96eSGc6d0,157 +markdown_it/common/html_blocks.py,sha256=QXbUDMoN9lXLgYFk2DBYllnLiFukL6dHn2X98Y6Wews,986 +markdown_it/common/html_re.py,sha256=FggAEv9IL8gHQqsGTkHcf333rTojwG0DQJMH9oVu0fU,926 +markdown_it/common/normalize_url.py,sha256=avOXnLd9xw5jU1q5PLftjAM9pvGx8l9QDEkmZSyrMgg,2568 +markdown_it/common/utils.py,sha256=pMgvMOE3ZW-BdJ7HfuzlXNKyD1Ivk7jHErc2J_B8J5M,8734 +markdown_it/helpers/__init__.py,sha256=YH2z7dS0WUc_9l51MWPvrLtFoBPh4JLGw58OuhGRCK0,253 +markdown_it/helpers/__pycache__/__init__.cpython-313.pyc,, +markdown_it/helpers/__pycache__/parse_link_destination.cpython-313.pyc,, +markdown_it/helpers/__pycache__/parse_link_label.cpython-313.pyc,, +markdown_it/helpers/__pycache__/parse_link_title.cpython-313.pyc,, +markdown_it/helpers/parse_link_destination.py,sha256=u-xxWVP3g1s7C1bQuQItiYyDrYoYHJzXaZXPgr-o6mY,1906 +markdown_it/helpers/parse_link_label.py,sha256=PIHG6ZMm3BUw0a2m17lCGqNrl3vaz911tuoGviWD3I4,1037 +markdown_it/helpers/parse_link_title.py,sha256=jkLoYQMKNeX9bvWQHkaSroiEo27HylkEUNmj8xBRlp4,2273 +markdown_it/main.py,sha256=vzuT23LJyKrPKNyHKKAbOHkNWpwIldOGUM-IGsv2DHM,12732 +markdown_it/parser_block.py,sha256=-MyugXB63Te71s4NcSQZiK5bE6BHkdFyZv_bviuatdI,3939 +markdown_it/parser_core.py,sha256=SRmJjqe8dC6GWzEARpWba59cBmxjCr3Gsg8h29O8sQk,1016 +markdown_it/parser_inline.py,sha256=y0jCig8CJxQO7hBz0ZY3sGvPlAKTohOwIgaqnlSaS5A,5024 +markdown_it/port.yaml,sha256=jt_rdwOnfocOV5nc35revTybAAQMIp_-1fla_527sVE,2447 +markdown_it/presets/__init__.py,sha256=22vFtwJEY7iqFRtgVZ-pJthcetfpr1Oig8XOF9x1328,970 +markdown_it/presets/__pycache__/__init__.cpython-313.pyc,, +markdown_it/presets/__pycache__/commonmark.cpython-313.pyc,, +markdown_it/presets/__pycache__/default.cpython-313.pyc,, +markdown_it/presets/__pycache__/zero.cpython-313.pyc,, +markdown_it/presets/commonmark.py,sha256=ygfb0R7WQ_ZoyQP3df-B0EnYMqNXCVOSw9SAdMjsGow,2869 +markdown_it/presets/default.py,sha256=FfKVUI0HH3M-_qy6RwotLStdC4PAaAxE7Dq0_KQtRtc,1811 +markdown_it/presets/zero.py,sha256=okXWTBEI-2nmwx5XKeCjxInRf65oC11gahtRl-QNtHM,2113 +markdown_it/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 +markdown_it/renderer.py,sha256=Lzr0glqd5oxFL10DOfjjW8kg4Gp41idQ4viEQaE47oA,9947 +markdown_it/ruler.py,sha256=eMAtWGRAfSM33aiJed0k5923BEkuMVsMq1ct8vU-ql4,9142 +markdown_it/rules_block/__init__.py,sha256=SQpg0ocmsHeILPAWRHhzgLgJMKIcNkQyELH13o_6Ktc,553 +markdown_it/rules_block/__pycache__/__init__.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/blockquote.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/code.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/fence.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/heading.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/hr.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/html_block.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/lheading.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/list.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/paragraph.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/reference.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/state_block.cpython-313.pyc,, +markdown_it/rules_block/__pycache__/table.cpython-313.pyc,, +markdown_it/rules_block/blockquote.py,sha256=7uymS36dcrned3DsIaRcqcbFU1NlymhvsZpEXTD3_n8,8887 +markdown_it/rules_block/code.py,sha256=iTAxv0U1-MDhz88M1m1pi2vzOhEMSEROsXMo2Qq--kU,860 +markdown_it/rules_block/fence.py,sha256=BJgU-PqZ4vAlCqGcrc8UtdLpJJyMeRWN-G-Op-zxrMc,2537 +markdown_it/rules_block/heading.py,sha256=4Lh15rwoVsQjE1hVhpbhidQ0k9xKHihgjAeYSbwgO5k,1745 +markdown_it/rules_block/hr.py,sha256=QCoY5kImaQRvF7PyP8OoWft6A8JVH1v6MN-0HR9Ikpg,1227 +markdown_it/rules_block/html_block.py,sha256=wA8pb34LtZr1BkIATgGKQBIGX5jQNOkwZl9UGEqvb5M,2721 +markdown_it/rules_block/lheading.py,sha256=fWoEuUo7S2svr5UMKmyQMkh0hheYAHg2gMM266Mogs4,2625 +markdown_it/rules_block/list.py,sha256=gIodkAJFyOIyKCZCj5lAlL7jIj5kAzrDb-K-2MFNplY,9668 +markdown_it/rules_block/paragraph.py,sha256=9pmCwA7eMu4LBdV4fWKzC4EdwaOoaGw2kfeYSQiLye8,1819 +markdown_it/rules_block/reference.py,sha256=ue1qZbUaUP0GIvwTjh6nD1UtCij8uwsIMuYW1xBkckc,6983 +markdown_it/rules_block/state_block.py,sha256=HowsQyy5hGUibH4HRZWKfLIlXeDUnuWL7kpF0-rSwoM,8422 +markdown_it/rules_block/table.py,sha256=8nMd9ONGOffER7BXmc9kbbhxkLjtpX79dVLR0iatGnM,7682 +markdown_it/rules_core/__init__.py,sha256=QFGBe9TUjnRQJDU7xY4SQYpxyTHNwg8beTSwXpNGRjE,394 +markdown_it/rules_core/__pycache__/__init__.cpython-313.pyc,, +markdown_it/rules_core/__pycache__/block.cpython-313.pyc,, +markdown_it/rules_core/__pycache__/inline.cpython-313.pyc,, +markdown_it/rules_core/__pycache__/linkify.cpython-313.pyc,, +markdown_it/rules_core/__pycache__/normalize.cpython-313.pyc,, +markdown_it/rules_core/__pycache__/replacements.cpython-313.pyc,, +markdown_it/rules_core/__pycache__/smartquotes.cpython-313.pyc,, +markdown_it/rules_core/__pycache__/state_core.cpython-313.pyc,, +markdown_it/rules_core/__pycache__/text_join.cpython-313.pyc,, +markdown_it/rules_core/block.py,sha256=0_JY1CUy-H2OooFtIEZAACtuoGUMohgxo4Z6A_UinSg,372 +markdown_it/rules_core/inline.py,sha256=9oWmeBhJHE7x47oJcN9yp6UsAZtrEY_A-VmfoMvKld4,325 +markdown_it/rules_core/linkify.py,sha256=mjQqpk_lHLh2Nxw4UFaLxa47Fgi-OHnmDamlgXnhmv0,5141 +markdown_it/rules_core/normalize.py,sha256=AJm4femtFJ_QBnM0dzh0UNqTTJk9K6KMtwRPaioZFqM,403 +markdown_it/rules_core/replacements.py,sha256=CH75mie-tdzdLKQtMBuCTcXAl1ijegdZGfbV_Vk7st0,3471 +markdown_it/rules_core/smartquotes.py,sha256=izK9fSyuTzA-zAUGkRkz9KwwCQWo40iRqcCKqOhFbEE,7443 +markdown_it/rules_core/state_core.py,sha256=HqWZCUr5fW7xG6jeQZDdO0hE9hxxyl3_-bawgOy57HY,570 +markdown_it/rules_core/text_join.py,sha256=rLXxNuLh_es5RvH31GsXi7en8bMNO9UJ5nbJMDBPltY,1173 +markdown_it/rules_inline/__init__.py,sha256=qqHZk6-YE8Rc12q6PxvVKBaxv2wmZeeo45H1XMR_Vxs,696 +markdown_it/rules_inline/__pycache__/__init__.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/autolink.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/backticks.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/balance_pairs.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/emphasis.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/entity.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/escape.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/fragments_join.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/html_inline.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/image.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/link.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/linkify.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/newline.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/state_inline.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/strikethrough.cpython-313.pyc,, +markdown_it/rules_inline/__pycache__/text.cpython-313.pyc,, +markdown_it/rules_inline/autolink.py,sha256=pPoqJY8i99VtFn7KgUzMackMeq1hytzioVvWs-VQPRo,2065 +markdown_it/rules_inline/backticks.py,sha256=J7bezjjNxiXlKqvHc0fJkHZwH7-2nBsXVjcKydk8E4M,2037 +markdown_it/rules_inline/balance_pairs.py,sha256=5zgBiGidqdiWmt7Io_cuZOYh5EFEfXrYRce8RXg5m7o,4852 +markdown_it/rules_inline/emphasis.py,sha256=7aDLZx0Jlekuvbu3uEUTDhJp00Z0Pj6g4C3-VLhI8Co,3123 +markdown_it/rules_inline/entity.py,sha256=CE8AIGMi5isEa24RNseo0wRmTTaj5YLbgTFdDmBesAU,1651 +markdown_it/rules_inline/escape.py,sha256=KGulwrP5FnqZM7GXY8lf7pyVv0YkR59taZDeHb5cmKg,1659 +markdown_it/rules_inline/fragments_join.py,sha256=_3JbwWYJz74gRHeZk6T8edVJT2IVSsi7FfmJJlieQlA,1493 +markdown_it/rules_inline/html_inline.py,sha256=SBg6HR0HRqCdrkkec0dfOYuQdAqyfeLRFLeQggtgjvg,1130 +markdown_it/rules_inline/image.py,sha256=Wbsg7jgnOtKXIwXGNJOlG7ORThkMkBVolxItC0ph6C0,4141 +markdown_it/rules_inline/link.py,sha256=2oD-fAdB0xyxDRtZLTjzLeWbzJ1k9bbPVQmohb58RuI,4258 +markdown_it/rules_inline/linkify.py,sha256=ifH6sb5wE8PGMWEw9Sr4x0DhMVfNOEBCfFSwKll2O-s,1706 +markdown_it/rules_inline/newline.py,sha256=329r0V3aDjzNtJcvzA3lsFYjzgBrShLAV5uf9hwQL_M,1297 +markdown_it/rules_inline/state_inline.py,sha256=d-menFzbz5FDy1JNgGBF-BASasnVI-9RuOxWz9PnKn4,5003 +markdown_it/rules_inline/strikethrough.py,sha256=pwcPlyhkh5pqFVxRCSrdW5dNCIOtU4eDit7TVDTPIVA,3214 +markdown_it/rules_inline/text.py,sha256=FQqaQRUqbnMLO9ZSWPWQUMEKH6JqWSSSmlZ5Ii9P48o,1119 +markdown_it/token.py,sha256=cWrt9kodfPdizHq_tYrzyIZNtJYNMN1813DPNlunwTg,6381 +markdown_it/tree.py,sha256=56Cdbwu2Aiks7kNYqO_fQZWpPb_n48CUllzjQQfgu1Y,11111 +markdown_it/utils.py,sha256=lVLeX7Af3GaNFfxmMgUbsn5p7cXbwhLq7RSf56UWuRE,5687 +markdown_it_py-4.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +markdown_it_py-4.0.0.dist-info/METADATA,sha256=6fyqHi2vP5bYQKCfuqo5T-qt83o22Ip7a2tnJIfGW_s,7288 +markdown_it_py-4.0.0.dist-info/RECORD,, +markdown_it_py-4.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +markdown_it_py-4.0.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +markdown_it_py-4.0.0.dist-info/direct_url.json,sha256=ZYT2w3sPb6DO5d8HIoEqd2rtXtsCLMabzyV9OS2amMM,74 +markdown_it_py-4.0.0.dist-info/entry_points.txt,sha256=T81l7fHQ3pllpQ4wUtQK6a8g_p6wxQbnjKVHCk2WMG4,58 +markdown_it_py-4.0.0.dist-info/licenses/LICENSE,sha256=SiJg1uLND1oVGh6G2_59PtVSseK-q_mUHBulxJy85IQ,1078 +markdown_it_py-4.0.0.dist-info/licenses/LICENSE.markdown-it,sha256=eSxIxahJoV_fnjfovPnm0d0TsytGxkKnSKCkapkZ1HM,1073 diff --git a/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..6b63f400cda3f2ae505e0d4291adf7f53b89c912 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/markdown-it-py_1756299186942/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d829cd792a5d754844f433c6a8dd499564fdcbf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/markdown_it_py-4.0.0.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +markdown-it=markdown_it.cli.parse:main + diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..635d84897abf2d079ef84a7a729b5d4d7ceb2a3b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/METADATA @@ -0,0 +1,33 @@ +Metadata-Version: 2.4 +Name: mdurl +Version: 0.1.2 +Summary: Markdown URL utilities +Keywords: markdown,commonmark +Author-email: Taneli Hukkinen +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +License-File: LICENSE +Project-URL: Homepage, https://github.com/executablebooks/mdurl + +# mdurl + +[![Build Status](https://github.com/executablebooks/mdurl/workflows/Tests/badge.svg?branch=master)](https://github.com/executablebooks/mdurl/actions?query=workflow%3ATests+branch%3Amaster+event%3Apush) +[![codecov.io](https://codecov.io/gh/executablebooks/mdurl/branch/master/graph/badge.svg)](https://codecov.io/gh/executablebooks/mdurl) +[![PyPI version](https://img.shields.io/pypi/v/mdurl)](https://pypi.org/project/mdurl) + +This is a Python port of the JavaScript [mdurl](https://www.npmjs.com/package/mdurl) package. +See the [upstream README.md file](https://github.com/markdown-it/mdurl/blob/master/README.md) for API documentation. + diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a5030004b67a736406bd1d1c98c32bb81ad9fa5d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/RECORD @@ -0,0 +1,20 @@ +mdurl-0.1.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +mdurl-0.1.2.dist-info/METADATA,sha256=q3vCoQWi3ousAZEfxEQi2e0OFZbHmbu61D5VnLEe-F0,1660 +mdurl-0.1.2.dist-info/RECORD,, +mdurl-0.1.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mdurl-0.1.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +mdurl-0.1.2.dist-info/direct_url.json,sha256=ZfxTEeB_-ifxVs3cnUCsKWsTH_E8S-z5eHyT7UUq-A0,95 +mdurl-0.1.2.dist-info/licenses/LICENSE,sha256=fGBd9uKGZ6lgMRjpgnT2SknOPu0NJvzM6VNKNF4O-VU,2338 +mdurl/__init__.py,sha256=1vpE89NyXniIRZNC_4f6BPm3Ub4bPntjfyyhLRR7opU,547 +mdurl/__pycache__/__init__.cpython-313.pyc,, +mdurl/__pycache__/_decode.cpython-313.pyc,, +mdurl/__pycache__/_encode.cpython-313.pyc,, +mdurl/__pycache__/_format.cpython-313.pyc,, +mdurl/__pycache__/_parse.cpython-313.pyc,, +mdurl/__pycache__/_url.cpython-313.pyc,, +mdurl/_decode.py,sha256=3Q_gDQqU__TvDbu7x-b9LjbVl4QWy5g_qFwljcuvN_Y,3004 +mdurl/_encode.py,sha256=goJLUFt1h4rVZNqqm9t15Nw2W-bFXYQEy3aR01ImWvs,2602 +mdurl/_format.py,sha256=xZct0mdePXA0H3kAqxjGtlB5O86G35DAYMGkA44CmB4,626 +mdurl/_parse.py,sha256=ezZSkM2_4NQ2Zx047sEdcJG7NYQRFHiZK7Y8INHFzwY,11374 +mdurl/_url.py,sha256=5kQnRQN2A_G4svLnRzZcG0bfoD9AbBrYDXousDHZ3z0,284 +mdurl/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..ca8b874655ed263901b2c63ef6d03c3c5d5803db --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl-0.1.2.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_175855216352428/conda-bld/mdurl_1758552176751/work"} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl/__init__.py b/data/miniconda3/lib/python3.13/site-packages/mdurl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cdbb640e004cef0e950a656a53d92d89d82c7472 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl/__init__.py @@ -0,0 +1,18 @@ +__all__ = ( + "decode", + "DECODE_DEFAULT_CHARS", + "DECODE_COMPONENT_CHARS", + "encode", + "ENCODE_DEFAULT_CHARS", + "ENCODE_COMPONENT_CHARS", + "format", + "parse", + "URL", +) +__version__ = "0.1.2" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT + +from mdurl._decode import DECODE_COMPONENT_CHARS, DECODE_DEFAULT_CHARS, decode +from mdurl._encode import ENCODE_COMPONENT_CHARS, ENCODE_DEFAULT_CHARS, encode +from mdurl._format import format +from mdurl._parse import url_parse as parse +from mdurl._url import URL diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl/_decode.py b/data/miniconda3/lib/python3.13/site-packages/mdurl/_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..9b50a2dde976a6d43491ec6f20d12e60f6f6597f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl/_decode.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +from collections.abc import Sequence +import functools +import re + +DECODE_DEFAULT_CHARS = ";/?:@&=+$,#" +DECODE_COMPONENT_CHARS = "" + +decode_cache: dict[str, list[str]] = {} + + +def get_decode_cache(exclude: str) -> Sequence[str]: + if exclude in decode_cache: + return decode_cache[exclude] + + cache: list[str] = [] + decode_cache[exclude] = cache + + for i in range(128): + ch = chr(i) + cache.append(ch) + + for i in range(len(exclude)): + ch_code = ord(exclude[i]) + cache[ch_code] = "%" + ("0" + hex(ch_code)[2:].upper())[-2:] + + return cache + + +# Decode percent-encoded string. +# +def decode(string: str, exclude: str = DECODE_DEFAULT_CHARS) -> str: + cache = get_decode_cache(exclude) + repl_func = functools.partial(repl_func_with_cache, cache=cache) + return re.sub(r"(%[a-f0-9]{2})+", repl_func, string, flags=re.IGNORECASE) + + +def repl_func_with_cache(match: re.Match, cache: Sequence[str]) -> str: + seq = match.group() + result = "" + + i = 0 + l = len(seq) # noqa: E741 + while i < l: + b1 = int(seq[i + 1 : i + 3], 16) + + if b1 < 0x80: + result += cache[b1] + i += 3 # emulate JS for loop statement3 + continue + + if (b1 & 0xE0) == 0xC0 and (i + 3 < l): + # 110xxxxx 10xxxxxx + b2 = int(seq[i + 4 : i + 6], 16) + + if (b2 & 0xC0) == 0x80: + all_bytes = bytes((b1, b2)) + try: + result += all_bytes.decode() + except UnicodeDecodeError: + result += "\ufffd" * 2 + + i += 3 + i += 3 # emulate JS for loop statement3 + continue + + if (b1 & 0xF0) == 0xE0 and (i + 6 < l): + # 1110xxxx 10xxxxxx 10xxxxxx + b2 = int(seq[i + 4 : i + 6], 16) + b3 = int(seq[i + 7 : i + 9], 16) + + if (b2 & 0xC0) == 0x80 and (b3 & 0xC0) == 0x80: + all_bytes = bytes((b1, b2, b3)) + try: + result += all_bytes.decode() + except UnicodeDecodeError: + result += "\ufffd" * 3 + + i += 6 + i += 3 # emulate JS for loop statement3 + continue + + if (b1 & 0xF8) == 0xF0 and (i + 9 < l): + # 111110xx 10xxxxxx 10xxxxxx 10xxxxxx + b2 = int(seq[i + 4 : i + 6], 16) + b3 = int(seq[i + 7 : i + 9], 16) + b4 = int(seq[i + 10 : i + 12], 16) + + if (b2 & 0xC0) == 0x80 and (b3 & 0xC0) == 0x80 and (b4 & 0xC0) == 0x80: + all_bytes = bytes((b1, b2, b3, b4)) + try: + result += all_bytes.decode() + except UnicodeDecodeError: + result += "\ufffd" * 4 + + i += 9 + i += 3 # emulate JS for loop statement3 + continue + + result += "\ufffd" + i += 3 # emulate JS for loop statement3 + + return result diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl/_encode.py b/data/miniconda3/lib/python3.13/site-packages/mdurl/_encode.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2e5b917afe9e9ecaa6f11af7a9ac82704d3914 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl/_encode.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +from collections.abc import Sequence +from string import ascii_letters, digits, hexdigits +from urllib.parse import quote as encode_uri_component + +ASCII_LETTERS_AND_DIGITS = ascii_letters + digits + +ENCODE_DEFAULT_CHARS = ";/?:@&=+$,-_.!~*'()#" +ENCODE_COMPONENT_CHARS = "-_.!~*'()" + +encode_cache: dict[str, list[str]] = {} + + +# Create a lookup array where anything but characters in `chars` string +# and alphanumeric chars is percent-encoded. +def get_encode_cache(exclude: str) -> Sequence[str]: + if exclude in encode_cache: + return encode_cache[exclude] + + cache: list[str] = [] + encode_cache[exclude] = cache + + for i in range(128): + ch = chr(i) + + if ch in ASCII_LETTERS_AND_DIGITS: + # always allow unencoded alphanumeric characters + cache.append(ch) + else: + cache.append("%" + ("0" + hex(i)[2:].upper())[-2:]) + + for i in range(len(exclude)): + cache[ord(exclude[i])] = exclude[i] + + return cache + + +# Encode unsafe characters with percent-encoding, skipping already +# encoded sequences. +# +# - string - string to encode +# - exclude - list of characters to ignore (in addition to a-zA-Z0-9) +# - keepEscaped - don't encode '%' in a correct escape sequence (default: true) +def encode( + string: str, exclude: str = ENCODE_DEFAULT_CHARS, *, keep_escaped: bool = True +) -> str: + result = "" + + cache = get_encode_cache(exclude) + + l = len(string) # noqa: E741 + i = 0 + while i < l: + code = ord(string[i]) + + # % + if keep_escaped and code == 0x25 and i + 2 < l: + if all(c in hexdigits for c in string[i + 1 : i + 3]): + result += string[i : i + 3] + i += 2 + i += 1 # JS for loop statement3 + continue + + if code < 128: + result += cache[code] + i += 1 # JS for loop statement3 + continue + + if code >= 0xD800 and code <= 0xDFFF: + if code >= 0xD800 and code <= 0xDBFF and i + 1 < l: + next_code = ord(string[i + 1]) + if next_code >= 0xDC00 and next_code <= 0xDFFF: + result += encode_uri_component(string[i] + string[i + 1]) + i += 1 + i += 1 # JS for loop statement3 + continue + result += "%EF%BF%BD" + i += 1 # JS for loop statement3 + continue + + result += encode_uri_component(string[i]) + i += 1 # JS for loop statement3 + + return result diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl/_format.py b/data/miniconda3/lib/python3.13/site-packages/mdurl/_format.py new file mode 100644 index 0000000000000000000000000000000000000000..12524ca626065183ec9974f3d7d08dadd4a7d3e8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl/_format.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from mdurl._url import URL + + +def format(url: URL) -> str: # noqa: A001 + result = "" + + result += url.protocol or "" + result += "//" if url.slashes else "" + result += url.auth + "@" if url.auth else "" + + if url.hostname and ":" in url.hostname: + # ipv6 address + result += "[" + url.hostname + "]" + else: + result += url.hostname or "" + + result += ":" + url.port if url.port else "" + result += url.pathname or "" + result += url.search or "" + result += url.hash or "" + + return result diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl/_parse.py b/data/miniconda3/lib/python3.13/site-packages/mdurl/_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..ffeeac768dca3bff60c55c9b1f0bc0fbb4cec7b1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl/_parse.py @@ -0,0 +1,304 @@ +# Copyright Joyent, Inc. and other Node contributors. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject to the +# following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +# USE OR OTHER DEALINGS IN THE SOFTWARE. + + +# Changes from joyent/node: +# +# 1. No leading slash in paths, +# e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/` +# +# 2. Backslashes are not replaced with slashes, +# so `http:\\example.org\` is treated like a relative path +# +# 3. Trailing colon is treated like a part of the path, +# i.e. in `http://example.org:foo` pathname is `:foo` +# +# 4. Nothing is URL-encoded in the resulting object, +# (in joyent/node some chars in auth and paths are encoded) +# +# 5. `url.parse()` does not have `parseQueryString` argument +# +# 6. Removed extraneous result properties: `host`, `path`, `query`, etc., +# which can be constructed using other parts of the url. + +from __future__ import annotations + +from collections import defaultdict +import re + +from mdurl._url import URL + +# Reference: RFC 3986, RFC 1808, RFC 2396 + +# define these here so at least they only have to be +# compiled once on the first module load. +PROTOCOL_PATTERN = re.compile(r"^([a-z0-9.+-]+:)", flags=re.IGNORECASE) +PORT_PATTERN = re.compile(r":[0-9]*$") + +# Special case for a simple path URL +SIMPLE_PATH_PATTERN = re.compile(r"^(//?(?!/)[^?\s]*)(\?[^\s]*)?$") + +# RFC 2396: characters reserved for delimiting URLs. +# We actually just auto-escape these. +DELIMS = ("<", ">", '"', "`", " ", "\r", "\n", "\t") + +# RFC 2396: characters not allowed for various reasons. +UNWISE = ("{", "}", "|", "\\", "^", "`") + DELIMS + +# Allowed by RFCs, but cause of XSS attacks. Always escape these. +AUTO_ESCAPE = ("'",) + UNWISE +# Characters that are never ever allowed in a hostname. +# Note that any invalid chars are also handled, but these +# are the ones that are *expected* to be seen, so we fast-path +# them. +NON_HOST_CHARS = ("%", "/", "?", ";", "#") + AUTO_ESCAPE +HOST_ENDING_CHARS = ("/", "?", "#") +HOSTNAME_MAX_LEN = 255 +HOSTNAME_PART_PATTERN = re.compile(r"^[+a-z0-9A-Z_-]{0,63}$") +HOSTNAME_PART_START = re.compile(r"^([+a-z0-9A-Z_-]{0,63})(.*)$") +# protocols that can allow "unsafe" and "unwise" chars. + +# protocols that never have a hostname. +HOSTLESS_PROTOCOL = defaultdict( + bool, + { + "javascript": True, + "javascript:": True, + }, +) +# protocols that always contain a // bit. +SLASHED_PROTOCOL = defaultdict( + bool, + { + "http": True, + "https": True, + "ftp": True, + "gopher": True, + "file": True, + "http:": True, + "https:": True, + "ftp:": True, + "gopher:": True, + "file:": True, + }, +) + + +class MutableURL: + def __init__(self) -> None: + self.protocol: str | None = None + self.slashes: bool = False + self.auth: str | None = None + self.port: str | None = None + self.hostname: str | None = None + self.hash: str | None = None + self.search: str | None = None + self.pathname: str | None = None + + def parse(self, url: str, slashes_denote_host: bool) -> "MutableURL": + lower_proto = "" + slashes = False + rest = url + + # trim before proceeding. + # This is to support parse stuff like " http://foo.com \n" + rest = rest.strip() + + if not slashes_denote_host and len(url.split("#")) == 1: + # Try fast path regexp + simple_path = SIMPLE_PATH_PATTERN.match(rest) + if simple_path: + self.pathname = simple_path.group(1) + if simple_path.group(2): + self.search = simple_path.group(2) + return self + + proto = "" + proto_match = PROTOCOL_PATTERN.match(rest) + if proto_match: + proto = proto_match.group() + lower_proto = proto.lower() + self.protocol = proto + rest = rest[len(proto) :] + + # figure out if it's got a host + # user@server is *always* interpreted as a hostname, and url + # resolution will treat //foo/bar as host=foo,path=bar because that's + # how the browser resolves relative URLs. + if slashes_denote_host or proto or re.search(r"^//[^@/]+@[^@/]+", rest): + slashes = rest.startswith("//") + if slashes and not (proto and HOSTLESS_PROTOCOL[proto]): + rest = rest[2:] + self.slashes = True + + if not HOSTLESS_PROTOCOL[proto] and ( + slashes or (proto and not SLASHED_PROTOCOL[proto]) + ): + + # there's a hostname. + # the first instance of /, ?, ;, or # ends the host. + # + # If there is an @ in the hostname, then non-host chars *are* allowed + # to the left of the last @ sign, unless some host-ending character + # comes *before* the @-sign. + # URLs are obnoxious. + # + # ex: + # http://a@b@c/ => user:a@b host:c + # http://a@b?@c => user:a host:c path:/?@c + + # v0.12 TODO(isaacs): This is not quite how Chrome does things. + # Review our test case against browsers more comprehensively. + + # find the first instance of any hostEndingChars + host_end = -1 + for i in range(len(HOST_ENDING_CHARS)): + hec = rest.find(HOST_ENDING_CHARS[i]) + if hec != -1 and (host_end == -1 or hec < host_end): + host_end = hec + + # at this point, either we have an explicit point where the + # auth portion cannot go past, or the last @ char is the decider. + if host_end == -1: + # atSign can be anywhere. + at_sign = rest.rfind("@") + else: + # atSign must be in auth portion. + # http://a@b/c@d => host:b auth:a path:/c@d + at_sign = rest.rfind("@", 0, host_end + 1) + + # Now we have a portion which is definitely the auth. + # Pull that off. + if at_sign != -1: + auth = rest[:at_sign] + rest = rest[at_sign + 1 :] + self.auth = auth + + # the host is the remaining to the left of the first non-host char + host_end = -1 + for i in range(len(NON_HOST_CHARS)): + hec = rest.find(NON_HOST_CHARS[i]) + if hec != -1 and (host_end == -1 or hec < host_end): + host_end = hec + # if we still have not hit it, then the entire thing is a host. + if host_end == -1: + host_end = len(rest) + + if host_end > 0 and rest[host_end - 1] == ":": + host_end -= 1 + host = rest[:host_end] + rest = rest[host_end:] + + # pull out port. + self.parse_host(host) + + # we've indicated that there is a hostname, + # so even if it's empty, it has to be present. + self.hostname = self.hostname or "" + + # if hostname begins with [ and ends with ] + # assume that it's an IPv6 address. + ipv6_hostname = self.hostname.startswith("[") and self.hostname.endswith( + "]" + ) + + # validate a little. + if not ipv6_hostname: + hostparts = self.hostname.split(".") + l = len(hostparts) # noqa: E741 + i = 0 + while i < l: + part = hostparts[i] + if not part: + i += 1 # emulate statement3 in JS for loop + continue + if not HOSTNAME_PART_PATTERN.search(part): + newpart = "" + k = len(part) + j = 0 + while j < k: + if ord(part[j]) > 127: + # we replace non-ASCII char with a temporary placeholder + # we need this to make sure size of hostname is not + # broken by replacing non-ASCII by nothing + newpart += "x" + else: + newpart += part[j] + j += 1 # emulate statement3 in JS for loop + + # we test again with ASCII char only + if not HOSTNAME_PART_PATTERN.search(newpart): + valid_parts = hostparts[:i] + not_host = hostparts[i + 1 :] + bit = HOSTNAME_PART_START.search(part) + if bit: + valid_parts.append(bit.group(1)) + not_host.insert(0, bit.group(2)) + if not_host: + rest = ".".join(not_host) + rest + self.hostname = ".".join(valid_parts) + break + i += 1 # emulate statement3 in JS for loop + + if len(self.hostname) > HOSTNAME_MAX_LEN: + self.hostname = "" + + # strip [ and ] from the hostname + # the host field still retains them, though + if ipv6_hostname: + self.hostname = self.hostname[1:-1] + + # chop off from the tail first. + hash = rest.find("#") # noqa: A001 + if hash != -1: + # got a fragment string. + self.hash = rest[hash:] + rest = rest[:hash] + qm = rest.find("?") + if qm != -1: + self.search = rest[qm:] + rest = rest[:qm] + if rest: + self.pathname = rest + if SLASHED_PROTOCOL[lower_proto] and self.hostname and not self.pathname: + self.pathname = "" + + return self + + def parse_host(self, host: str) -> None: + port_match = PORT_PATTERN.search(host) + if port_match: + port = port_match.group() + if port != ":": + self.port = port[1:] + host = host[: -len(port)] + if host: + self.hostname = host + + +def url_parse(url: URL | str, *, slashes_denote_host: bool = False) -> URL: + if isinstance(url, URL): + return url + u = MutableURL() + u.parse(url, slashes_denote_host) + return URL( + u.protocol, u.slashes, u.auth, u.port, u.hostname, u.hash, u.search, u.pathname + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl/_url.py b/data/miniconda3/lib/python3.13/site-packages/mdurl/_url.py new file mode 100644 index 0000000000000000000000000000000000000000..f866e7a179c8854e37c9bba6294f48681e5d99d7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl/_url.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from typing import NamedTuple + + +class URL(NamedTuple): + protocol: str | None + slashes: bool + auth: str | None + port: str | None + hostname: str | None + hash: str | None # noqa: A003 + search: str | None + pathname: str | None diff --git a/data/miniconda3/lib/python3.13/site-packages/mdurl/py.typed b/data/miniconda3/lib/python3.13/site-packages/mdurl/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..7632ecf77545c5e5501cb3fc5719df0761104ca2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mdurl/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561 diff --git a/data/miniconda3/lib/python3.13/site-packages/msgpack/__init__.py b/data/miniconda3/lib/python3.13/site-packages/msgpack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad68271d864357f386e97295983db59f8fee3cce --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/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, 1) +__version__ = "1.1.1" + + +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/data/miniconda3/lib/python3.13/site-packages/msgpack/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/msgpack/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d2615cfdd0b914d064cdf7eecd45761e4bcaf6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/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/data/miniconda3/lib/python3.13/site-packages/msgpack/ext.py b/data/miniconda3/lib/python3.13/site-packages/msgpack/ext.py new file mode 100644 index 0000000000000000000000000000000000000000..9694819a7df1570ccbb41de065cb7052f9af8e79 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/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/data/miniconda3/lib/python3.13/site-packages/msgpack/fallback.py b/data/miniconda3/lib/python3.13/site-packages/msgpack/fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..b02e47cfb91a54a7205881ee87a5db2ea8d049a7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/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/data/miniconda3/lib/python3.13/site-packages/networkx/__init__.py b/data/miniconda3/lib/python3.13/site-packages/networkx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b975a1ff66b1b1e87de65a9966dafdb09cb00031 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/networkx/__init__.py @@ -0,0 +1,62 @@ +""" +NetworkX +======== + +NetworkX is a Python package for the creation, manipulation, and study of the +structure, dynamics, and functions of complex networks. + +See https://networkx.org for complete documentation. +""" + +__version__ = "3.6.1" + + +# These are imported in order as listed +from networkx.lazy_imports import _lazy_import + +from networkx.exception import * + +from networkx import utils +from networkx.utils import _clear_cache, _dispatchable + +# load_and_call entry_points, set configs +config = utils.backends._set_configs_from_environment() +utils.config = utils.configs.config = config # type: ignore[attr-defined] + +from networkx import classes +from networkx.classes import filters +from networkx.classes import * + +from networkx import convert +from networkx.convert import * + +from networkx import convert_matrix +from networkx.convert_matrix import * + +from networkx import relabel +from networkx.relabel import * + +from networkx import generators +from networkx.generators import * + +from networkx import readwrite +from networkx.readwrite import * + +# Need to test with SciPy, when available +from networkx import algorithms +from networkx.algorithms import * + +from networkx import linalg +from networkx.linalg import * + +from networkx import drawing +from networkx.drawing import * + + +def __getattr__(name): + if name == "random_tree": + raise AttributeError( + "nx.random_tree was removed in version 3.4. Use `nx.random_labeled_tree` instead.\n" + "See: https://networkx.org/documentation/latest/release/release_3.4.html" + ) + raise AttributeError(f"module 'networkx' has no attribute '{name}'") diff --git a/data/miniconda3/lib/python3.13/site-packages/networkx/conftest.py b/data/miniconda3/lib/python3.13/site-packages/networkx/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..186b33bb7039f202656b5072c2452b369f1cae8a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/networkx/conftest.py @@ -0,0 +1,261 @@ +""" +Testing +======= + +General guidelines for writing good tests: + +- doctests always assume ``import networkx as nx`` so don't add that +- prefer pytest fixtures over classes with setup methods. +- use the ``@pytest.mark.parametrize`` decorator +- use ``pytest.importorskip`` for numpy, scipy, pandas, and matplotlib b/c of PyPy. + and add the module to the relevant entries below. + +""" + +import os +import warnings +from importlib.metadata import entry_points + +import pytest + +import networkx as nx + + +def pytest_addoption(parser): + parser.addoption( + "--runslow", action="store_true", default=False, help="run slow tests" + ) + parser.addoption( + "--backend", + action="store", + default=None, + help="Run tests with a backend by auto-converting nx graphs to backend graphs", + ) + parser.addoption( + "--fallback-to-nx", + action="store_true", + default=False, + help="Run nx function if a backend doesn't implement a dispatchable function" + " (use with --backend)", + ) + + +def pytest_configure(config): + config.addinivalue_line("markers", "slow: mark test as slow to run") + backend = config.getoption("--backend") + if backend is None: + backend = os.environ.get("NETWORKX_TEST_BACKEND") + # nx_loopback backend is only available when testing with a backend + loopback_ep = entry_points(name="nx_loopback", group="networkx.backends") + if not loopback_ep: + warnings.warn( + "\n\n WARNING: Mixed NetworkX configuration! \n\n" + " This environment has mixed configuration for networkx.\n" + " The test object nx_loopback is not configured correctly.\n" + " You should not be seeing this message.\n" + " Try `pip install -e .`, or change your PYTHONPATH\n" + " Make sure python finds the networkx repo you are testing\n\n" + ) + config.backend = backend + if backend: + # We will update `networkx.config.backend_priority` below in `*_modify_items` + # to allow tests to get set up with normal networkx graphs. + nx.utils.backends.backends["nx_loopback"] = loopback_ep["nx_loopback"] + nx.utils.backends.backend_info["nx_loopback"] = {} + nx.config.backends = nx.utils.Config( + nx_loopback=nx.utils.Config(), + **nx.config.backends, + ) + fallback_to_nx = config.getoption("--fallback-to-nx") + if not fallback_to_nx: + fallback_to_nx = os.environ.get("NETWORKX_FALLBACK_TO_NX") + nx.config.fallback_to_nx = bool(fallback_to_nx) + nx.utils.backends._dispatchable.__call__ = ( + nx.utils.backends._dispatchable._call_if_any_backends_installed + ) + + +def pytest_collection_modifyitems(config, items): + # Setting this to True here allows tests to be set up before dispatching + # any function call to a backend. + if config.backend: + # Allow pluggable backends to add markers to tests (such as skip or xfail) + # when running in auto-conversion test mode + backend_name = config.backend + if backend_name != "networkx": + nx.utils.backends._dispatchable._is_testing = True + nx.config.backend_priority.algos = [backend_name] + nx.config.backend_priority.generators = [backend_name] + backend = nx.utils.backends.backends[backend_name].load() + if hasattr(backend, "on_start_tests"): + getattr(backend, "on_start_tests")(items) + + if config.getoption("--runslow"): + # --runslow given in cli: do not skip slow tests + return + skip_slow = pytest.mark.skip(reason="need --runslow option to run") + for item in items: + if "slow" in item.keywords: + item.add_marker(skip_slow) + + +# TODO: The warnings below need to be dealt with, but for now we silence them. +@pytest.fixture(autouse=True) +def set_warnings(): + warnings.filterwarnings( + "ignore", + category=UserWarning, + message=r"Exited (at iteration \d+|postprocessing) with accuracies.*", + ) + warnings.filterwarnings( + "ignore", + category=UserWarning, + message=r"The hashes produced for ", + ) + warnings.filterwarnings( + "ignore", category=DeprecationWarning, message="\n\nThe `normalized`" + ) + warnings.filterwarnings( + "ignore", category=DeprecationWarning, message="maybe_regular_expander" + ) + warnings.filterwarnings( + "ignore", category=DeprecationWarning, message="metric_closure is deprecated" + ) + + +@pytest.fixture(autouse=True) +def add_nx(doctest_namespace): + doctest_namespace["nx"] = nx + + +# What dependencies are installed? + +try: + import numpy as np + + has_numpy = True +except ImportError: + has_numpy = False + +try: + import scipy as sp + + has_scipy = True +except ImportError: + has_scipy = False + +try: + import matplotlib as mpl + + has_matplotlib = True +except ImportError: + has_matplotlib = False + +try: + import pandas as pd + + has_pandas = True +except ImportError: + has_pandas = False + +try: + import pygraphviz + + has_pygraphviz = True +except ImportError: + has_pygraphviz = False + +try: + import pydot + + has_pydot = True +except ImportError: + has_pydot = False + +try: + import sympy + + has_sympy = True +except ImportError: + has_sympy = False + + +# List of files that pytest should ignore + +collect_ignore = [] + +needs_numpy = [ + "algorithms/approximation/traveling_salesman.py", + "algorithms/centrality/current_flow_closeness.py", + "algorithms/centrality/laplacian.py", + "algorithms/node_classification.py", + "algorithms/non_randomness.py", + "algorithms/polynomials.py", + "algorithms/shortest_paths/dense.py", + "algorithms/tree/mst.py", + "drawing/nx_latex.py", + "generators/expanders.py", + "linalg/bethehessianmatrix.py", + "linalg/laplacianmatrix.py", + "utils/misc.py", +] +needs_scipy = [ + "algorithms/approximation/traveling_salesman.py", + "algorithms/assortativity/correlation.py", + "algorithms/assortativity/mixing.py", + "algorithms/assortativity/pairs.py", + "algorithms/bipartite/matrix.py", + "algorithms/bipartite/spectral.py", + "algorithms/bipartite/link_analysis.py", + "algorithms/centrality/current_flow_betweenness.py", + "algorithms/centrality/current_flow_betweenness_subset.py", + "algorithms/centrality/eigenvector.py", + "algorithms/centrality/katz.py", + "algorithms/centrality/laplacian.py", + "algorithms/centrality/second_order.py", + "algorithms/centrality/subgraph_alg.py", + "algorithms/communicability_alg.py", + "algorithms/community/divisive.py", + "algorithms/community/bipartitions.py", + "algorithms/distance_measures.py", + "algorithms/link_analysis/hits_alg.py", + "algorithms/link_analysis/pagerank_alg.py", + "algorithms/node_classification.py", + "algorithms/similarity.py", + "algorithms/tree/mst.py", + "algorithms/walks.py", + "convert_matrix.py", + "drawing/layout.py", + "drawing/nx_pylab.py", + "generators/spectral_graph_forge.py", + "generators/geometric.py", + "generators/expanders.py", + "linalg/algebraicconnectivity.py", + "linalg/attrmatrix.py", + "linalg/bethehessianmatrix.py", + "linalg/graphmatrix.py", + "linalg/laplacianmatrix.py", + "linalg/modularitymatrix.py", + "linalg/spectrum.py", + "utils/rcm.py", +] +needs_matplotlib = ["drawing/nx_pylab.py", "generators/classic.py"] +needs_pandas = ["convert_matrix.py"] +needs_pygraphviz = ["drawing/nx_agraph.py"] +needs_pydot = ["drawing/nx_pydot.py"] +needs_sympy = ["algorithms/polynomials.py"] + +if not has_numpy: + collect_ignore += needs_numpy +if not has_scipy: + collect_ignore += needs_scipy +if not has_matplotlib: + collect_ignore += needs_matplotlib +if not has_pandas: + collect_ignore += needs_pandas +if not has_pygraphviz: + collect_ignore += needs_pygraphviz +if not has_pydot: + collect_ignore += needs_pydot +if not has_sympy: + collect_ignore += needs_sympy diff --git a/data/miniconda3/lib/python3.13/site-packages/networkx/convert.py b/data/miniconda3/lib/python3.13/site-packages/networkx/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0a502a271f04594d7384f9eb7c4e6cf92f4edb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/networkx/convert.py @@ -0,0 +1,502 @@ +"""Functions to convert NetworkX graphs to and from other formats. + +The preferred way of converting data to a NetworkX graph is through the +graph constructor. The constructor calls the to_networkx_graph() function +which attempts to guess the input type and convert it automatically. + +Examples +-------- +Create a graph with a single edge from a dictionary of dictionaries + +>>> d = {0: {1: 1}} # dict-of-dicts single edge (0,1) +>>> G = nx.Graph(d) + +See Also +-------- +nx_agraph, nx_pydot +""" + +from collections.abc import Collection, Generator, Iterator + +import networkx as nx + +__all__ = [ + "to_networkx_graph", + "from_dict_of_dicts", + "to_dict_of_dicts", + "from_dict_of_lists", + "to_dict_of_lists", + "from_edgelist", + "to_edgelist", +] + + +def to_networkx_graph(data, create_using=None, multigraph_input=False): + """Make a NetworkX graph from a known data structure. + + The preferred way to call this is automatically + from the class constructor + + >>> d = {0: {1: {"weight": 1}}} # dict-of-dicts single edge (0,1) + >>> G = nx.Graph(d) + + instead of the equivalent + + >>> G = nx.from_dict_of_dicts(d) + + Parameters + ---------- + data : object to be converted + + Current known types are: + any NetworkX graph + dict-of-dicts + dict-of-lists + container (e.g. set, list, tuple) of edges + iterator (e.g. itertools.chain) that produces edges + generator of edges + Pandas DataFrame (row per edge) + 2D numpy array + scipy sparse array + pygraphviz agraph + + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + multigraph_input : bool (default False) + If True and data is a dict_of_dicts, + try to create a multigraph assuming dict_of_dict_of_lists. + If data and create_using are both multigraphs then create + a multigraph from a multigraph. + + """ + # NX graph + if hasattr(data, "adj"): + try: + result = from_dict_of_dicts( + data.adj, + create_using=create_using, + multigraph_input=data.is_multigraph(), + ) + # data.graph should be dict-like + result.graph.update(data.graph) + # data.nodes should be dict-like + # result.add_node_from(data.nodes.items()) possible but + # for custom node_attr_dict_factory which may be hashable + # will be unexpected behavior + for n, dd in data.nodes.items(): + result._node[n].update(dd) + return result + except Exception as err: + raise nx.NetworkXError("Input is not a correct NetworkX graph.") from err + + # dict of dicts/lists + if isinstance(data, dict): + try: + return from_dict_of_dicts( + data, create_using=create_using, multigraph_input=multigraph_input + ) + except Exception as err1: + if multigraph_input is True: + raise nx.NetworkXError( + f"converting multigraph_input raised:\n{type(err1)}: {err1}" + ) + try: + return from_dict_of_lists(data, create_using=create_using) + except Exception as err2: + raise TypeError("Input is not known type.") from err2 + + # edgelists + if isinstance(data, list | tuple | nx.reportviews.EdgeViewABC | Iterator): + try: + return from_edgelist(data, create_using=create_using) + except: + pass + + # pygraphviz agraph + if hasattr(data, "is_strict"): + try: + return nx.nx_agraph.from_agraph(data, create_using=create_using) + except Exception as err: + raise nx.NetworkXError("Input is not a correct pygraphviz graph.") from err + + # Pandas DataFrame + try: + import pandas as pd + + if isinstance(data, pd.DataFrame): + if data.shape[0] == data.shape[1]: + try: + return nx.from_pandas_adjacency(data, create_using=create_using) + except Exception as err: + msg = "Input is not a correct Pandas DataFrame adjacency matrix." + raise nx.NetworkXError(msg) from err + else: + try: + return nx.from_pandas_edgelist( + data, edge_attr=True, create_using=create_using + ) + except Exception as err: + msg = "Input is not a correct Pandas DataFrame edge-list." + raise nx.NetworkXError(msg) from err + except ImportError: + pass + + # numpy array + try: + import numpy as np + + if isinstance(data, np.ndarray): + try: + return nx.from_numpy_array(data, create_using=create_using) + except Exception as err: + raise nx.NetworkXError( + f"Failed to interpret array as an adjacency matrix." + ) from err + except ImportError: + pass + + # scipy sparse array - any format + try: + import scipy as sp + + if hasattr(data, "format"): + try: + return nx.from_scipy_sparse_array(data, create_using=create_using) + except Exception as err: + raise nx.NetworkXError( + "Input is not a correct scipy sparse array type." + ) from err + except ImportError: + pass + + # Note: most general check - should remain last in order of execution + # Includes containers (e.g. list, set, dict, etc.), generators, and + # iterators (e.g. itertools.chain) of edges + + if isinstance(data, Collection | Generator | Iterator): + try: + return from_edgelist(data, create_using=create_using) + except Exception as err: + raise nx.NetworkXError("Input is not a valid edge list") from err + + raise nx.NetworkXError("Input is not a known data type for conversion.") + + +@nx._dispatchable +def to_dict_of_lists(G, nodelist=None): + """Returns adjacency representation of graph as a dictionary of lists. + + Parameters + ---------- + G : graph + A NetworkX graph + + nodelist : list + Use only nodes specified in nodelist + + Notes + ----- + Completely ignores edge data for MultiGraph and MultiDiGraph. + + """ + if nodelist is None: + nodelist = G + + d = {} + for n in nodelist: + d[n] = [nbr for nbr in G.neighbors(n) if nbr in nodelist] + return d + + +@nx._dispatchable(graphs=None, returns_graph=True) +def from_dict_of_lists(d, create_using=None): + """Returns a graph from a dictionary of lists. + + Parameters + ---------- + d : dictionary of lists + A dictionary of lists adjacency representation. + + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Examples + -------- + >>> dol = {0: [1]} # single edge (0,1) + >>> G = nx.from_dict_of_lists(dol) + + or + + >>> G = nx.Graph(dol) # use Graph constructor + + """ + G = nx.empty_graph(0, create_using) + G.add_nodes_from(d) + if G.is_multigraph() and not G.is_directed(): + # a dict_of_lists can't show multiedges. BUT for undirected graphs, + # each edge shows up twice in the dict_of_lists. + # So we need to treat this case separately. + seen = {} + for node, nbrlist in d.items(): + for nbr in nbrlist: + if nbr not in seen: + G.add_edge(node, nbr) + seen[node] = 1 # don't allow reverse edge to show up + else: + G.add_edges_from( + ((node, nbr) for node, nbrlist in d.items() for nbr in nbrlist) + ) + return G + + +def to_dict_of_dicts(G, nodelist=None, edge_data=None): + """Returns adjacency representation of graph as a dictionary of dictionaries. + + Parameters + ---------- + G : graph + A NetworkX graph + + nodelist : list + Use only nodes specified in nodelist. If None, all nodes in G. + + edge_data : scalar, optional (default: the G edgedatadict for each edge) + If provided, the value of the dictionary will be set to `edge_data` for + all edges. Usual values could be `1` or `True`. If `edge_data` is + `None` (the default), the edgedata in `G` is used, resulting in a + dict-of-dict-of-dicts. If `G` is a MultiGraph, the result will be a + dict-of-dict-of-dict-of-dicts. See Notes for an approach to customize + handling edge data. `edge_data` should *not* be a container as it will + be the same container for all the edges. + + Returns + ------- + dod : dict + A nested dictionary representation of `G`. Note that the level of + nesting depends on the type of `G` and the value of `edge_data` + (see Examples). + + See Also + -------- + from_dict_of_dicts, to_dict_of_lists + + Notes + ----- + For a more custom approach to handling edge data, try:: + + dod = { + n: {nbr: custom(n, nbr, dd) for nbr, dd in nbrdict.items()} + for n, nbrdict in G.adj.items() + } + + where `custom` returns the desired edge data for each edge between `n` and + `nbr`, given existing edge data `dd`. + + Examples + -------- + >>> G = nx.path_graph(3) + >>> nx.to_dict_of_dicts(G) + {0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}}} + + Edge data is preserved by default (``edge_data=None``), resulting + in dict-of-dict-of-dicts where the innermost dictionary contains the + edge data: + + >>> G = nx.Graph() + >>> G.add_edges_from( + ... [ + ... (0, 1, {"weight": 1.0}), + ... (1, 2, {"weight": 2.0}), + ... (2, 0, {"weight": 1.0}), + ... ] + ... ) + >>> d = nx.to_dict_of_dicts(G) + >>> d # doctest: +SKIP + {0: {1: {'weight': 1.0}, 2: {'weight': 1.0}}, + 1: {0: {'weight': 1.0}, 2: {'weight': 2.0}}, + 2: {1: {'weight': 2.0}, 0: {'weight': 1.0}}} + >>> d[1][2]["weight"] + 2.0 + + If `edge_data` is not `None`, edge data in the original graph (if any) is + replaced: + + >>> d = nx.to_dict_of_dicts(G, edge_data=1) + >>> d + {0: {1: 1, 2: 1}, 1: {0: 1, 2: 1}, 2: {1: 1, 0: 1}} + >>> d[1][2] + 1 + + This also applies to MultiGraphs: edge data is preserved by default: + + >>> G = nx.MultiGraph() + >>> G.add_edge(0, 1, key="a", weight=1.0) + 'a' + >>> G.add_edge(0, 1, key="b", weight=5.0) + 'b' + >>> d = nx.to_dict_of_dicts(G) + >>> d # doctest: +SKIP + {0: {1: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}, + 1: {0: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}} + >>> d[0][1]["b"]["weight"] + 5.0 + + But multi edge data is lost if `edge_data` is not `None`: + + >>> d = nx.to_dict_of_dicts(G, edge_data=10) + >>> d + {0: {1: 10}, 1: {0: 10}} + """ + dod = {} + if nodelist is None: + if edge_data is None: + for u, nbrdict in G.adjacency(): + dod[u] = nbrdict.copy() + else: # edge_data is not None + for u, nbrdict in G.adjacency(): + dod[u] = dod.fromkeys(nbrdict, edge_data) + else: # nodelist is not None + if edge_data is None: + for u in nodelist: + dod[u] = {} + for v, data in ((v, data) for v, data in G[u].items() if v in nodelist): + dod[u][v] = data + else: # nodelist and edge_data are not None + for u in nodelist: + dod[u] = {} + for v in (v for v in G[u] if v in nodelist): + dod[u][v] = edge_data + return dod + + +@nx._dispatchable(graphs=None, returns_graph=True) +def from_dict_of_dicts(d, create_using=None, multigraph_input=False): + """Returns a graph from a dictionary of dictionaries. + + Parameters + ---------- + d : dictionary of dictionaries + A dictionary of dictionaries adjacency representation. + + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + multigraph_input : bool (default False) + When True, the dict `d` is assumed + to be a dict-of-dict-of-dict-of-dict structure keyed by + node to neighbor to edge keys to edge data for multi-edges. + Otherwise this routine assumes dict-of-dict-of-dict keyed by + node to neighbor to edge data. + + Examples + -------- + >>> dod = {0: {1: {"weight": 1}}} # single edge (0,1) + >>> G = nx.from_dict_of_dicts(dod) + + or + + >>> G = nx.Graph(dod) # use Graph constructor + + """ + G = nx.empty_graph(0, create_using) + G.add_nodes_from(d) + # does dict d represent a MultiGraph or MultiDiGraph? + if multigraph_input: + if G.is_directed(): + if G.is_multigraph(): + G.add_edges_from( + (u, v, key, data) + for u, nbrs in d.items() + for v, datadict in nbrs.items() + for key, data in datadict.items() + ) + else: + G.add_edges_from( + (u, v, data) + for u, nbrs in d.items() + for v, datadict in nbrs.items() + for key, data in datadict.items() + ) + else: # Undirected + if G.is_multigraph(): + seen = set() # don't add both directions of undirected graph + for u, nbrs in d.items(): + for v, datadict in nbrs.items(): + if (u, v) not in seen: + G.add_edges_from( + (u, v, key, data) for key, data in datadict.items() + ) + seen.add((v, u)) + else: + seen = set() # don't add both directions of undirected graph + for u, nbrs in d.items(): + for v, datadict in nbrs.items(): + if (u, v) not in seen: + G.add_edges_from( + (u, v, data) for key, data in datadict.items() + ) + seen.add((v, u)) + + else: # not a multigraph to multigraph transfer + if G.is_multigraph() and not G.is_directed(): + # d can have both representations u-v, v-u in dict. Only add one. + # We don't need this check for digraphs since we add both directions, + # or for Graph() since it is done implicitly (parallel edges not allowed) + seen = set() + for u, nbrs in d.items(): + for v, data in nbrs.items(): + if (u, v) not in seen: + G.add_edge(u, v, key=0) + G[u][v][0].update(data) + seen.add((v, u)) + else: + G.add_edges_from( + ((u, v, data) for u, nbrs in d.items() for v, data in nbrs.items()) + ) + return G + + +@nx._dispatchable(preserve_edge_attrs=True) +def to_edgelist(G, nodelist=None): + """Returns a list of edges in the graph. + + Parameters + ---------- + G : graph + A NetworkX graph + + nodelist : list + Use only nodes specified in nodelist + + """ + if nodelist is None: + return G.edges(data=True) + return G.edges(nodelist, data=True) + + +@nx._dispatchable(graphs=None, returns_graph=True) +def from_edgelist(edgelist, create_using=None): + """Returns a graph from a list of edges. + + Parameters + ---------- + edgelist : list or iterator + Edge tuples + + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Examples + -------- + >>> edgelist = [(0, 1)] # single edge (0,1) + >>> G = nx.from_edgelist(edgelist) + + or + + >>> G = nx.Graph(edgelist) # use Graph constructor + + """ + G = nx.empty_graph(0, create_using) + G.add_edges_from(edgelist) + return G diff --git a/data/miniconda3/lib/python3.13/site-packages/networkx/convert_matrix.py b/data/miniconda3/lib/python3.13/site-packages/networkx/convert_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..72a551798d13a16f8666d3a70274beaafb63d6a7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/networkx/convert_matrix.py @@ -0,0 +1,1314 @@ +"""Functions to convert NetworkX graphs to and from common data containers +like numpy arrays, scipy sparse arrays, and pandas DataFrames. + +The preferred way of converting data to a NetworkX graph is through the +graph constructor. The constructor calls the `~networkx.convert.to_networkx_graph` +function which attempts to guess the input type and convert it automatically. + +Examples +-------- +Create a 10 node random graph from a numpy array + +>>> import numpy as np +>>> rng = np.random.default_rng() +>>> a = rng.integers(low=0, high=2, size=(10, 10)) +>>> DG = nx.from_numpy_array(a, create_using=nx.DiGraph) + +or equivalently: + +>>> DG = nx.DiGraph(a) + +which calls `from_numpy_array` internally based on the type of ``a``. + +See Also +-------- +nx_agraph, nx_pydot +""" + +import itertools +from collections import defaultdict + +import networkx as nx + +__all__ = [ + "from_pandas_adjacency", + "to_pandas_adjacency", + "from_pandas_edgelist", + "to_pandas_edgelist", + "from_scipy_sparse_array", + "to_scipy_sparse_array", + "from_numpy_array", + "to_numpy_array", +] + + +@nx._dispatchable(edge_attrs="weight") +def to_pandas_adjacency( + G, + nodelist=None, + dtype=None, + order=None, + multigraph_weight=sum, + weight="weight", + nonedge=0.0, +): + """Returns the graph adjacency matrix as a Pandas DataFrame. + + Parameters + ---------- + G : graph + The NetworkX graph used to construct the Pandas DataFrame. + + nodelist : list, optional + The rows and columns are ordered according to the nodes in `nodelist`. + If `nodelist` is None, then the ordering is produced by G.nodes(). + + multigraph_weight : {sum, min, max}, optional + An operator that determines how weights in multigraphs are handled. + The default is to sum the weights of the multiple edges. + + weight : string or None, optional + The edge attribute that holds the numerical value used for + the edge weight. If an edge does not have that attribute, then the + value 1 is used instead. + + nonedge : float, optional + The matrix values corresponding to nonedges are typically set to zero. + However, this could be undesirable if there are matrix values + corresponding to actual edges that also have the value zero. If so, + one might prefer nonedges to have some other value, such as nan. + + Returns + ------- + df : Pandas DataFrame + Graph adjacency matrix + + Notes + ----- + For directed graphs, entry i,j corresponds to an edge from i to j. + + The DataFrame entries are assigned to the weight edge attribute. When + an edge does not have a weight attribute, the value of the entry is set to + the number 1. For multiple (parallel) edges, the values of the entries + are determined by the 'multigraph_weight' parameter. The default is to + sum the weight attributes for each of the parallel edges. + + When `nodelist` does not contain every node in `G`, the matrix is built + from the subgraph of `G` that is induced by the nodes in `nodelist`. + + The convention used for self-loop edges in graphs is to assign the + diagonal matrix entry value to the weight attribute of the edge + (or the number 1 if the edge has no weight attribute). If the + alternate convention of doubling the edge weight is desired the + resulting Pandas DataFrame can be modified as follows:: + + >>> import pandas as pd + >>> G = nx.Graph([(1, 1), (2, 2)]) + >>> df = nx.to_pandas_adjacency(G) + >>> df + 1 2 + 1 1.0 0.0 + 2 0.0 1.0 + >>> diag_idx = list(range(len(df))) + >>> df.iloc[diag_idx, diag_idx] *= 2 + >>> df + 1 2 + 1 2.0 0.0 + 2 0.0 2.0 + + Examples + -------- + >>> G = nx.MultiDiGraph() + >>> G.add_edge(0, 1, weight=2) + 0 + >>> G.add_edge(1, 0) + 0 + >>> G.add_edge(2, 2, weight=3) + 0 + >>> G.add_edge(2, 2) + 1 + >>> nx.to_pandas_adjacency(G, nodelist=[0, 1, 2], dtype=int) + 0 1 2 + 0 0 2 0 + 1 1 0 0 + 2 0 0 4 + + """ + import pandas as pd + + M = to_numpy_array( + G, + nodelist=nodelist, + dtype=dtype, + order=order, + multigraph_weight=multigraph_weight, + weight=weight, + nonedge=nonedge, + ) + if nodelist is None: + nodelist = list(G) + return pd.DataFrame(data=M, index=nodelist, columns=nodelist) + + +@nx._dispatchable(graphs=None, returns_graph=True) +def from_pandas_adjacency(df, create_using=None): + r"""Returns a graph from Pandas DataFrame. + + The Pandas DataFrame is interpreted as an adjacency matrix for the graph. + + Parameters + ---------- + df : Pandas DataFrame + An adjacency matrix representation of a graph + + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + Notes + ----- + For directed graphs, explicitly mention create_using=nx.DiGraph, + and entry i,j of df corresponds to an edge from i to j. + + If `df` has a single data type for each entry it will be converted to an + appropriate Python data type. + + If you have node attributes stored in a separate dataframe `df_nodes`, + you can load those attributes to the graph `G` using the following code:: + + df_nodes = pd.DataFrame({"node_id": [1, 2, 3], "attribute1": ["A", "B", "C"]}) + G.add_nodes_from((n, dict(d)) for n, d in df_nodes.iterrows()) + + If `df` has a user-specified compound data type the names + of the data fields will be used as attribute keys in the resulting + NetworkX graph. + + See Also + -------- + to_pandas_adjacency + + Examples + -------- + Simple integer weights on edges: + + >>> import pandas as pd + >>> pd.options.display.max_columns = 20 + >>> df = pd.DataFrame([[1, 1], [2, 1]]) + >>> df + 0 1 + 0 1 1 + 1 2 1 + >>> G = nx.from_pandas_adjacency(df) + >>> G.name = "Graph from pandas adjacency matrix" + >>> print(G) + Graph named 'Graph from pandas adjacency matrix' with 2 nodes and 3 edges + """ + + try: + df = df[df.index] + except Exception as err: + missing = list(set(df.index).difference(set(df.columns))) + msg = f"{missing} not in columns" + raise nx.NetworkXError("Columns must match Indices.", msg) from err + + A = df.values + G = from_numpy_array(A, create_using=create_using, nodelist=df.columns) + + return G + + +@nx._dispatchable(preserve_edge_attrs=True) +def to_pandas_edgelist( + G, + source="source", + target="target", + nodelist=None, + dtype=None, + edge_key=None, +): + """Returns the graph edge list as a Pandas DataFrame. + + Parameters + ---------- + G : graph + The NetworkX graph used to construct the Pandas DataFrame. + + source : str or int, optional + A valid column name (string or integer) for the source nodes (for the + directed case). + + target : str or int, optional + A valid column name (string or integer) for the target nodes (for the + directed case). + + nodelist : list, optional + Use only nodes specified in nodelist + + dtype : dtype, default None + Use to create the DataFrame. Data type to force. + Only a single dtype is allowed. If None, infer. + + edge_key : str or int or None, optional (default=None) + A valid column name (string or integer) for the edge keys (for the + multigraph case). If None, edge keys are not stored in the DataFrame. + + Returns + ------- + df : Pandas DataFrame + Graph edge list + + Examples + -------- + >>> G = nx.Graph( + ... [ + ... ("A", "B", {"cost": 1, "weight": 7}), + ... ("C", "E", {"cost": 9, "weight": 10}), + ... ] + ... ) + >>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"]) + >>> df[["source", "target", "cost", "weight"]] + source target cost weight + 0 A B 1 7 + 1 C E 9 10 + + >>> G = nx.MultiGraph([("A", "B", {"cost": 1}), ("A", "B", {"cost": 9})]) + >>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"], edge_key="ekey") + >>> df[["source", "target", "cost", "ekey"]] + source target cost ekey + 0 A B 1 0 + 1 A B 9 1 + + """ + import pandas as pd + + if nodelist is None: + edgelist = G.edges(data=True) + else: + edgelist = G.edges(nodelist, data=True) + source_nodes = [s for s, _, _ in edgelist] + target_nodes = [t for _, t, _ in edgelist] + + all_attrs = set().union(*(d.keys() for _, _, d in edgelist)) + if source in all_attrs: + raise nx.NetworkXError(f"Source name {source!r} is an edge attr name") + if target in all_attrs: + raise nx.NetworkXError(f"Target name {target!r} is an edge attr name") + + nan = float("nan") + edge_attr = {k: [d.get(k, nan) for _, _, d in edgelist] for k in all_attrs} + + if G.is_multigraph() and edge_key is not None: + if edge_key in all_attrs: + raise nx.NetworkXError(f"Edge key name {edge_key!r} is an edge attr name") + edge_keys = [k for _, _, k in G.edges(keys=True)] + edgelistdict = {source: source_nodes, target: target_nodes, edge_key: edge_keys} + else: + edgelistdict = {source: source_nodes, target: target_nodes} + + edgelistdict.update(edge_attr) + return pd.DataFrame(edgelistdict, dtype=dtype) + + +@nx._dispatchable(graphs=None, returns_graph=True) +def from_pandas_edgelist( + df, + source="source", + target="target", + edge_attr=None, + create_using=None, + edge_key=None, +): + """Returns a graph from Pandas DataFrame containing an edge list. + + The Pandas DataFrame should contain at least two columns of node names and + zero or more columns of edge attributes. Each row will be processed as one + edge instance. + + Note: This function iterates over DataFrame.values, which is not + guaranteed to retain the data type across columns in the row. This is only + a problem if your row is entirely numeric and a mix of ints and floats. In + that case, all values will be returned as floats. See the + DataFrame.iterrows documentation for an example. + + Parameters + ---------- + df : Pandas DataFrame + An edge list representation of a graph + + source : str or int + A valid column name (string or integer) for the source nodes (for the + directed case). + + target : str or int + A valid column name (string or integer) for the target nodes (for the + directed case). + + edge_attr : str or int, iterable, True, or None + A valid column name (str or int) or iterable of column names that are + used to retrieve items and add them to the graph as edge attributes. + If `True`, all columns will be added except `source`, `target` and `edge_key`. + If `None`, no edge attributes are added to the graph. + + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + edge_key : str or None, optional (default=None) + A valid column name for the edge keys (for a MultiGraph). The values in + this column are used for the edge keys when adding edges if create_using + is a multigraph. + + Notes + ----- + If you have node attributes stored in a separate dataframe `df_nodes`, + you can load those attributes to the graph `G` using the following code:: + + df_nodes = pd.DataFrame({"node_id": [1, 2, 3], "attribute1": ["A", "B", "C"]}) + G.add_nodes_from((n, dict(d)) for n, d in df_nodes.iterrows()) + + See Also + -------- + to_pandas_edgelist + + Examples + -------- + Simple integer weights on edges: + + >>> import pandas as pd + >>> pd.options.display.max_columns = 20 + >>> import numpy as np + >>> rng = np.random.RandomState(seed=5) + >>> ints = rng.randint(1, 11, size=(3, 2)) + >>> a = ["A", "B", "C"] + >>> b = ["D", "A", "E"] + >>> df = pd.DataFrame(ints, columns=["weight", "cost"]) + >>> df[0] = a + >>> df["b"] = b + >>> df[["weight", "cost", 0, "b"]] + weight cost 0 b + 0 4 7 A D + 1 7 1 B A + 2 10 9 C E + >>> G = nx.from_pandas_edgelist(df, 0, "b", ["weight", "cost"]) + >>> G["E"]["C"]["weight"] + 10 + >>> G["E"]["C"]["cost"] + 9 + >>> edges = pd.DataFrame( + ... { + ... "source": [0, 1, 2], + ... "target": [2, 2, 3], + ... "weight": [3, 4, 5], + ... "color": ["red", "blue", "blue"], + ... } + ... ) + >>> G = nx.from_pandas_edgelist(edges, edge_attr=True) + >>> G[0][2]["color"] + 'red' + + Build multigraph with custom keys: + + >>> edges = pd.DataFrame( + ... { + ... "source": [0, 1, 2, 0], + ... "target": [2, 2, 3, 2], + ... "my_edge_key": ["A", "B", "C", "D"], + ... "weight": [3, 4, 5, 6], + ... "color": ["red", "blue", "blue", "blue"], + ... } + ... ) + >>> G = nx.from_pandas_edgelist( + ... edges, + ... edge_key="my_edge_key", + ... edge_attr=["weight", "color"], + ... create_using=nx.MultiGraph(), + ... ) + >>> G[0][2] + AtlasView({'A': {'weight': 3, 'color': 'red'}, 'D': {'weight': 6, 'color': 'blue'}}) + + + """ + g = nx.empty_graph(0, create_using) + + if edge_attr is None: + if g.is_multigraph() and edge_key is not None: + for u, v, k in zip(df[source], df[target], df[edge_key]): + g.add_edge(u, v, k) + else: + g.add_edges_from(zip(df[source], df[target])) + return g + + reserved_columns = [source, target] + if g.is_multigraph() and edge_key is not None: + reserved_columns.append(edge_key) + + # Additional columns requested + attr_col_headings = [] + attribute_data = [] + if edge_attr is True: + attr_col_headings = [c for c in df.columns if c not in reserved_columns] + elif isinstance(edge_attr, list | tuple): + attr_col_headings = edge_attr + else: + attr_col_headings = [edge_attr] + if len(attr_col_headings) == 0: + raise nx.NetworkXError( + f"Invalid edge_attr argument: No columns found with name: {attr_col_headings}" + ) + + try: + attribute_data = zip(*[df[col] for col in attr_col_headings]) + except (KeyError, TypeError) as err: + msg = f"Invalid edge_attr argument: {edge_attr}" + raise nx.NetworkXError(msg) from err + + if g.is_multigraph(): + # => append the edge keys from the df to the bundled data + if edge_key is not None: + try: + multigraph_edge_keys = df[edge_key] + attribute_data = zip(attribute_data, multigraph_edge_keys) + except (KeyError, TypeError) as err: + msg = f"Invalid edge_key argument: {edge_key}" + raise nx.NetworkXError(msg) from err + + for s, t, attrs in zip(df[source], df[target], attribute_data): + if edge_key is not None: + attrs, multigraph_edge_key = attrs + key = g.add_edge(s, t, key=multigraph_edge_key) + else: + key = g.add_edge(s, t) + + g[s][t][key].update(zip(attr_col_headings, attrs)) + else: + for s, t, attrs in zip(df[source], df[target], attribute_data): + g.add_edge(s, t) + g[s][t].update(zip(attr_col_headings, attrs)) + + return g + + +@nx._dispatchable(edge_attrs="weight") +def to_scipy_sparse_array(G, nodelist=None, dtype=None, weight="weight", format="csr"): + """Returns the graph adjacency matrix as a SciPy sparse array. + + Parameters + ---------- + G : graph + The NetworkX graph used to construct the sparse array. + + nodelist : list, optional + The rows and columns are ordered according to the nodes in `nodelist`. + If `nodelist` is None, then the ordering is produced by ``G.nodes()``. + + dtype : NumPy data-type, optional + A valid NumPy dtype used to initialize the array. If None, then the + NumPy default is used. + + weight : string or None, optional (default='weight') + The edge attribute that holds the numerical value used for + the edge weight. If None then all edge weights are 1. + + format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'} + The format of the sparse array to be returned (default 'csr'). For + some algorithms different implementations of sparse arrays + can perform better. See [1]_ for details. + + Returns + ------- + A : SciPy sparse array + Graph adjacency matrix. + + Notes + ----- + For directed graphs, matrix entry ``i, j`` corresponds to an edge from + ``i`` to ``j``. + + The values of the adjacency matrix are populated using the edge attribute held in + parameter `weight`. When an edge does not have that attribute, the + value of the entry is 1. + + For multiple edges the matrix values are the sums of the edge weights. + + When `nodelist` does not contain every node in `G`, the adjacency matrix + is built from the subgraph of `G` that is induced by the nodes in + `nodelist`. + + The convention used for self-loop edges in graphs is to assign the + diagonal matrix entry value to the weight attribute of the edge + (or the number 1 if the edge has no weight attribute). If the + alternate convention of doubling the edge weight is desired the + resulting array can be modified as follows:: + + >>> G = nx.Graph([(1, 1)]) + >>> A = nx.to_scipy_sparse_array(G) + >>> A.toarray() + array([[1]]) + >>> A.setdiag(A.diagonal() * 2) + >>> A.toarray() + array([[2]]) + + Examples + -------- + + Basic usage: + + >>> G = nx.path_graph(4) + >>> A = nx.to_scipy_sparse_array(G) + >>> A # doctest: +SKIP + + + >>> A.toarray() + array([[0, 1, 0, 0], + [1, 0, 1, 0], + [0, 1, 0, 1], + [0, 0, 1, 0]]) + + .. note:: The `toarray` method is used in these examples to better visualize + the adjacency matrix. For a dense representation of the adjaceny matrix, + use `to_numpy_array` instead. + + Directed graphs: + + >>> G = nx.DiGraph([(0, 1), (1, 2), (2, 3)]) + >>> nx.to_scipy_sparse_array(G).toarray() + array([[0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + [0, 0, 0, 0]]) + + >>> H = G.reverse() + >>> H.edges + OutEdgeView([(1, 0), (2, 1), (3, 2)]) + >>> nx.to_scipy_sparse_array(H).toarray() + array([[0, 0, 0, 0], + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0]]) + + By default, the order of the rows/columns of the adjacency matrix is determined + by the ordering of the nodes in `G`: + + >>> G = nx.Graph() + >>> G.add_nodes_from([3, 5, 0, 1]) + >>> G.add_edges_from([(1, 3), (1, 5)]) + >>> nx.to_scipy_sparse_array(G).toarray() + array([[0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 0], + [1, 1, 0, 0]]) + + The ordering of the rows can be changed with `nodelist`: + + >>> ordered = [0, 1, 3, 5] + >>> nx.to_scipy_sparse_array(G, nodelist=ordered).toarray() + array([[0, 0, 0, 0], + [0, 0, 1, 1], + [0, 1, 0, 0], + [0, 1, 0, 0]]) + + If `nodelist` contains a subset of the nodes in `G`, the adjacency matrix + for the node-induced subgraph is produced: + + >>> nx.to_scipy_sparse_array(G, nodelist=[1, 3, 5]).toarray() + array([[0, 1, 1], + [1, 0, 0], + [1, 0, 0]]) + + The values of the adjacency matrix are drawn from the edge attribute + specified by the `weight` parameter: + + >>> G = nx.path_graph(4) + >>> nx.set_edge_attributes( + ... G, values={(0, 1): 1, (1, 2): 10, (2, 3): 2}, name="weight" + ... ) + >>> nx.set_edge_attributes( + ... G, values={(0, 1): 50, (1, 2): 35, (2, 3): 10}, name="capacity" + ... ) + >>> nx.to_scipy_sparse_array(G).toarray() # Default weight="weight" + array([[ 0, 1, 0, 0], + [ 1, 0, 10, 0], + [ 0, 10, 0, 2], + [ 0, 0, 2, 0]]) + >>> nx.to_scipy_sparse_array(G, weight="capacity").toarray() + array([[ 0, 50, 0, 0], + [50, 0, 35, 0], + [ 0, 35, 0, 10], + [ 0, 0, 10, 0]]) + + Any edges that don't have a `weight` attribute default to 1: + + >>> G[1][2].pop("capacity") + 35 + >>> nx.to_scipy_sparse_array(G, weight="capacity").toarray() + array([[ 0, 50, 0, 0], + [50, 0, 1, 0], + [ 0, 1, 0, 10], + [ 0, 0, 10, 0]]) + + When `G` is a multigraph, the values in the adjacency matrix are given by + the sum of the `weight` edge attribute over each edge key: + + >>> G = nx.MultiDiGraph([(0, 1), (0, 1), (0, 1), (2, 0)]) + >>> nx.to_scipy_sparse_array(G).toarray() + array([[0, 3, 0], + [0, 0, 0], + [1, 0, 0]]) + + References + ---------- + .. [1] Scipy Dev. References, "Sparse Arrays", + https://docs.scipy.org/doc/scipy/reference/sparse.html + """ + import scipy as sp + + if len(G) == 0: + raise nx.NetworkXError("Graph has no nodes or edges") + + if nodelist is None: + nodelist = list(G) + nlen = len(G) + else: + nlen = len(nodelist) + if nlen == 0: + raise nx.NetworkXError("nodelist has no nodes") + nodeset = set(G.nbunch_iter(nodelist)) + if nlen != len(nodeset): + for n in nodelist: + if n not in G: + raise nx.NetworkXError(f"Node {n} in nodelist is not in G") + raise nx.NetworkXError("nodelist contains duplicates.") + if nlen < len(G): + G = G.subgraph(nodelist) + + index = dict(zip(nodelist, range(nlen))) + coefficients = zip( + *((index[u], index[v], wt) for u, v, wt in G.edges(data=weight, default=1)) + ) + try: + row, col, data = coefficients + except ValueError: + # there is no edge in the subgraph + row, col, data = [], [], [] + + if G.is_directed(): + A = sp.sparse.coo_array((data, (row, col)), shape=(nlen, nlen), dtype=dtype) + else: + # symmetrize matrix + d = data + data + r = row + col + c = col + row + # selfloop entries get double counted when symmetrizing + # so we subtract the data on the diagonal + selfloops = list(nx.selfloop_edges(G, data=weight, default=1)) + if selfloops: + diag_index, diag_data = zip(*((index[u], -wt) for u, v, wt in selfloops)) + d += diag_data + r += diag_index + c += diag_index + A = sp.sparse.coo_array((d, (r, c)), shape=(nlen, nlen), dtype=dtype) + try: + return A.asformat(format) + except ValueError as err: + raise nx.NetworkXError(f"Unknown sparse matrix format: {format}") from err + + +def _csr_gen_triples(A): + """Converts a SciPy sparse array in **Compressed Sparse Row** format to + an iterable of weighted edge triples. + + """ + nrows = A.shape[0] + indptr, dst_indices, data = A.indptr, A.indices, A.data + import numpy as np + + src_indices = np.repeat(np.arange(nrows), np.diff(indptr)) + return zip(src_indices.tolist(), dst_indices.tolist(), A.data.tolist()) + + +def _csc_gen_triples(A): + """Converts a SciPy sparse array in **Compressed Sparse Column** format to + an iterable of weighted edge triples. + + """ + ncols = A.shape[1] + indptr, src_indices, data = A.indptr, A.indices, A.data + import numpy as np + + dst_indices = np.repeat(np.arange(ncols), np.diff(indptr)) + return zip(src_indices.tolist(), dst_indices.tolist(), A.data.tolist()) + + +def _coo_gen_triples(A): + """Converts a SciPy sparse array in **Coordinate** format to an iterable + of weighted edge triples. + + """ + return zip(A.row.tolist(), A.col.tolist(), A.data.tolist()) + + +def _dok_gen_triples(A): + """Converts a SciPy sparse array in **Dictionary of Keys** format to an + iterable of weighted edge triples. + + """ + for (r, c), v in A.items(): + # Use `v.item()` to convert a NumPy scalar to the appropriate Python scalar + yield int(r), int(c), v.item() + + +def _generate_weighted_edges(A): + """Returns an iterable over (u, v, w) triples, where u and v are adjacent + vertices and w is the weight of the edge joining u and v. + + `A` is a SciPy sparse array (in any format). + + """ + if A.format == "csr": + return _csr_gen_triples(A) + if A.format == "csc": + return _csc_gen_triples(A) + if A.format == "dok": + return _dok_gen_triples(A) + # If A is in any other format (including COO), convert it to COO format. + return _coo_gen_triples(A.tocoo()) + + +@nx._dispatchable(graphs=None, returns_graph=True) +def from_scipy_sparse_array( + A, parallel_edges=False, create_using=None, edge_attribute="weight" +): + """Creates a new graph from an adjacency matrix given as a SciPy sparse + array. + + Parameters + ---------- + A: scipy.sparse array + An adjacency matrix representation of a graph + + parallel_edges : Boolean + If this is True, `create_using` is a multigraph, and `A` is an + integer matrix, then entry *(i, j)* in the matrix is interpreted as the + number of parallel edges joining vertices *i* and *j* in the graph. + If it is False, then the entries in the matrix are interpreted as + the weight of a single edge joining the vertices. + + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + edge_attribute: string + Name of edge attribute to store matrix numeric value. The data will + have the same type as the matrix entry (int, float, (real,imag)). + + Notes + ----- + For directed graphs, explicitly mention create_using=nx.DiGraph, + and entry i,j of A corresponds to an edge from i to j. + + If `create_using` is :class:`networkx.MultiGraph` or + :class:`networkx.MultiDiGraph`, `parallel_edges` is True, and the + entries of `A` are of type :class:`int`, then this function returns a + multigraph (constructed from `create_using`) with parallel edges. + In this case, `edge_attribute` will be ignored. + + If `create_using` indicates an undirected multigraph, then only the edges + indicated by the upper triangle of the matrix `A` will be added to the + graph. + + Examples + -------- + >>> import scipy as sp + >>> A = sp.sparse.eye(2, 2, 1) + >>> G = nx.from_scipy_sparse_array(A) + + If `create_using` indicates a multigraph and the matrix has only integer + entries and `parallel_edges` is False, then the entries will be treated + as weights for edges joining the nodes (without creating parallel edges): + + >>> A = sp.sparse.csr_array([[1, 1], [1, 2]]) + >>> G = nx.from_scipy_sparse_array(A, create_using=nx.MultiGraph) + >>> G[1][1] + AtlasView({0: {'weight': 2}}) + + If `create_using` indicates a multigraph and the matrix has only integer + entries and `parallel_edges` is True, then the entries will be treated + as the number of parallel edges joining those two vertices: + + >>> A = sp.sparse.csr_array([[1, 1], [1, 2]]) + >>> G = nx.from_scipy_sparse_array( + ... A, parallel_edges=True, create_using=nx.MultiGraph + ... ) + >>> G[1][1] + AtlasView({0: {'weight': 1}, 1: {'weight': 1}}) + + """ + G = nx.empty_graph(0, create_using) + n, m = A.shape + if n != m: + raise nx.NetworkXError(f"Adjacency matrix not square: nx,ny={A.shape}") + # Make sure we get even the isolated nodes of the graph. + G.add_nodes_from(range(n)) + # Create an iterable over (u, v, w) triples and for each triple, add an + # edge from u to v with weight w. + triples = _generate_weighted_edges(A) + # If the entries in the adjacency matrix are integers, the graph is a + # multigraph, and parallel_edges is True, then create parallel edges, each + # with weight 1, for each entry in the adjacency matrix. Otherwise, create + # one edge for each positive entry in the adjacency matrix and set the + # weight of that edge to be the entry in the matrix. + if A.dtype.kind in ("i", "u") and G.is_multigraph() and parallel_edges: + chain = itertools.chain.from_iterable + # The following line is equivalent to: + # + # for (u, v) in edges: + # for d in range(A[u, v]): + # G.add_edge(u, v, weight=1) + # + triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples) + # If we are creating an undirected multigraph, only add the edges from the + # upper triangle of the matrix. Otherwise, add all the edges. This relies + # on the fact that the vertices created in the + # `_generated_weighted_edges()` function are actually the row/column + # indices for the matrix `A`. + # + # Without this check, we run into a problem where each edge is added twice + # when `G.add_weighted_edges_from()` is invoked below. + if G.is_multigraph() and not G.is_directed(): + triples = ((u, v, d) for u, v, d in triples if u <= v) + G.add_weighted_edges_from(triples, weight=edge_attribute) + return G + + +@nx._dispatchable(edge_attrs="weight") # edge attrs may also be obtained from `dtype` +def to_numpy_array( + G, + nodelist=None, + dtype=None, + order=None, + multigraph_weight=sum, + weight="weight", + nonedge=0.0, +): + """Returns the graph adjacency matrix as a NumPy array. + + Parameters + ---------- + G : graph + The NetworkX graph used to construct the NumPy array. + + nodelist : list, optional + The rows and columns are ordered according to the nodes in `nodelist`. + If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``. + + dtype : NumPy data type, optional + A NumPy data type used to initialize the array. If None, then the NumPy + default is used. The dtype can be structured if `weight=None`, in which + case the dtype field names are used to look up edge attributes. The + result is a structured array where each named field in the dtype + corresponds to the adjacency for that edge attribute. See examples for + details. + + order : {'C', 'F'}, optional + Whether to store multidimensional data in C- or Fortran-contiguous + (row- or column-wise) order in memory. If None, then the NumPy default + is used. + + multigraph_weight : callable, optional + An function that determines how weights in multigraphs are handled. + The function should accept a sequence of weights and return a single + value. The default is to sum the weights of the multiple edges. + + weight : string or None optional (default = 'weight') + The edge attribute that holds the numerical value used for + the edge weight. If an edge does not have that attribute, then the + value 1 is used instead. `weight` must be ``None`` if a structured + dtype is used. + + nonedge : array_like (default = 0.0) + The value used to represent non-edges in the adjacency matrix. + The array values corresponding to nonedges are typically set to zero. + However, this could be undesirable if there are array values + corresponding to actual edges that also have the value zero. If so, + one might prefer nonedges to have some other value, such as ``nan``. + + Returns + ------- + A : NumPy ndarray + Graph adjacency matrix + + Raises + ------ + NetworkXError + If `dtype` is a structured dtype and `G` is a multigraph + ValueError + If `dtype` is a structured dtype and `weight` is not `None` + + See Also + -------- + from_numpy_array + + Notes + ----- + For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``. + + Entries in the adjacency matrix are given by the `weight` edge attribute. + When an edge does not have a weight attribute, the value of the entry is + set to the number 1. For multiple (parallel) edges, the values of the + entries are determined by the `multigraph_weight` parameter. The default is + to sum the weight attributes for each of the parallel edges. + + When `nodelist` does not contain every node in `G`, the adjacency matrix is + built from the subgraph of `G` that is induced by the nodes in `nodelist`. + + The convention used for self-loop edges in graphs is to assign the + diagonal array entry value to the weight attribute of the edge + (or the number 1 if the edge has no weight attribute). If the + alternate convention of doubling the edge weight is desired the + resulting NumPy array can be modified as follows: + + >>> import numpy as np + >>> G = nx.Graph([(1, 1)]) + >>> A = nx.to_numpy_array(G) + >>> A + array([[1.]]) + >>> A[np.diag_indices_from(A)] *= 2 + >>> A + array([[2.]]) + + Examples + -------- + >>> G = nx.MultiDiGraph() + >>> G.add_edge(0, 1, weight=2) + 0 + >>> G.add_edge(1, 0) + 0 + >>> G.add_edge(2, 2, weight=3) + 0 + >>> G.add_edge(2, 2) + 1 + >>> nx.to_numpy_array(G, nodelist=[0, 1, 2]) + array([[0., 2., 0.], + [1., 0., 0.], + [0., 0., 4.]]) + + When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist` + and their edges are not included in the adjacency matrix. Here is an example: + + >>> G = nx.Graph() + >>> G.add_edge(3, 1) + >>> G.add_edge(2, 0) + >>> G.add_edge(2, 1) + >>> G.add_edge(3, 0) + >>> nx.to_numpy_array(G, nodelist=[1, 2, 3]) + array([[0., 1., 1.], + [1., 0., 0.], + [1., 0., 0.]]) + + This function can also be used to create adjacency matrices for multiple + edge attributes with structured dtypes: + + >>> G = nx.Graph() + >>> G.add_edge(0, 1, weight=10) + >>> G.add_edge(1, 2, cost=5) + >>> G.add_edge(2, 3, weight=3, cost=-4.0) + >>> dtype = np.dtype([("weight", int), ("cost", float)]) + >>> A = nx.to_numpy_array(G, dtype=dtype, weight=None) + >>> A["weight"] + array([[ 0, 10, 0, 0], + [10, 0, 1, 0], + [ 0, 1, 0, 3], + [ 0, 0, 3, 0]]) + >>> A["cost"] + array([[ 0., 1., 0., 0.], + [ 1., 0., 5., 0.], + [ 0., 5., 0., -4.], + [ 0., 0., -4., 0.]]) + + As stated above, the argument "nonedge" is useful especially when there are + actually edges with weight 0 in the graph. Setting a nonedge value different than 0, + makes it much clearer to differentiate such 0-weighted edges and actual nonedge values. + + >>> G = nx.Graph() + >>> G.add_edge(3, 1, weight=2) + >>> G.add_edge(2, 0, weight=0) + >>> G.add_edge(2, 1, weight=0) + >>> G.add_edge(3, 0, weight=1) + >>> nx.to_numpy_array(G, nonedge=-1.0) + array([[-1., 2., -1., 1.], + [ 2., -1., 0., -1.], + [-1., 0., -1., 0.], + [ 1., -1., 0., -1.]]) + """ + import numpy as np + + if nodelist is None: + nodelist = list(G) + nlen = len(nodelist) + + # Input validation + nodeset = set(nodelist) + if nodeset - set(G): + raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G") + if len(nodeset) < nlen: + raise nx.NetworkXError("nodelist contains duplicates.") + + A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order) + + # Corner cases: empty nodelist or graph without any edges + if nlen == 0 or G.number_of_edges() == 0: + return A + + # If dtype is structured and weight is None, use dtype field names as + # edge attributes + edge_attrs = None # Only single edge attribute by default + if A.dtype.names: + if weight is None: + edge_attrs = dtype.names + else: + raise ValueError( + "Specifying `weight` not supported for structured dtypes\n." + "To create adjacency matrices from structured dtypes, use `weight=None`." + ) + + # Map nodes to row/col in matrix + idx = dict(zip(nodelist, range(nlen))) + if len(nodelist) < len(G): + G = G.subgraph(nodelist).copy() + + # Collect all edge weights and reduce with `multigraph_weights` + if G.is_multigraph(): + if edge_attrs: + raise nx.NetworkXError( + "Structured arrays are not supported for MultiGraphs" + ) + d = defaultdict(list) + for u, v, wt in G.edges(data=weight, default=1.0): + d[(idx[u], idx[v])].append(wt) + i, j = np.array(list(d.keys())).T # indices + wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights + else: + i, j, wts = [], [], [] + + # Special branch: multi-attr adjacency from structured dtypes + if edge_attrs: + # Extract edges with all data + for u, v, data in G.edges(data=True): + i.append(idx[u]) + j.append(idx[v]) + wts.append(data) + # Map each attribute to the appropriate named field in the + # structured dtype + for attr in edge_attrs: + attr_data = [wt.get(attr, 1.0) for wt in wts] + A[attr][i, j] = attr_data + if not G.is_directed(): + A[attr][j, i] = attr_data + return A + + for u, v, wt in G.edges(data=weight, default=1.0): + i.append(idx[u]) + j.append(idx[v]) + wts.append(wt) + + # Set array values with advanced indexing + A[i, j] = wts + if not G.is_directed(): + A[j, i] = wts + + return A + + +@nx._dispatchable(graphs=None, returns_graph=True) +def from_numpy_array( + A, parallel_edges=False, create_using=None, edge_attr="weight", *, nodelist=None +): + """Returns a graph from a 2D NumPy array. + + The 2D NumPy array is interpreted as an adjacency matrix for the graph. + + Parameters + ---------- + A : a 2D numpy.ndarray + An adjacency matrix representation of a graph + + parallel_edges : Boolean + If this is True, `create_using` is a multigraph, and `A` is an + integer array, then entry *(i, j)* in the array is interpreted as the + number of parallel edges joining vertices *i* and *j* in the graph. + If it is False, then the entries in the array are interpreted as + the weight of a single edge joining the vertices. + + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + + edge_attr : String, optional (default="weight") + The attribute to which the array values are assigned on each edge. If + it is None, edge attributes will not be assigned. + + nodelist : sequence of nodes, optional + A sequence of objects to use as the nodes in the graph. If provided, the + list of nodes must be the same length as the dimensions of `A`. The + default is `None`, in which case the nodes are drawn from ``range(n)``. + + Notes + ----- + For directed graphs, explicitly mention create_using=nx.DiGraph, + and entry i,j of A corresponds to an edge from i to j. + + If `create_using` is :class:`networkx.MultiGraph` or + :class:`networkx.MultiDiGraph`, `parallel_edges` is True, and the + entries of `A` are of type :class:`int`, then this function returns a + multigraph (of the same type as `create_using`) with parallel edges. + + If `create_using` indicates an undirected multigraph, then only the edges + indicated by the upper triangle of the array `A` will be added to the + graph. + + If `edge_attr` is Falsy (False or None), edge attributes will not be + assigned, and the array data will be treated like a binary mask of + edge presence or absence. Otherwise, the attributes will be assigned + as follows: + + If the NumPy array has a single data type for each array entry it + will be converted to an appropriate Python data type. + + If the NumPy array has a user-specified compound data type the names + of the data fields will be used as attribute keys in the resulting + NetworkX graph. + + See Also + -------- + to_numpy_array + + Examples + -------- + Simple integer weights on edges: + + >>> import numpy as np + >>> A = np.array([[1, 1], [2, 1]]) + >>> G = nx.from_numpy_array(A) + >>> G.edges(data=True) + EdgeDataView([(0, 0, {'weight': 1}), (0, 1, {'weight': 2}), (1, 1, {'weight': 1})]) + + If `create_using` indicates a multigraph and the array has only integer + entries and `parallel_edges` is False, then the entries will be treated + as weights for edges joining the nodes (without creating parallel edges): + + >>> A = np.array([[1, 1], [1, 2]]) + >>> G = nx.from_numpy_array(A, create_using=nx.MultiGraph) + >>> G[1][1] + AtlasView({0: {'weight': 2}}) + + If `create_using` indicates a multigraph and the array has only integer + entries and `parallel_edges` is True, then the entries will be treated + as the number of parallel edges joining those two vertices: + + >>> A = np.array([[1, 1], [1, 2]]) + >>> temp = nx.MultiGraph() + >>> G = nx.from_numpy_array(A, parallel_edges=True, create_using=temp) + >>> G[1][1] + AtlasView({0: {'weight': 1}, 1: {'weight': 1}}) + + User defined compound data type on edges: + + >>> dt = [("weight", float), ("cost", int)] + >>> A = np.array([[(1.0, 2)]], dtype=dt) + >>> G = nx.from_numpy_array(A) + >>> G.edges() + EdgeView([(0, 0)]) + >>> G[0][0]["cost"] + 2 + >>> G[0][0]["weight"] + 1.0 + + """ + kind_to_python_type = { + "f": float, + "i": int, + "u": int, + "b": bool, + "c": complex, + "S": str, + "U": str, + "V": "void", + } + G = nx.empty_graph(0, create_using) + if A.ndim != 2: + raise nx.NetworkXError(f"Input array must be 2D, not {A.ndim}") + n, m = A.shape + if n != m: + raise nx.NetworkXError(f"Adjacency matrix not square: nx,ny={A.shape}") + dt = A.dtype + try: + python_type = kind_to_python_type[dt.kind] + except Exception as err: + raise TypeError(f"Unknown numpy data type: {dt}") from err + if _default_nodes := (nodelist is None): + nodelist = range(n) + else: + if len(nodelist) != n: + raise ValueError("nodelist must have the same length as A.shape[0]") + + # Make sure we get even the isolated nodes of the graph. + G.add_nodes_from(nodelist) + # Get a list of all the entries in the array with nonzero entries. These + # coordinates become edges in the graph. (convert to int from np.int64) + edges = ((int(e[0]), int(e[1])) for e in zip(*A.nonzero())) + # handle numpy constructed data type + if python_type == "void": + # Sort the fields by their offset, then by dtype, then by name. + fields = sorted( + (offset, dtype, name) for name, (dtype, offset) in A.dtype.fields.items() + ) + triples = ( + ( + u, + v, + {} + if edge_attr in [False, None] + else { + name: kind_to_python_type[dtype.kind](val) + for (_, dtype, name), val in zip(fields, A[u, v]) + }, + ) + for u, v in edges + ) + # If the entries in the adjacency matrix are integers, the graph is a + # multigraph, and parallel_edges is True, then create parallel edges, each + # with weight 1, for each entry in the adjacency matrix. Otherwise, create + # one edge for each positive entry in the adjacency matrix and set the + # weight of that edge to be the entry in the matrix. + elif python_type is int and G.is_multigraph() and parallel_edges: + chain = itertools.chain.from_iterable + # The following line is equivalent to: + # + # for (u, v) in edges: + # for d in range(A[u, v]): + # G.add_edge(u, v, weight=1) + # + if edge_attr in [False, None]: + triples = chain(((u, v, {}) for d in range(A[u, v])) for (u, v) in edges) + else: + triples = chain( + ((u, v, {edge_attr: 1}) for d in range(A[u, v])) for (u, v) in edges + ) + else: # basic data type + if edge_attr in [False, None]: + triples = ((u, v, {}) for u, v in edges) + else: + triples = ((u, v, {edge_attr: python_type(A[u, v])}) for u, v in edges) + # If we are creating an undirected multigraph, only add the edges from the + # upper triangle of the matrix. Otherwise, add all the edges. This relies + # on the fact that the vertices created in the + # `_generated_weighted_edges()` function are actually the row/column + # indices for the matrix `A`. + # + # Without this check, we run into a problem where each edge is added twice + # when `G.add_edges_from()` is invoked below. + if G.is_multigraph() and not G.is_directed(): + triples = ((u, v, d) for u, v, d in triples if u <= v) + # Remap nodes if user provided custom `nodelist` + if not _default_nodes: + idx_to_node = dict(enumerate(nodelist)) + triples = ((idx_to_node[u], idx_to_node[v], d) for u, v, d in triples) + G.add_edges_from(triples) + return G diff --git a/data/miniconda3/lib/python3.13/site-packages/networkx/exception.py b/data/miniconda3/lib/python3.13/site-packages/networkx/exception.py new file mode 100644 index 0000000000000000000000000000000000000000..c960cf13fd5a8e4da0ca68c66350b8baa1728c34 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/networkx/exception.py @@ -0,0 +1,131 @@ +""" +********** +Exceptions +********** + +Base exceptions and errors for NetworkX. +""" + +__all__ = [ + "HasACycle", + "NodeNotFound", + "PowerIterationFailedConvergence", + "ExceededMaxIterations", + "AmbiguousSolution", + "NetworkXAlgorithmError", + "NetworkXException", + "NetworkXError", + "NetworkXNoCycle", + "NetworkXNoPath", + "NetworkXNotImplemented", + "NetworkXPointlessConcept", + "NetworkXUnbounded", + "NetworkXUnfeasible", +] + + +class NetworkXException(Exception): + """Base class for exceptions in NetworkX.""" + + +class NetworkXError(NetworkXException): + """Exception for a serious error in NetworkX""" + + +class NetworkXPointlessConcept(NetworkXException): + """Raised when a null graph is provided as input to an algorithm + that cannot use it. + + The null graph is sometimes considered a pointless concept [1]_, + thus the name of the exception. + + Notes + ----- + Null graphs and empty graphs are often used interchangeably but they + are well defined in NetworkX. An ``empty_graph`` is a graph with ``n`` nodes + and 0 edges, and a ``null_graph`` is a graph with 0 nodes and 0 edges. + + References + ---------- + .. [1] Harary, F. and Read, R. "Is the Null Graph a Pointless + Concept?" In Graphs and Combinatorics Conference, George + Washington University. New York: Springer-Verlag, 1973. + + """ + + +class NetworkXAlgorithmError(NetworkXException): + """Exception for unexpected termination of algorithms.""" + + +class NetworkXUnfeasible(NetworkXAlgorithmError): + """Exception raised by algorithms trying to solve a problem + instance that has no feasible solution.""" + + +class NetworkXNoPath(NetworkXUnfeasible): + """Exception for algorithms that should return a path when running + on graphs where such a path does not exist.""" + + +class NetworkXNoCycle(NetworkXUnfeasible): + """Exception for algorithms that should return a cycle when running + on graphs where such a cycle does not exist.""" + + +class HasACycle(NetworkXException): + """Raised if a graph has a cycle when an algorithm expects that it + will have no cycles. + + """ + + +class NetworkXUnbounded(NetworkXAlgorithmError): + """Exception raised by algorithms trying to solve a maximization + or a minimization problem instance that is unbounded.""" + + +class NetworkXNotImplemented(NetworkXException): + """Exception raised by algorithms not implemented for a type of graph.""" + + +class NodeNotFound(NetworkXException): + """Exception raised if requested node is not present in the graph""" + + +class AmbiguousSolution(NetworkXException): + """Raised if more than one valid solution exists for an intermediary step + of an algorithm. + + In the face of ambiguity, refuse the temptation to guess. + This may occur, for example, when trying to determine the + bipartite node sets in a disconnected bipartite graph when + computing bipartite matchings. + + """ + + +class ExceededMaxIterations(NetworkXException): + """Raised if a loop iterates too many times without breaking. + + This may occur, for example, in an algorithm that computes + progressively better approximations to a value but exceeds an + iteration bound specified by the user. + + """ + + +class PowerIterationFailedConvergence(ExceededMaxIterations): + """Raised when the power iteration method fails to converge within a + specified iteration limit. + + `num_iterations` is the number of iterations that have been + completed when this exception was raised. + + """ + + def __init__(self, num_iterations, *args, **kw): + msg = f"power iteration failed to converge within {num_iterations} iterations" + exception_message = msg + superinit = super().__init__ + superinit(self, exception_message, *args, **kw) diff --git a/data/miniconda3/lib/python3.13/site-packages/networkx/lazy_imports.py b/data/miniconda3/lib/python3.13/site-packages/networkx/lazy_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c05ca5462868fbccc270ea1e93b301037dfc8c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/networkx/lazy_imports.py @@ -0,0 +1,188 @@ +import importlib +import importlib.util +import inspect +import os +import sys +import types + +__all__ = ["attach", "_lazy_import"] + + +def attach(module_name, submodules=None, submod_attrs=None): + """Attach lazily loaded submodules, and functions or other attributes. + + Typically, modules import submodules and attributes as follows:: + + import mysubmodule + import anothersubmodule + + from .foo import someattr + + The idea of this function is to replace the `__init__.py` + module's `__getattr__`, `__dir__`, and `__all__` attributes such that + all imports work exactly the way they normally would, except that the + actual import is delayed until the resulting module object is first used. + + The typical way to call this function, replacing the above imports, is:: + + __getattr__, __lazy_dir__, __all__ = lazy.attach( + __name__, ["mysubmodule", "anothersubmodule"], {"foo": "someattr"} + ) + + This functionality requires Python 3.7 or higher. + + Parameters + ---------- + module_name : str + Typically use __name__. + submodules : set + List of submodules to lazily import. + submod_attrs : dict + Dictionary of submodule -> list of attributes / functions. + These attributes are imported as they are used. + + Returns + ------- + __getattr__, __dir__, __all__ + + """ + if submod_attrs is None: + submod_attrs = {} + + if submodules is None: + submodules = set() + else: + submodules = set(submodules) + + attr_to_modules = { + attr: mod for mod, attrs in submod_attrs.items() for attr in attrs + } + + __all__ = list(submodules | attr_to_modules.keys()) + + def __getattr__(name): + if name in submodules: + return importlib.import_module(f"{module_name}.{name}") + elif name in attr_to_modules: + submod = importlib.import_module(f"{module_name}.{attr_to_modules[name]}") + return getattr(submod, name) + else: + raise AttributeError(f"No {module_name} attribute {name}") + + def __dir__(): + return __all__ + + if os.environ.get("EAGER_IMPORT", ""): + for attr in set(attr_to_modules.keys()) | submodules: + __getattr__(attr) + + return __getattr__, __dir__, list(__all__) + + +class DelayedImportErrorModule(types.ModuleType): + def __init__(self, frame_data, *args, **kwargs): + self.__frame_data = frame_data + super().__init__(*args, **kwargs) + + def __getattr__(self, x): + if x in ("__class__", "__file__", "__frame_data"): + super().__getattr__(x) + else: + fd = self.__frame_data + raise ModuleNotFoundError( + f"No module named '{fd['spec']}'\n\n" + "This error is lazily reported, having originally occurred in\n" + f" File {fd['filename']}, line {fd['lineno']}, in {fd['function']}\n\n" + f"----> {''.join(fd['code_context'] or '').strip()}" + ) + + +def _lazy_import(fullname): + """Return a lazily imported proxy for a module or library. + + Warning + ------- + Importing using this function can currently cause trouble + when the user tries to import from a subpackage of a module before + the package is fully imported. In particular, this idiom may not work: + + np = lazy_import("numpy") + from numpy.lib import recfunctions + + This is due to a difference in the way Python's LazyLoader handles + subpackage imports compared to the normal import process. Hopefully + we will get Python's LazyLoader to fix this, or find a workaround. + In the meantime, this is a potential problem. + + The workaround is to import numpy before importing from the subpackage. + + Notes + ----- + We often see the following pattern:: + + def myfunc(): + import scipy as sp + sp.argmin(...) + .... + + This is to prevent a library, in this case `scipy`, from being + imported at function definition time, since that can be slow. + + This function provides a proxy module that, upon access, imports + the actual module. So the idiom equivalent to the above example is:: + + sp = lazy.load("scipy") + + def myfunc(): + sp.argmin(...) + .... + + The initial import time is fast because the actual import is delayed + until the first attribute is requested. The overall import time may + decrease as well for users that don't make use of large portions + of the library. + + Parameters + ---------- + fullname : str + The full name of the package or subpackage to import. For example:: + + sp = lazy.load("scipy") # import scipy as sp + spla = lazy.load("scipy.linalg") # import scipy.linalg as spla + + Returns + ------- + pm : importlib.util._LazyModule + Proxy module. Can be used like any regularly imported module. + Actual loading of the module occurs upon first attribute request. + + """ + try: + return sys.modules[fullname] + except: + pass + + # Not previously loaded -- look it up + spec = importlib.util.find_spec(fullname) + + if spec is None: + try: + parent = inspect.stack()[1] + frame_data = { + "spec": fullname, + "filename": parent.filename, + "lineno": parent.lineno, + "function": parent.function, + "code_context": parent.code_context, + } + return DelayedImportErrorModule(frame_data, "DelayedImportErrorModule") + finally: + del parent + + module = importlib.util.module_from_spec(spec) + sys.modules[fullname] = module + + loader = importlib.util.LazyLoader(spec.loader) + loader.exec_module(module) + + return module diff --git a/data/miniconda3/lib/python3.13/site-packages/networkx/relabel.py b/data/miniconda3/lib/python3.13/site-packages/networkx/relabel.py new file mode 100644 index 0000000000000000000000000000000000000000..4b870f726ef42e0bcaa7bf724e2ae6ab4145f288 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/networkx/relabel.py @@ -0,0 +1,285 @@ +import networkx as nx + +__all__ = ["convert_node_labels_to_integers", "relabel_nodes"] + + +@nx._dispatchable( + preserve_all_attrs=True, mutates_input={"not copy": 2}, returns_graph=True +) +def relabel_nodes(G, mapping, copy=True): + """Relabel the nodes of the graph G according to a given mapping. + + The original node ordering may not be preserved if `copy` is `False` and the + mapping includes overlap between old and new labels. + + Parameters + ---------- + G : graph + A NetworkX graph + + mapping : dictionary + A dictionary with the old labels as keys and new labels as values. + A partial mapping is allowed. Mapping 2 nodes to a single node is allowed. + Any non-node keys in the mapping are ignored. + + copy : bool (optional, default=True) + If True return a copy, or if False relabel the nodes in place. + + Examples + -------- + To create a new graph with nodes relabeled according to a given + dictionary: + + >>> G = nx.path_graph(3) + >>> sorted(G) + [0, 1, 2] + >>> mapping = {0: "a", 1: "b", 2: "c"} + >>> H = nx.relabel_nodes(G, mapping) + >>> sorted(H) + ['a', 'b', 'c'] + + Nodes can be relabeled with any hashable object, including numbers + and strings: + + >>> import string + >>> G = nx.path_graph(26) # nodes are integers 0 through 25 + >>> sorted(G)[:3] + [0, 1, 2] + >>> mapping = dict(zip(G, string.ascii_lowercase)) + >>> G = nx.relabel_nodes(G, mapping) # nodes are characters a through z + >>> sorted(G)[:3] + ['a', 'b', 'c'] + >>> mapping = dict(zip(G, range(1, 27))) + >>> G = nx.relabel_nodes(G, mapping) # nodes are integers 1 through 26 + >>> sorted(G)[:3] + [1, 2, 3] + + To perform a partial in-place relabeling, provide a dictionary + mapping only a subset of the nodes, and set the `copy` keyword + argument to False: + + >>> G = nx.path_graph(3) # nodes 0-1-2 + >>> mapping = {0: "a", 1: "b"} # 0->'a' and 1->'b' + >>> G = nx.relabel_nodes(G, mapping, copy=False) + >>> sorted(G, key=str) + [2, 'a', 'b'] + + A mapping can also be given as a function: + + >>> G = nx.path_graph(3) + >>> H = nx.relabel_nodes(G, lambda x: x**2) + >>> list(H) + [0, 1, 4] + + In a multigraph, relabeling two or more nodes to the same new node + will retain all edges, but may change the edge keys in the process: + + >>> G = nx.MultiGraph() + >>> G.add_edge(0, 1, value="a") # returns the key for this edge + 0 + >>> G.add_edge(0, 2, value="b") + 0 + >>> G.add_edge(0, 3, value="c") + 0 + >>> mapping = {1: 4, 2: 4, 3: 4} + >>> H = nx.relabel_nodes(G, mapping, copy=True) + >>> print(H[0]) + {4: {0: {'value': 'a'}, 1: {'value': 'b'}, 2: {'value': 'c'}}} + + This works for in-place relabeling too: + + >>> G = nx.relabel_nodes(G, mapping, copy=False) + >>> print(G[0]) + {4: {0: {'value': 'a'}, 1: {'value': 'b'}, 2: {'value': 'c'}}} + + Notes + ----- + Only the nodes specified in the mapping will be relabeled. + Any non-node keys in the mapping are ignored. + + The keyword setting copy=False modifies the graph in place. + Relabel_nodes avoids naming collisions by building a + directed graph from ``mapping`` which specifies the order of + relabelings. Naming collisions, such as a->b, b->c, are ordered + such that "b" gets renamed to "c" before "a" gets renamed "b". + In cases of circular mappings (e.g. a->b, b->a), modifying the + graph is not possible in-place and an exception is raised. + In that case, use copy=True. + + If a relabel operation on a multigraph would cause two or more + edges to have the same source, target and key, the second edge must + be assigned a new key to retain all edges. The new key is set + to the lowest non-negative integer not already used as a key + for edges between these two nodes. Note that this means non-numeric + keys may be replaced by numeric keys. + + See Also + -------- + convert_node_labels_to_integers + """ + # you can pass any callable e.g. f(old_label) -> new_label or + # e.g. str(old_label) -> new_label, but we'll just make a dictionary here regardless + m = {n: mapping(n) for n in G} if callable(mapping) else mapping + + if copy: + return _relabel_copy(G, m) + else: + return _relabel_inplace(G, m) + + +def _relabel_inplace(G, mapping): + if len(mapping.keys() & mapping.values()) > 0: + # labels sets overlap + # can we topological sort and still do the relabeling? + D = nx.DiGraph(list(mapping.items())) + D.remove_edges_from(nx.selfloop_edges(D)) + try: + nodes = reversed(list(nx.topological_sort(D))) + except nx.NetworkXUnfeasible as err: + raise nx.NetworkXUnfeasible( + "The node label sets are overlapping and no ordering can " + "resolve the mapping. Use copy=True." + ) from err + else: + # non-overlapping label sets, sort them in the order of G nodes + nodes = [n for n in G if n in mapping] + + multigraph = G.is_multigraph() + directed = G.is_directed() + + for old in nodes: + # Test that old is in both mapping and G, otherwise ignore. + try: + new = mapping[old] + G.add_node(new, **G.nodes[old]) + except KeyError: + continue + if new == old: + continue + if multigraph: + new_edges = [ + (new, new if old == target else target, key, data) + for (_, target, key, data) in G.edges(old, data=True, keys=True) + ] + if directed: + new_edges += [ + (new if old == source else source, new, key, data) + for (source, _, key, data) in G.in_edges(old, data=True, keys=True) + ] + # Ensure new edges won't overwrite existing ones + seen = set() + for i, (source, target, key, data) in enumerate(new_edges): + if target in G[source] and key in G[source][target]: + new_key = 0 if not isinstance(key, int | float) else key + while new_key in G[source][target] or (target, new_key) in seen: + new_key += 1 + new_edges[i] = (source, target, new_key, data) + seen.add((target, new_key)) + else: + new_edges = [ + (new, new if old == target else target, data) + for (_, target, data) in G.edges(old, data=True) + ] + if directed: + new_edges += [ + (new if old == source else source, new, data) + for (source, _, data) in G.in_edges(old, data=True) + ] + G.remove_node(old) + G.add_edges_from(new_edges) + return G + + +def _relabel_copy(G, mapping): + H = G.__class__() + H.add_nodes_from(mapping.get(n, n) for n in G) + H._node.update((mapping.get(n, n), d.copy()) for n, d in G.nodes.items()) + if G.is_multigraph(): + new_edges = [ + (mapping.get(n1, n1), mapping.get(n2, n2), k, d.copy()) + for (n1, n2, k, d) in G.edges(keys=True, data=True) + ] + + # check for conflicting edge-keys + undirected = not G.is_directed() + seen_edges = set() + for i, (source, target, key, data) in enumerate(new_edges): + while (source, target, key) in seen_edges: + if not isinstance(key, int | float): + key = 0 + key += 1 + seen_edges.add((source, target, key)) + if undirected: + seen_edges.add((target, source, key)) + new_edges[i] = (source, target, key, data) + + H.add_edges_from(new_edges) + else: + H.add_edges_from( + (mapping.get(n1, n1), mapping.get(n2, n2), d.copy()) + for (n1, n2, d) in G.edges(data=True) + ) + H.graph.update(G.graph) + return H + + +@nx._dispatchable(preserve_all_attrs=True, returns_graph=True) +def convert_node_labels_to_integers( + G, first_label=0, ordering="default", label_attribute=None +): + """Returns a copy of the graph G with the nodes relabeled using + consecutive integers. + + Parameters + ---------- + G : graph + A NetworkX graph + + first_label : int, optional (default=0) + An integer specifying the starting offset in numbering nodes. + The new integer labels are numbered first_label, ..., n-1+first_label. + + ordering : string + "default" : inherit node ordering from G.nodes() + "sorted" : inherit node ordering from sorted(G.nodes()) + "increasing degree" : nodes are sorted by increasing degree + "decreasing degree" : nodes are sorted by decreasing degree + + label_attribute : string, optional (default=None) + Name of node attribute to store old label. If None no attribute + is created. + + Notes + ----- + Node and edge attribute data are copied to the new (relabeled) graph. + + There is no guarantee that the relabeling of nodes to integers will + give the same two integers for two (even identical graphs). + Use the `ordering` argument to try to preserve the order. + + See Also + -------- + relabel_nodes + """ + N = G.number_of_nodes() + first_label + if ordering == "default": + mapping = dict(zip(G.nodes(), range(first_label, N))) + elif ordering == "sorted": + nlist = sorted(G.nodes()) + mapping = dict(zip(nlist, range(first_label, N))) + elif ordering == "increasing degree": + dv_pairs = [(d, n) for (n, d) in G.degree()] + dv_pairs.sort() # in-place sort from lowest to highest degree + mapping = dict(zip([n for d, n in dv_pairs], range(first_label, N))) + elif ordering == "decreasing degree": + dv_pairs = [(d, n) for (n, d) in G.degree()] + dv_pairs.sort() # in-place sort from lowest to highest degree + dv_pairs.reverse() + mapping = dict(zip([n for d, n in dv_pairs], range(first_label, N))) + else: + raise nx.NetworkXError(f"Unknown node ordering: {ordering}") + H = relabel_nodes(G, mapping) + # create node attribute with the old label + if label_attribute is not None: + nx.set_node_attributes(H, {v: k for k, v in mapping.items()}, label_attribute) + return H diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/__config__.py b/data/miniconda3/lib/python3.13/site-packages/numpy/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7883a5bdc10c4c3a8dbd62e3bf9a3fae296c02a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/__config__.py @@ -0,0 +1,170 @@ +# This file is generated by numpy's build process +# It contains system_info results at the time of building this package. +from enum import Enum +from numpy._core._multiarray_umath import ( + __cpu_features__, + __cpu_baseline__, + __cpu_dispatch__, +) + +__all__ = ["show_config"] +_built_with_meson = True + + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + + +def _cleanup(d): + """ + Removes empty values in a `dict` recursively + This ensures we remove values that Meson could not provide to CONFIG + """ + if isinstance(d, dict): + return {k: _cleanup(v) for k, v in d.items() if v and _cleanup(v)} + else: + return d + + +CONFIG = _cleanup( + { + "Compilers": { + "c": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "14.2.1", + "commands": r"cc", + "args": r"", + "linker args": r"", + }, + "cython": { + "name": "cython", + "linker": r"cython", + "version": "3.2.4", + "commands": r"cython", + "args": r"", + "linker args": r"", + }, + "c++": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "14.2.1", + "commands": r"c++", + "args": r"", + "linker args": r"", + }, + }, + "Machine Information": { + "host": { + "cpu": "x86_64", + "family": "x86_64", + "endian": "little", + "system": "linux", + }, + "build": { + "cpu": "x86_64", + "family": "x86_64", + "endian": "little", + "system": "linux", + }, + "cross-compiled": bool("False".lower().replace("false", "")), + }, + "Build Dependencies": { + "blas": { + "name": "scipy-openblas", + "found": bool("True".lower().replace("false", "")), + "version": "0.3.31.dev", + "detection method": "pkgconfig", + "include directory": r"/opt/_internal/cpython-3.13.8/lib/python3.13/site-packages/scipy_openblas64/include", + "lib directory": r"/opt/_internal/cpython-3.13.8/lib/python3.13/site-packages/scipy_openblas64/lib", + "openblas configuration": r"OpenBLAS 0.3.31.dev USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=64", + "pc file directory": r"/project/.openblas", + }, + "lapack": { + "name": "scipy-openblas", + "found": bool("True".lower().replace("false", "")), + "version": "0.3.31.dev", + "detection method": "pkgconfig", + "include directory": r"/opt/_internal/cpython-3.13.8/lib/python3.13/site-packages/scipy_openblas64/include", + "lib directory": r"/opt/_internal/cpython-3.13.8/lib/python3.13/site-packages/scipy_openblas64/lib", + "openblas configuration": r"OpenBLAS 0.3.31.dev USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell MAX_THREADS=64", + "pc file directory": r"/project/.openblas", + }, + }, + "Python Information": { + "path": r"/tmp/build-env-k9r05nns/bin/python", + "version": "3.13", + }, + "SIMD Extensions": { + "baseline": __cpu_baseline__, + "found": [ + feature for feature in __cpu_dispatch__ if __cpu_features__[feature] + ], + "not found": [ + feature for feature in __cpu_dispatch__ if not __cpu_features__[feature] + ], + }, + } +) + + +def _check_pyyaml(): + import yaml + + return yaml + + +def show(mode=DisplayModes.stdout.value): + """ + Show libraries and system information on which NumPy was built + and is being used + + Parameters + ---------- + mode : {`'stdout'`, `'dicts'`}, optional. + Indicates how to display the config information. + `'stdout'` prints to console, `'dicts'` returns a dictionary + of the configuration. + + Returns + ------- + out : {`dict`, `None`} + If mode is `'dicts'`, a dict is returned, else None + + See Also + -------- + get_include : Returns the directory containing NumPy C + header files. + + Notes + ----- + 1. The `'stdout'` mode will give more readable + output if ``pyyaml`` is installed + + """ + if mode == DisplayModes.stdout.value: + try: # Non-standard library, check import + yaml = _check_pyyaml() + + print(yaml.dump(CONFIG)) + except ModuleNotFoundError: + import warnings + import json + + warnings.warn("Install `pyyaml` for better output", stacklevel=1) + print(json.dumps(CONFIG, indent=2)) + elif mode == DisplayModes.dicts.value: + return CONFIG + else: + raise AttributeError( + f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}" + ) + + +def show_config(mode=DisplayModes.stdout.value): + return show(mode) + + +show_config.__doc__ = show.__doc__ +show_config.__module__ = "numpy" diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/__config__.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/__config__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..21e8b01fdd96dcb5044758d1fa0a14839c5d1e3a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/__config__.pyi @@ -0,0 +1,108 @@ +from enum import Enum +from types import ModuleType +from typing import ( + Final, + Literal as L, + NotRequired, + TypedDict, + overload, + type_check_only, +) + +_CompilerConfigDictValue = TypedDict( + "_CompilerConfigDictValue", + { + "name": str, + "linker": str, + "version": str, + "commands": str, + "args": str, + "linker args": str, + }, +) +_CompilerConfigDict = TypedDict( + "_CompilerConfigDict", + { + "c": _CompilerConfigDictValue, + "cython": _CompilerConfigDictValue, + "c++": _CompilerConfigDictValue, + }, +) +_MachineInformationDict = TypedDict( + "_MachineInformationDict", + { + "host": _MachineInformationDictValue, + "build": _MachineInformationDictValue, + "cross-compiled": NotRequired[L[True]], + }, +) + +@type_check_only +class _MachineInformationDictValue(TypedDict): + cpu: str + family: str + endian: L["little", "big"] + system: str + +_BuildDependenciesDictValue = TypedDict( + "_BuildDependenciesDictValue", + { + "name": str, + "found": NotRequired[L[True]], + "version": str, + "include directory": str, + "lib directory": str, + "openblas configuration": str, + "pc file directory": str, + }, +) + +class _BuildDependenciesDict(TypedDict): + blas: _BuildDependenciesDictValue + lapack: _BuildDependenciesDictValue + +class _PythonInformationDict(TypedDict): + path: str + version: str + +_SIMDExtensionsDict = TypedDict( + "_SIMDExtensionsDict", + { + "baseline": list[str], + "found": list[str], + "not found": list[str], + }, +) + +_ConfigDict = TypedDict( + "_ConfigDict", + { + "Compilers": _CompilerConfigDict, + "Machine Information": _MachineInformationDict, + "Build Dependencies": _BuildDependenciesDict, + "Python Information": _PythonInformationDict, + "SIMD Extensions": _SIMDExtensionsDict, + }, +) + +### + +__all__ = ["show_config"] + +CONFIG: Final[_ConfigDict] = ... + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + +def _check_pyyaml() -> ModuleType: ... + +@overload +def show(mode: L["stdout"] = "stdout") -> None: ... +@overload +def show(mode: L["dicts"]) -> _ConfigDict: ... + +@overload +def show_config(mode: L["stdout"] = "stdout") -> None: ... +@overload +def show_config(mode: L["dicts"]) -> _ConfigDict: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.cython-30.pxd b/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.cython-30.pxd new file mode 100644 index 0000000000000000000000000000000000000000..c71898626070b23f1ce6bdc029fbf8082b3d913c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.cython-30.pxd @@ -0,0 +1,1242 @@ +# NumPy static imports for Cython >= 3.0 +# +# If any of the PyArray_* functions are called, import_array must be +# called first. This is done automatically by Cython 3.0+ if a call +# is not detected inside of the module. +# +# Author: Dag Sverre Seljebotn +# + +from cpython.ref cimport Py_INCREF +from cpython.object cimport PyObject, PyTypeObject, PyObject_TypeCheck +cimport libc.stdio as stdio + + +cdef extern from *: + # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython. + # See https://github.com/cython/cython/issues/3573 + """ + /* Using NumPy API declarations from "numpy/__init__.cython-30.pxd" */ + """ + + +cdef extern from "numpy/arrayobject.h": + # It would be nice to use size_t and ssize_t, but ssize_t has special + # implicit conversion rules, so just use "long". + # Note: The actual type only matters for Cython promotion, so long + # is closer than int, but could lead to incorrect promotion. + # (Not to worrying, and always the status-quo.) + ctypedef signed long npy_intp + ctypedef unsigned long npy_uintp + + ctypedef unsigned char npy_bool + + ctypedef signed char npy_byte + ctypedef signed short npy_short + ctypedef signed int npy_int + ctypedef signed long npy_long + ctypedef signed long long npy_longlong + + ctypedef unsigned char npy_ubyte + ctypedef unsigned short npy_ushort + ctypedef unsigned int npy_uint + ctypedef unsigned long npy_ulong + ctypedef unsigned long long npy_ulonglong + + ctypedef float npy_float + ctypedef double npy_double + ctypedef long double npy_longdouble + + ctypedef signed char npy_int8 + ctypedef signed short npy_int16 + ctypedef signed int npy_int32 + ctypedef signed long long npy_int64 + + ctypedef unsigned char npy_uint8 + ctypedef unsigned short npy_uint16 + ctypedef unsigned int npy_uint32 + ctypedef unsigned long long npy_uint64 + + ctypedef float npy_float32 + ctypedef double npy_float64 + ctypedef long double npy_float80 + ctypedef long double npy_float96 + ctypedef long double npy_float128 + + ctypedef struct npy_cfloat: + pass + + ctypedef struct npy_cdouble: + pass + + ctypedef struct npy_clongdouble: + pass + + ctypedef struct npy_complex64: + pass + + ctypedef struct npy_complex128: + pass + + ctypedef struct npy_complex160: + pass + + ctypedef struct npy_complex192: + pass + + ctypedef struct npy_complex256: + pass + + ctypedef struct PyArray_Dims: + npy_intp *ptr + int len + + + cdef enum NPY_TYPES: + NPY_BOOL + NPY_BYTE + NPY_UBYTE + NPY_SHORT + NPY_USHORT + NPY_INT + NPY_UINT + NPY_LONG + NPY_ULONG + NPY_LONGLONG + NPY_ULONGLONG + NPY_FLOAT + NPY_DOUBLE + NPY_LONGDOUBLE + NPY_CFLOAT + NPY_CDOUBLE + NPY_CLONGDOUBLE + NPY_OBJECT + NPY_STRING + NPY_UNICODE + NPY_VSTRING + NPY_VOID + NPY_DATETIME + NPY_TIMEDELTA + NPY_NTYPES_LEGACY + NPY_NOTYPE + + NPY_INT8 + NPY_INT16 + NPY_INT32 + NPY_INT64 + NPY_UINT8 + NPY_UINT16 + NPY_UINT32 + NPY_UINT64 + NPY_FLOAT16 + NPY_FLOAT32 + NPY_FLOAT64 + NPY_FLOAT80 + NPY_FLOAT96 + NPY_FLOAT128 + NPY_COMPLEX64 + NPY_COMPLEX128 + NPY_COMPLEX160 + NPY_COMPLEX192 + NPY_COMPLEX256 + + NPY_INTP + NPY_UINTP + NPY_DEFAULT_INT # Not a compile time constant (normally)! + + ctypedef enum NPY_ORDER: + NPY_ANYORDER + NPY_CORDER + NPY_FORTRANORDER + NPY_KEEPORDER + + ctypedef enum NPY_CASTING: + NPY_NO_CASTING + NPY_EQUIV_CASTING + NPY_SAFE_CASTING + NPY_SAME_KIND_CASTING + NPY_UNSAFE_CASTING + NPY_SAME_VALUE_CASTING + + ctypedef enum NPY_CLIPMODE: + NPY_CLIP + NPY_WRAP + NPY_RAISE + + ctypedef enum NPY_SCALARKIND: + NPY_NOSCALAR, + NPY_BOOL_SCALAR, + NPY_INTPOS_SCALAR, + NPY_INTNEG_SCALAR, + NPY_FLOAT_SCALAR, + NPY_COMPLEX_SCALAR, + NPY_OBJECT_SCALAR + + ctypedef enum NPY_SORTKIND: + NPY_QUICKSORT + NPY_HEAPSORT + NPY_MERGESORT + + ctypedef enum NPY_SEARCHSIDE: + NPY_SEARCHLEFT + NPY_SEARCHRIGHT + + enum: + NPY_ARRAY_C_CONTIGUOUS + NPY_ARRAY_F_CONTIGUOUS + NPY_ARRAY_OWNDATA + NPY_ARRAY_FORCECAST + NPY_ARRAY_ENSURECOPY + NPY_ARRAY_ENSUREARRAY + NPY_ARRAY_ELEMENTSTRIDES + NPY_ARRAY_ALIGNED + NPY_ARRAY_NOTSWAPPED + NPY_ARRAY_WRITEABLE + NPY_ARRAY_WRITEBACKIFCOPY + + NPY_ARRAY_BEHAVED + NPY_ARRAY_BEHAVED_NS + NPY_ARRAY_CARRAY + NPY_ARRAY_CARRAY_RO + NPY_ARRAY_FARRAY + NPY_ARRAY_FARRAY_RO + NPY_ARRAY_DEFAULT + + NPY_ARRAY_IN_ARRAY + NPY_ARRAY_OUT_ARRAY + NPY_ARRAY_INOUT_ARRAY + NPY_ARRAY_IN_FARRAY + NPY_ARRAY_OUT_FARRAY + NPY_ARRAY_INOUT_FARRAY + + NPY_ARRAY_UPDATE_ALL + + cdef enum: + NPY_MAXDIMS # 64 on NumPy 2.x and 32 on NumPy 1.x + NPY_RAVEL_AXIS # Used for functions like PyArray_Mean + + ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *) + + ctypedef struct PyArray_ArrayDescr: + # shape is a tuple, but Cython doesn't support "tuple shape" + # inside a non-PyObject declaration, so we have to declare it + # as just a PyObject*. + PyObject* shape + + ctypedef struct PyArray_Descr: + pass + + ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]: + # Use PyDataType_* macros when possible, however there are no macros + # for accessing some of the fields, so some are defined. + cdef PyTypeObject* typeobj + cdef char kind + cdef char type + # Numpy sometimes mutates this without warning (e.g. it'll + # sometimes change "|" to "<" in shared dtype objects on + # little-endian machines). If this matters to you, use + # PyArray_IsNativeByteOrder(dtype.byteorder) instead of + # directly accessing this field. + cdef char byteorder + cdef int type_num + + @property + cdef inline npy_intp itemsize(self) noexcept nogil: + return PyDataType_ELSIZE(self) + + @property + cdef inline npy_intp alignment(self) noexcept nogil: + return PyDataType_ALIGNMENT(self) + + # Use fields/names with care as they may be NULL. You must check + # for this using PyDataType_HASFIELDS. + @property + cdef inline object fields(self): + return PyDataType_FIELDS(self) + + @property + cdef inline tuple names(self): + return PyDataType_NAMES(self) + + # Use PyDataType_HASSUBARRAY to test whether this field is + # valid (the pointer can be NULL). Most users should access + # this field via the inline helper method PyDataType_SHAPE. + @property + cdef inline PyArray_ArrayDescr* subarray(self) noexcept nogil: + return PyDataType_SUBARRAY(self) + + @property + cdef inline npy_uint64 flags(self) noexcept nogil: + """The data types flags.""" + return PyDataType_FLAGS(self) + + + ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]: + # Use through macros + pass + + ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]: + + @property + cdef inline int numiter(self) noexcept nogil: + """The number of arrays that need to be broadcast to the same shape.""" + return PyArray_MultiIter_NUMITER(self) + + @property + cdef inline npy_intp size(self) noexcept nogil: + """The total broadcasted size.""" + return PyArray_MultiIter_SIZE(self) + + @property + cdef inline npy_intp index(self) noexcept nogil: + """The current (1-d) index into the broadcasted result.""" + return PyArray_MultiIter_INDEX(self) + + @property + cdef inline int nd(self) noexcept nogil: + """The number of dimensions in the broadcasted result.""" + return PyArray_MultiIter_NDIM(self) + + @property + cdef inline npy_intp* dimensions(self) noexcept nogil: + """The shape of the broadcasted result.""" + return PyArray_MultiIter_DIMS(self) + + @property + cdef inline void** iters(self) noexcept nogil: + """An array of iterator objects that holds the iterators for the arrays to be broadcast together. + On return, the iterators are adjusted for broadcasting.""" + return PyArray_MultiIter_ITERS(self) + + + ctypedef struct PyArrayObject: + # For use in situations where ndarray can't replace PyArrayObject*, + # like PyArrayObject**. + pass + + ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]: + cdef __cythonbufferdefaults__ = {"mode": "strided"} + + # NOTE: no field declarations since direct access is deprecated since NumPy 1.7 + # Instead, we use properties that map to the corresponding C-API functions. + + @property + cdef inline PyObject* base(self) noexcept nogil: + """Returns a borrowed reference to the object owning the data/memory. + """ + return PyArray_BASE(self) + + @property + cdef inline dtype descr(self): + """Returns an owned reference to the dtype of the array. + """ + return PyArray_DESCR(self) + + @property + cdef inline int ndim(self) noexcept nogil: + """Returns the number of dimensions in the array. + """ + return PyArray_NDIM(self) + + @property + cdef inline npy_intp *shape(self) noexcept nogil: + """Returns a pointer to the dimensions/shape of the array. + The number of elements matches the number of dimensions of the array (ndim). + Can return NULL for 0-dimensional arrays. + """ + return PyArray_DIMS(self) + + @property + cdef inline npy_intp *strides(self) noexcept nogil: + """Returns a pointer to the strides of the array. + The number of elements matches the number of dimensions of the array (ndim). + """ + return PyArray_STRIDES(self) + + @property + cdef inline npy_intp size(self) noexcept nogil: + """Returns the total size (in number of elements) of the array. + """ + return PyArray_SIZE(self) + + @property + cdef inline char* data(self) noexcept nogil: + """The pointer to the data buffer as a char*. + This is provided for legacy reasons to avoid direct struct field access. + For new code that needs this access, you probably want to cast the result + of `PyArray_DATA()` instead, which returns a 'void*'. + """ + return PyArray_BYTES(self) + + + int _import_array() except -1 + # A second definition so _import_array isn't marked as used when we use it here. + # Do not use - subject to change any time. + int __pyx_import_array "_import_array"() except -1 + + # + # Macros from ndarrayobject.h + # + bint PyArray_CHKFLAGS(ndarray m, int flags) nogil + bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil + bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil + bint PyArray_ISCONTIGUOUS(ndarray m) nogil + bint PyArray_ISWRITEABLE(ndarray m) nogil + bint PyArray_ISALIGNED(ndarray m) nogil + + int PyArray_NDIM(ndarray) nogil + bint PyArray_ISONESEGMENT(ndarray) nogil + bint PyArray_ISFORTRAN(ndarray) nogil + int PyArray_FORTRANIF(ndarray) nogil + + void* PyArray_DATA(ndarray) nogil + char* PyArray_BYTES(ndarray) nogil + + npy_intp* PyArray_DIMS(ndarray) nogil + npy_intp* PyArray_STRIDES(ndarray) nogil + npy_intp PyArray_DIM(ndarray, size_t) nogil + npy_intp PyArray_STRIDE(ndarray, size_t) nogil + + PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference! + PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype! + PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr. + int PyArray_FLAGS(ndarray) nogil + void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7 + void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7 + npy_intp PyArray_ITEMSIZE(ndarray) nogil + int PyArray_TYPE(ndarray arr) nogil + + object PyArray_GETITEM(ndarray arr, void *itemptr) + int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1 + + bint PyTypeNum_ISBOOL(int) nogil + bint PyTypeNum_ISUNSIGNED(int) nogil + bint PyTypeNum_ISSIGNED(int) nogil + bint PyTypeNum_ISINTEGER(int) nogil + bint PyTypeNum_ISFLOAT(int) nogil + bint PyTypeNum_ISNUMBER(int) nogil + bint PyTypeNum_ISSTRING(int) nogil + bint PyTypeNum_ISCOMPLEX(int) nogil + bint PyTypeNum_ISFLEXIBLE(int) nogil + bint PyTypeNum_ISUSERDEF(int) nogil + bint PyTypeNum_ISEXTENDED(int) nogil + bint PyTypeNum_ISOBJECT(int) nogil + + npy_intp PyDataType_ELSIZE(dtype) nogil + npy_intp PyDataType_ALIGNMENT(dtype) nogil + PyObject* PyDataType_METADATA(dtype) nogil + PyArray_ArrayDescr* PyDataType_SUBARRAY(dtype) nogil + PyObject* PyDataType_NAMES(dtype) nogil + PyObject* PyDataType_FIELDS(dtype) nogil + + bint PyDataType_ISBOOL(dtype) nogil + bint PyDataType_ISUNSIGNED(dtype) nogil + bint PyDataType_ISSIGNED(dtype) nogil + bint PyDataType_ISINTEGER(dtype) nogil + bint PyDataType_ISFLOAT(dtype) nogil + bint PyDataType_ISNUMBER(dtype) nogil + bint PyDataType_ISSTRING(dtype) nogil + bint PyDataType_ISCOMPLEX(dtype) nogil + bint PyDataType_ISFLEXIBLE(dtype) nogil + bint PyDataType_ISUSERDEF(dtype) nogil + bint PyDataType_ISEXTENDED(dtype) nogil + bint PyDataType_ISOBJECT(dtype) nogil + bint PyDataType_HASFIELDS(dtype) nogil + bint PyDataType_HASSUBARRAY(dtype) nogil + npy_uint64 PyDataType_FLAGS(dtype) nogil + + bint PyArray_ISBOOL(ndarray) nogil + bint PyArray_ISUNSIGNED(ndarray) nogil + bint PyArray_ISSIGNED(ndarray) nogil + bint PyArray_ISINTEGER(ndarray) nogil + bint PyArray_ISFLOAT(ndarray) nogil + bint PyArray_ISNUMBER(ndarray) nogil + bint PyArray_ISSTRING(ndarray) nogil + bint PyArray_ISCOMPLEX(ndarray) nogil + bint PyArray_ISFLEXIBLE(ndarray) nogil + bint PyArray_ISUSERDEF(ndarray) nogil + bint PyArray_ISEXTENDED(ndarray) nogil + bint PyArray_ISOBJECT(ndarray) nogil + bint PyArray_HASFIELDS(ndarray) nogil + + bint PyArray_ISVARIABLE(ndarray) nogil + + bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil + bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder + bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder + bint PyArray_ISNOTSWAPPED(ndarray) nogil + bint PyArray_ISBYTESWAPPED(ndarray) nogil + + bint PyArray_FLAGSWAP(ndarray, int) nogil + + bint PyArray_ISCARRAY(ndarray) nogil + bint PyArray_ISCARRAY_RO(ndarray) nogil + bint PyArray_ISFARRAY(ndarray) nogil + bint PyArray_ISFARRAY_RO(ndarray) nogil + bint PyArray_ISBEHAVED(ndarray) nogil + bint PyArray_ISBEHAVED_RO(ndarray) nogil + + + bint PyDataType_ISNOTSWAPPED(dtype) nogil + bint PyDataType_ISBYTESWAPPED(dtype) nogil + + bint PyArray_DescrCheck(object) + + bint PyArray_Check(object) + bint PyArray_CheckExact(object) + + # Cannot be supported due to out arg: + # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&) + # bint PyArray_HasArrayInterface(op, out) + + + bint PyArray_IsZeroDim(object) + # Cannot be supported due to ## ## in macro: + # bint PyArray_IsScalar(object, verbatim work) + bint PyArray_CheckScalar(object) + bint PyArray_IsPythonNumber(object) + bint PyArray_IsPythonScalar(object) + bint PyArray_IsAnyScalar(object) + bint PyArray_CheckAnyScalar(object) + + ndarray PyArray_GETCONTIGUOUS(ndarray) + bint PyArray_SAMESHAPE(ndarray, ndarray) nogil + npy_intp PyArray_SIZE(ndarray) nogil + npy_intp PyArray_NBYTES(ndarray) nogil + + object PyArray_FROM_O(object) + object PyArray_FROM_OF(object m, int flags) + object PyArray_FROM_OT(object m, int type) + object PyArray_FROM_OTF(object m, int type, int flags) + object PyArray_FROMANY(object m, int type, int min, int max, int flags) + object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran) + object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran) + void PyArray_FILLWBYTE(ndarray, int val) + object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth) + unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2) + bint PyArray_EquivByteorders(int b1, int b2) nogil + object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum) + object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data) + #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr) + object PyArray_ToScalar(void* data, ndarray arr) + + void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil + void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil + void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil + void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil + + # Cannot be supported due to out arg + # void PyArray_DESCR_REPLACE(descr) + + + object PyArray_Copy(ndarray) + object PyArray_FromObject(object op, int type, int min_depth, int max_depth) + object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth) + object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth) + + object PyArray_Cast(ndarray mp, int type_num) + object PyArray_Take(ndarray ap, object items, int axis) + object PyArray_Put(ndarray ap, object items, object values) + + void PyArray_ITER_RESET(flatiter it) nogil + void PyArray_ITER_NEXT(flatiter it) nogil + void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil + void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil + void* PyArray_ITER_DATA(flatiter it) nogil + bint PyArray_ITER_NOTDONE(flatiter it) nogil + + void PyArray_MultiIter_RESET(broadcast multi) nogil + void PyArray_MultiIter_NEXT(broadcast multi) nogil + void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil + void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil + void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil + void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil + bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil + npy_intp PyArray_MultiIter_SIZE(broadcast multi) nogil + int PyArray_MultiIter_NDIM(broadcast multi) nogil + npy_intp PyArray_MultiIter_INDEX(broadcast multi) nogil + int PyArray_MultiIter_NUMITER(broadcast multi) nogil + npy_intp* PyArray_MultiIter_DIMS(broadcast multi) nogil + void** PyArray_MultiIter_ITERS(broadcast multi) nogil + + # Functions from __multiarray_api.h + + # Functions taking dtype and returning object/ndarray are disabled + # for now as they steal dtype references. I'm conservative and disable + # more than is probably needed until it can be checked further. + int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF... + int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF... + dtype PyArray_DescrFromType (int) + object PyArray_TypeObjectFromType (int) + char * PyArray_Zero (ndarray) + char * PyArray_One (ndarray) + #object PyArray_CastToType (ndarray, dtype, int) + int PyArray_CanCastSafely (int, int) # writes errors + npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors + int PyArray_ObjectType (object, int) except 0 + dtype PyArray_DescrFromObject (object, dtype) + #ndarray* PyArray_ConvertToCommonType (object, int *) + dtype PyArray_DescrFromScalar (object) + dtype PyArray_DescrFromTypeObject (object) + npy_intp PyArray_Size (object) + #object PyArray_Scalar (void *, dtype, object) + #object PyArray_FromScalar (object, dtype) + void PyArray_ScalarAsCtype (object, void *) + #int PyArray_CastScalarToCtype (object, void *, dtype) + #int PyArray_CastScalarDirect (object, dtype, void *, int) + #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int) + #object PyArray_FromAny (object, dtype, int, int, int, object) + object PyArray_EnsureArray (object) + object PyArray_EnsureAnyArray (object) + #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *) + #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *) + #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp) + #object PyArray_FromIter (object, dtype, npy_intp) + object PyArray_Return (ndarray) + #object PyArray_GetField (ndarray, dtype, int) + #int PyArray_SetField (ndarray, dtype, int, object) except -1 + object PyArray_Byteswap (ndarray, npy_bool) + object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER) + int PyArray_CopyInto (ndarray, ndarray) except -1 + int PyArray_CopyAnyInto (ndarray, ndarray) except -1 + int PyArray_CopyObject (ndarray, object) except -1 + object PyArray_NewCopy (ndarray, NPY_ORDER) + object PyArray_ToList (ndarray) + object PyArray_ToString (ndarray, NPY_ORDER) + int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1 + int PyArray_Dump (object, object, int) except -1 + object PyArray_Dumps (object, int) + int PyArray_ValidType (int) # Cannot error + void PyArray_UpdateFlags (ndarray, int) + object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object) + #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object) + #dtype PyArray_DescrNew (dtype) + dtype PyArray_DescrNewFromType (int) + double PyArray_GetPriority (object, double) # clears errors as of 1.25 + object PyArray_IterNew (object) + object PyArray_MultiIterNew (int, ...) + + int PyArray_PyIntAsInt (object) except? -1 + npy_intp PyArray_PyIntAsIntp (object) + int PyArray_Broadcast (broadcast) except -1 + int PyArray_FillWithScalar (ndarray, object) except -1 + npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *) + dtype PyArray_DescrNewByteorder (dtype, char) + object PyArray_IterAllButAxis (object, int *) + #object PyArray_CheckFromAny (object, dtype, int, int, int, object) + #object PyArray_FromArray (ndarray, dtype, int) + object PyArray_FromInterface (object) + object PyArray_FromStructInterface (object) + #object PyArray_FromArrayAttr (object, dtype, object) + #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*) + int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND) + npy_bool PyArray_CanCastScalar (type, type) + int PyArray_RemoveSmallest (broadcast) except -1 + int PyArray_ElementStrides (object) + void PyArray_Item_INCREF (char *, dtype) except * + void PyArray_Item_XDECREF (char *, dtype) except * + object PyArray_Transpose (ndarray, PyArray_Dims *) + object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE) + object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE) + object PyArray_PutMask (ndarray, object, object) + object PyArray_Repeat (ndarray, object, int) + object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE) + int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1 + object PyArray_ArgSort (ndarray, int, NPY_SORTKIND) + object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *) + object PyArray_ArgMax (ndarray, int, ndarray) + object PyArray_ArgMin (ndarray, int, ndarray) + object PyArray_Reshape (ndarray, object) + object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER) + object PyArray_Squeeze (ndarray) + #object PyArray_View (ndarray, dtype, type) + object PyArray_SwapAxes (ndarray, int, int) + object PyArray_Max (ndarray, int, ndarray) + object PyArray_Min (ndarray, int, ndarray) + object PyArray_Ptp (ndarray, int, ndarray) + object PyArray_Mean (ndarray, int, int, ndarray) + object PyArray_Trace (ndarray, int, int, int, int, ndarray) + object PyArray_Diagonal (ndarray, int, int, int) + object PyArray_Clip (ndarray, object, object, ndarray) + object PyArray_Conjugate (ndarray, ndarray) + object PyArray_Nonzero (ndarray) + object PyArray_Std (ndarray, int, int, ndarray, int) + object PyArray_Sum (ndarray, int, int, ndarray) + object PyArray_CumSum (ndarray, int, int, ndarray) + object PyArray_Prod (ndarray, int, int, ndarray) + object PyArray_CumProd (ndarray, int, int, ndarray) + object PyArray_All (ndarray, int, ndarray) + object PyArray_Any (ndarray, int, ndarray) + object PyArray_Compress (ndarray, object, int, ndarray) + object PyArray_Flatten (ndarray, NPY_ORDER) + object PyArray_Ravel (ndarray, NPY_ORDER) + npy_intp PyArray_MultiplyList (npy_intp *, int) + int PyArray_MultiplyIntList (int *, int) + void * PyArray_GetPtr (ndarray, npy_intp*) + int PyArray_CompareLists (npy_intp *, npy_intp *, int) + #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype) + int PyArray_Free (object, void *) + #int PyArray_Converter (object, object*) + int PyArray_IntpFromSequence (object, npy_intp *, int) except -1 + object PyArray_Concatenate (object, int) + object PyArray_InnerProduct (object, object) + object PyArray_MatrixProduct (object, object) + object PyArray_Correlate (object, object, int) + #int PyArray_DescrConverter (object, dtype*) except 0 + #int PyArray_DescrConverter2 (object, dtype*) except 0 + int PyArray_IntpConverter (object, PyArray_Dims *) except 0 + #int PyArray_BufferConverter (object, chunk) except 0 + int PyArray_AxisConverter (object, int *) except 0 + int PyArray_BoolConverter (object, npy_bool *) except 0 + int PyArray_ByteorderConverter (object, char *) except 0 + int PyArray_OrderConverter (object, NPY_ORDER *) except 0 + unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors + #object PyArray_Zeros (int, npy_intp *, dtype, int) + #object PyArray_Empty (int, npy_intp *, dtype, int) + object PyArray_Where (object, object, object) + object PyArray_Arange (double, double, double, int) + #object PyArray_ArangeObj (object, object, object, dtype) + int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0 + object PyArray_LexSort (object, int) + object PyArray_Round (ndarray, int, ndarray) + unsigned char PyArray_EquivTypenums (int, int) + int PyArray_RegisterDataType (dtype) except -1 + int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1 + int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1 + #void PyArray_InitArrFuncs (PyArray_ArrFuncs *) + object PyArray_IntTupleFromIntp (int, npy_intp *) + int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0 + #int PyArray_OutputConverter (object, ndarray*) except 0 + object PyArray_BroadcastToShape (object, npy_intp *, int) + #int PyArray_DescrAlignConverter (object, dtype*) except 0 + #int PyArray_DescrAlignConverter2 (object, dtype*) except 0 + int PyArray_SearchsideConverter (object, void *) except 0 + object PyArray_CheckAxis (ndarray, int *, int) + npy_intp PyArray_OverflowMultiplyList (npy_intp *, int) + int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead. + + # The memory handler functions require the NumPy 1.22 API + # and may require defining NPY_TARGET_VERSION + ctypedef struct PyDataMemAllocator: + void *ctx + void* (*malloc) (void *ctx, size_t size) + void* (*calloc) (void *ctx, size_t nelem, size_t elsize) + void* (*realloc) (void *ctx, void *ptr, size_t new_size) + void (*free) (void *ctx, void *ptr, size_t size) + + ctypedef struct PyDataMem_Handler: + char* name + npy_uint8 version + PyDataMemAllocator allocator + + object PyDataMem_SetHandler(object handler) + object PyDataMem_GetHandler() + + # additional datetime related functions are defined below + + +# Typedefs that matches the runtime dtype objects in +# the numpy module. + +# The ones that are commented out needs an IFDEF function +# in Cython to enable them only on the right systems. + +ctypedef npy_int8 int8_t +ctypedef npy_int16 int16_t +ctypedef npy_int32 int32_t +ctypedef npy_int64 int64_t + +ctypedef npy_uint8 uint8_t +ctypedef npy_uint16 uint16_t +ctypedef npy_uint32 uint32_t +ctypedef npy_uint64 uint64_t + +ctypedef npy_float32 float32_t +ctypedef npy_float64 float64_t +#ctypedef npy_float80 float80_t +#ctypedef npy_float128 float128_t + +ctypedef float complex complex64_t +ctypedef double complex complex128_t + +ctypedef npy_longlong longlong_t +ctypedef npy_ulonglong ulonglong_t + +ctypedef npy_intp intp_t +ctypedef npy_uintp uintp_t + +ctypedef npy_double float_t +ctypedef npy_double double_t +ctypedef npy_longdouble longdouble_t + +ctypedef float complex cfloat_t +ctypedef double complex cdouble_t +ctypedef double complex complex_t +ctypedef long double complex clongdouble_t + +cdef inline object PyArray_MultiIterNew1(a): + return PyArray_MultiIterNew(1, a) + +cdef inline object PyArray_MultiIterNew2(a, b): + return PyArray_MultiIterNew(2, a, b) + +cdef inline object PyArray_MultiIterNew3(a, b, c): + return PyArray_MultiIterNew(3, a, b, c) + +cdef inline object PyArray_MultiIterNew4(a, b, c, d): + return PyArray_MultiIterNew(4, a, b, c, d) + +cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + return PyArray_MultiIterNew(5, a, b, c, d, e) + +cdef inline tuple PyDataType_SHAPE(dtype d): + if PyDataType_HASSUBARRAY(d): + return d.subarray.shape + else: + return () + + +cdef extern from "numpy/ndarrayobject.h": + PyTypeObject PyTimedeltaArrType_Type + PyTypeObject PyDatetimeArrType_Type + ctypedef int64_t npy_timedelta + ctypedef int64_t npy_datetime + +cdef extern from "numpy/ndarraytypes.h": + ctypedef struct PyArray_DatetimeMetaData: + NPY_DATETIMEUNIT base + int64_t num + + ctypedef struct npy_datetimestruct: + int64_t year + int32_t month, day, hour, min, sec, us, ps, as + + # Iterator API added in v1.6 + # + # These don't match the definition in the C API because Cython can't wrap + # function pointers that return functions. + # https://github.com/cython/cython/issues/6720 + ctypedef int (*NpyIter_IterNextFunc "NpyIter_IterNextFunc *")(NpyIter* it) noexcept nogil + ctypedef void (*NpyIter_GetMultiIndexFunc "NpyIter_GetMultiIndexFunc *")(NpyIter* it, npy_intp* outcoords) noexcept nogil + + +cdef extern from "numpy/arrayscalars.h": + + # abstract types + ctypedef class numpy.generic [object PyObject]: + pass + ctypedef class numpy.number [object PyObject]: + pass + ctypedef class numpy.integer [object PyObject]: + pass + ctypedef class numpy.signedinteger [object PyObject]: + pass + ctypedef class numpy.unsignedinteger [object PyObject]: + pass + ctypedef class numpy.inexact [object PyObject]: + pass + ctypedef class numpy.floating [object PyObject]: + pass + ctypedef class numpy.complexfloating [object PyObject]: + pass + ctypedef class numpy.flexible [object PyObject]: + pass + ctypedef class numpy.character [object PyObject]: + pass + + ctypedef struct PyDatetimeScalarObject: + # PyObject_HEAD + npy_datetime obval + PyArray_DatetimeMetaData obmeta + + ctypedef struct PyTimedeltaScalarObject: + # PyObject_HEAD + npy_timedelta obval + PyArray_DatetimeMetaData obmeta + + ctypedef enum NPY_DATETIMEUNIT: + NPY_FR_Y + NPY_FR_M + NPY_FR_W + NPY_FR_D + NPY_FR_B + NPY_FR_h + NPY_FR_m + NPY_FR_s + NPY_FR_ms + NPY_FR_us + NPY_FR_ns + NPY_FR_ps + NPY_FR_fs + NPY_FR_as + NPY_FR_GENERIC + + +cdef extern from "numpy/arrayobject.h": + # These are part of the C-API defined in `__multiarray_api.h` + + # NumPy internal definitions in datetime_strings.c: + int get_datetime_iso_8601_strlen "NpyDatetime_GetDatetimeISO8601StrLen" ( + int local, NPY_DATETIMEUNIT base) + int make_iso_8601_datetime "NpyDatetime_MakeISO8601Datetime" ( + npy_datetimestruct *dts, char *outstr, npy_intp outlen, + int local, int utc, NPY_DATETIMEUNIT base, int tzoffset, + NPY_CASTING casting) except -1 + + # NumPy internal definition in datetime.c: + # May return 1 to indicate that object does not appear to be a datetime + # (returns 0 on success). + int convert_pydatetime_to_datetimestruct "NpyDatetime_ConvertPyDateTimeToDatetimeStruct" ( + PyObject *obj, npy_datetimestruct *out, + NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) except -1 + int convert_datetime64_to_datetimestruct "NpyDatetime_ConvertDatetime64ToDatetimeStruct" ( + PyArray_DatetimeMetaData *meta, npy_datetime dt, + npy_datetimestruct *out) except -1 + int convert_datetimestruct_to_datetime64 "NpyDatetime_ConvertDatetimeStructToDatetime64"( + PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, + npy_datetime *out) except -1 + + +# +# ufunc API +# + +cdef extern from "numpy/ufuncobject.h": + + ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *) + + ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]: + cdef: + int nin, nout, nargs + int identity + PyUFuncGenericFunction *functions + void **data + int ntypes + int check_return + char *name + char *types + char *doc + void *ptr + PyObject *obj + PyObject *userloops + + cdef enum: + PyUFunc_Zero + PyUFunc_One + PyUFunc_None + # deprecated + UFUNC_FPE_DIVIDEBYZERO + UFUNC_FPE_OVERFLOW + UFUNC_FPE_UNDERFLOW + UFUNC_FPE_INVALID + # use these instead + NPY_FPE_DIVIDEBYZERO + NPY_FPE_OVERFLOW + NPY_FPE_UNDERFLOW + NPY_FPE_INVALID + + + object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *, + void **, char *, int, int, int, int, char *, char *, int) + int PyUFunc_RegisterLoopForType(ufunc, int, + PyUFuncGenericFunction, int *, void *) except -1 + void PyUFunc_f_f_As_d_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_d_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_f_f \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_g_g \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_F_F_As_D_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_F_F \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_D_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_G_G \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_O_O \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_ff_f_As_dd_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_ff_f \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_dd_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_gg_g \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_FF_F_As_DD_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_DD_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_FF_F \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_GG_G \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_OO_O \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_O_O_method \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_OO_O_method \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_On_Om \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_clearfperr() + int PyUFunc_getfperr() + int PyUFunc_ReplaceLoopBySignature \ + (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *) + object PyUFunc_FromFuncAndDataAndSignature \ + (PyUFuncGenericFunction *, void **, char *, int, int, int, + int, char *, char *, int, char *) + + int _import_umath() except -1 + +cdef inline void set_array_base(ndarray arr, object base) except *: + Py_INCREF(base) # important to do this before stealing the reference below! + PyArray_SetBaseObject(arr, base) + +cdef inline object get_array_base(ndarray arr): + base = PyArray_BASE(arr) + if base is NULL: + return None + return base + +# Versions of the import_* functions which are more suitable for +# Cython code. +cdef inline int import_array() except -1: + try: + __pyx_import_array() + except Exception: + raise ImportError("numpy._core.multiarray failed to import") + +cdef inline int import_umath() except -1: + try: + _import_umath() + except Exception: + raise ImportError("numpy._core.umath failed to import") + +cdef inline int import_ufunc() except -1: + try: + _import_umath() + except Exception: + raise ImportError("numpy._core.umath failed to import") + + +cdef inline bint is_timedelta64_object(object obj) noexcept: + """ + Cython equivalent of `isinstance(obj, np.timedelta64)` + + Parameters + ---------- + obj : object + + Returns + ------- + bool + """ + return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) + + +cdef inline bint is_datetime64_object(object obj) noexcept: + """ + Cython equivalent of `isinstance(obj, np.datetime64)` + + Parameters + ---------- + obj : object + + Returns + ------- + bool + """ + return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) + + +cdef inline npy_datetime get_datetime64_value(object obj) noexcept nogil: + """ + returns the int64 value underlying scalar numpy datetime64 object + + Note that to interpret this as a datetime, the corresponding unit is + also needed. That can be found using `get_datetime64_unit`. + """ + return (obj).obval + + +cdef inline npy_timedelta get_timedelta64_value(object obj) noexcept nogil: + """ + returns the int64 value underlying scalar numpy timedelta64 object + """ + return (obj).obval + + +cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) noexcept nogil: + """ + returns the unit part of the dtype for a numpy datetime64 object. + """ + return (obj).obmeta.base + + +cdef extern from "numpy/arrayobject.h": + + ctypedef struct NpyIter: + pass + + cdef enum: + NPY_FAIL + NPY_SUCCEED + + cdef enum: + # Track an index representing C order + NPY_ITER_C_INDEX + # Track an index representing Fortran order + NPY_ITER_F_INDEX + # Track a multi-index + NPY_ITER_MULTI_INDEX + # User code external to the iterator does the 1-dimensional innermost loop + NPY_ITER_EXTERNAL_LOOP + # Convert all the operands to a common data type + NPY_ITER_COMMON_DTYPE + # Operands may hold references, requiring API access during iteration + NPY_ITER_REFS_OK + # Zero-sized operands should be permitted, iteration checks IterSize for 0 + NPY_ITER_ZEROSIZE_OK + # Permits reductions (size-0 stride with dimension size > 1) + NPY_ITER_REDUCE_OK + # Enables sub-range iteration + NPY_ITER_RANGED + # Enables buffering + NPY_ITER_BUFFERED + # When buffering is enabled, grows the inner loop if possible + NPY_ITER_GROWINNER + # Delay allocation of buffers until first Reset* call + NPY_ITER_DELAY_BUFALLOC + # When NPY_KEEPORDER is specified, disable reversing negative-stride axes + NPY_ITER_DONT_NEGATE_STRIDES + NPY_ITER_COPY_IF_OVERLAP + # The operand will be read from and written to + NPY_ITER_READWRITE + # The operand will only be read from + NPY_ITER_READONLY + # The operand will only be written to + NPY_ITER_WRITEONLY + # The operand's data must be in native byte order + NPY_ITER_NBO + # The operand's data must be aligned + NPY_ITER_ALIGNED + # The operand's data must be contiguous (within the inner loop) + NPY_ITER_CONTIG + # The operand may be copied to satisfy requirements + NPY_ITER_COPY + # The operand may be copied with WRITEBACKIFCOPY to satisfy requirements + NPY_ITER_UPDATEIFCOPY + # Allocate the operand if it is NULL + NPY_ITER_ALLOCATE + # If an operand is allocated, don't use any subtype + NPY_ITER_NO_SUBTYPE + # This is a virtual array slot, operand is NULL but temporary data is there + NPY_ITER_VIRTUAL + # Require that the dimension match the iterator dimensions exactly + NPY_ITER_NO_BROADCAST + # A mask is being used on this array, affects buffer -> array copy + NPY_ITER_WRITEMASKED + # This array is the mask for all WRITEMASKED operands + NPY_ITER_ARRAYMASK + # Assume iterator order data access for COPY_IF_OVERLAP + NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE + + # construction and destruction functions + NpyIter* NpyIter_New(ndarray arr, npy_uint32 flags, NPY_ORDER order, + NPY_CASTING casting, dtype datatype) except NULL + NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags, + NPY_ORDER order, NPY_CASTING casting, npy_uint32* + op_flags, PyArray_Descr** op_dtypes) except NULL + NpyIter* NpyIter_AdvancedNew(npy_intp nop, PyArrayObject** op, + npy_uint32 flags, NPY_ORDER order, + NPY_CASTING casting, npy_uint32* op_flags, + PyArray_Descr** op_dtypes, int oa_ndim, + int** op_axes, const npy_intp* itershape, + npy_intp buffersize) except NULL + NpyIter* NpyIter_Copy(NpyIter* it) except NULL + int NpyIter_RemoveAxis(NpyIter* it, int axis) except NPY_FAIL + int NpyIter_RemoveMultiIndex(NpyIter* it) except NPY_FAIL + int NpyIter_EnableExternalLoop(NpyIter* it) except NPY_FAIL + int NpyIter_Deallocate(NpyIter* it) except NPY_FAIL + int NpyIter_Reset(NpyIter* it, char** errmsg) except NPY_FAIL + int NpyIter_ResetToIterIndexRange(NpyIter* it, npy_intp istart, + npy_intp iend, char** errmsg) except NPY_FAIL + int NpyIter_ResetBasePointers(NpyIter* it, char** baseptrs, char** errmsg) except NPY_FAIL + int NpyIter_GotoMultiIndex(NpyIter* it, const npy_intp* multi_index) except NPY_FAIL + int NpyIter_GotoIndex(NpyIter* it, npy_intp index) except NPY_FAIL + npy_intp NpyIter_GetIterSize(NpyIter* it) nogil + npy_intp NpyIter_GetIterIndex(NpyIter* it) nogil + void NpyIter_GetIterIndexRange(NpyIter* it, npy_intp* istart, + npy_intp* iend) nogil + int NpyIter_GotoIterIndex(NpyIter* it, npy_intp iterindex) except NPY_FAIL + npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* it) nogil + npy_bool NpyIter_HasExternalLoop(NpyIter* it) nogil + npy_bool NpyIter_HasMultiIndex(NpyIter* it) nogil + npy_bool NpyIter_HasIndex(NpyIter* it) nogil + npy_bool NpyIter_RequiresBuffering(NpyIter* it) nogil + npy_bool NpyIter_IsBuffered(NpyIter* it) nogil + npy_bool NpyIter_IsGrowInner(NpyIter* it) nogil + npy_intp NpyIter_GetBufferSize(NpyIter* it) nogil + int NpyIter_GetNDim(NpyIter* it) nogil + int NpyIter_GetNOp(NpyIter* it) nogil + npy_intp* NpyIter_GetAxisStrideArray(NpyIter* it, int axis) except NULL + int NpyIter_GetShape(NpyIter* it, npy_intp* outshape) nogil + PyArray_Descr** NpyIter_GetDescrArray(NpyIter* it) + PyArrayObject** NpyIter_GetOperandArray(NpyIter* it) + ndarray NpyIter_GetIterView(NpyIter* it, npy_intp i) + void NpyIter_GetReadFlags(NpyIter* it, char* outreadflags) + void NpyIter_GetWriteFlags(NpyIter* it, char* outwriteflags) + int NpyIter_CreateCompatibleStrides(NpyIter* it, npy_intp itemsize, + npy_intp* outstrides) except NPY_FAIL + npy_bool NpyIter_IsFirstVisit(NpyIter* it, int iop) nogil + # functions for iterating an NpyIter object + # + # These don't match the definition in the C API because Cython can't wrap + # function pointers that return functions. + NpyIter_IterNextFunc NpyIter_GetIterNext(NpyIter* it, char** errmsg) except NULL + NpyIter_GetMultiIndexFunc NpyIter_GetGetMultiIndex(NpyIter* it, + char** errmsg) except NULL + char** NpyIter_GetDataPtrArray(NpyIter* it) nogil + char** NpyIter_GetInitialDataPtrArray(NpyIter* it) nogil + npy_intp* NpyIter_GetIndexPtr(NpyIter* it) + npy_intp* NpyIter_GetInnerStrideArray(NpyIter* it) nogil + npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* it) nogil + void NpyIter_GetInnerFixedStrideArray(NpyIter* it, npy_intp* outstrides) nogil + npy_bool NpyIter_IterationNeedsAPI(NpyIter* it) nogil + void NpyIter_DebugPrint(NpyIter* it) + +# NpyString API +cdef extern from "numpy/ndarraytypes.h": + ctypedef struct npy_string_allocator: + pass + + ctypedef struct npy_packed_static_string: + pass + + ctypedef struct npy_static_string: + size_t size + const char *buf + + ctypedef struct PyArray_StringDTypeObject: + PyArray_Descr base + PyObject *na_object + char coerce + char has_nan_na + char has_string_na + char array_owned + npy_static_string default_string + npy_static_string na_name + npy_string_allocator *allocator + +cdef extern from "numpy/arrayobject.h": + npy_string_allocator *NpyString_acquire_allocator(const PyArray_StringDTypeObject *descr) + void NpyString_acquire_allocators(size_t n_descriptors, PyArray_Descr *const descrs[], npy_string_allocator *allocators[]) + void NpyString_release_allocator(npy_string_allocator *allocator) + void NpyString_release_allocators(size_t length, npy_string_allocator *allocators[]) + int NpyString_load(npy_string_allocator *allocator, const npy_packed_static_string *packed_string, npy_static_string *unpacked_string) + int NpyString_pack_null(npy_string_allocator *allocator, npy_packed_static_string *packed_string) + int NpyString_pack(npy_string_allocator *allocator, npy_packed_static_string *packed_string, const char *buf, size_t size) diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.pxd b/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..40a24b6c7cc1e60c213e5365c2f3c793b10ee0ae --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.pxd @@ -0,0 +1,1155 @@ +# NumPy static imports for Cython < 3.0 +# +# If any of the PyArray_* functions are called, import_array must be +# called first. +# +# Author: Dag Sverre Seljebotn +# + +DEF _buffer_format_string_len = 255 + +cimport cpython.buffer as pybuf +from cpython.ref cimport Py_INCREF +from cpython.mem cimport PyObject_Malloc, PyObject_Free +from cpython.object cimport PyObject, PyTypeObject +from cpython.buffer cimport PyObject_GetBuffer +from cpython.type cimport type +cimport libc.stdio as stdio + + +cdef extern from *: + # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython. + # See https://github.com/cython/cython/issues/3573 + """ + /* Using NumPy API declarations from "numpy/__init__.pxd" */ + """ + + +cdef extern from "Python.h": + ctypedef int Py_intptr_t + bint PyObject_TypeCheck(object obj, PyTypeObject* type) + +cdef extern from "numpy/arrayobject.h": + # It would be nice to use size_t and ssize_t, but ssize_t has special + # implicit conversion rules, so just use "long". + # Note: The actual type only matters for Cython promotion, so long + # is closer than int, but could lead to incorrect promotion. + # (Not to worrying, and always the status-quo.) + ctypedef signed long npy_intp + ctypedef unsigned long npy_uintp + + ctypedef unsigned char npy_bool + + ctypedef signed char npy_byte + ctypedef signed short npy_short + ctypedef signed int npy_int + ctypedef signed long npy_long + ctypedef signed long long npy_longlong + + ctypedef unsigned char npy_ubyte + ctypedef unsigned short npy_ushort + ctypedef unsigned int npy_uint + ctypedef unsigned long npy_ulong + ctypedef unsigned long long npy_ulonglong + + ctypedef float npy_float + ctypedef double npy_double + ctypedef long double npy_longdouble + + ctypedef signed char npy_int8 + ctypedef signed short npy_int16 + ctypedef signed int npy_int32 + ctypedef signed long long npy_int64 + + ctypedef unsigned char npy_uint8 + ctypedef unsigned short npy_uint16 + ctypedef unsigned int npy_uint32 + ctypedef unsigned long long npy_uint64 + + ctypedef float npy_float32 + ctypedef double npy_float64 + ctypedef long double npy_float80 + ctypedef long double npy_float96 + ctypedef long double npy_float128 + + ctypedef struct npy_cfloat: + pass + + ctypedef struct npy_cdouble: + pass + + ctypedef struct npy_clongdouble: + pass + + ctypedef struct npy_complex64: + pass + + ctypedef struct npy_complex128: + pass + + ctypedef struct npy_complex160: + pass + + ctypedef struct npy_complex192: + pass + + ctypedef struct npy_complex256: + pass + + ctypedef struct PyArray_Dims: + npy_intp *ptr + int len + + + cdef enum NPY_TYPES: + NPY_BOOL + NPY_BYTE + NPY_UBYTE + NPY_SHORT + NPY_USHORT + NPY_INT + NPY_UINT + NPY_LONG + NPY_ULONG + NPY_LONGLONG + NPY_ULONGLONG + NPY_FLOAT + NPY_DOUBLE + NPY_LONGDOUBLE + NPY_CFLOAT + NPY_CDOUBLE + NPY_CLONGDOUBLE + NPY_OBJECT + NPY_STRING + NPY_UNICODE + NPY_VSTRING + NPY_VOID + NPY_DATETIME + NPY_TIMEDELTA + NPY_NTYPES_LEGACY + NPY_NOTYPE + + NPY_INT8 + NPY_INT16 + NPY_INT32 + NPY_INT64 + NPY_UINT8 + NPY_UINT16 + NPY_UINT32 + NPY_UINT64 + NPY_FLOAT16 + NPY_FLOAT32 + NPY_FLOAT64 + NPY_FLOAT80 + NPY_FLOAT96 + NPY_FLOAT128 + NPY_COMPLEX64 + NPY_COMPLEX128 + NPY_COMPLEX160 + NPY_COMPLEX192 + NPY_COMPLEX256 + + NPY_INTP + NPY_UINTP + NPY_DEFAULT_INT # Not a compile time constant (normally)! + + ctypedef enum NPY_ORDER: + NPY_ANYORDER + NPY_CORDER + NPY_FORTRANORDER + NPY_KEEPORDER + + ctypedef enum NPY_CASTING: + NPY_NO_CASTING + NPY_EQUIV_CASTING + NPY_SAFE_CASTING + NPY_SAME_KIND_CASTING + NPY_UNSAFE_CASTING + NPY_SAME_VALUE_CASTING + + ctypedef enum NPY_CLIPMODE: + NPY_CLIP + NPY_WRAP + NPY_RAISE + + ctypedef enum NPY_SCALARKIND: + NPY_NOSCALAR, + NPY_BOOL_SCALAR, + NPY_INTPOS_SCALAR, + NPY_INTNEG_SCALAR, + NPY_FLOAT_SCALAR, + NPY_COMPLEX_SCALAR, + NPY_OBJECT_SCALAR + + ctypedef enum NPY_SORTKIND: + NPY_QUICKSORT + NPY_HEAPSORT + NPY_MERGESORT + + ctypedef enum NPY_SEARCHSIDE: + NPY_SEARCHLEFT + NPY_SEARCHRIGHT + + enum: + NPY_ARRAY_C_CONTIGUOUS + NPY_ARRAY_F_CONTIGUOUS + NPY_ARRAY_OWNDATA + NPY_ARRAY_FORCECAST + NPY_ARRAY_ENSURECOPY + NPY_ARRAY_ENSUREARRAY + NPY_ARRAY_ELEMENTSTRIDES + NPY_ARRAY_ALIGNED + NPY_ARRAY_NOTSWAPPED + NPY_ARRAY_WRITEABLE + NPY_ARRAY_WRITEBACKIFCOPY + + NPY_ARRAY_BEHAVED + NPY_ARRAY_BEHAVED_NS + NPY_ARRAY_CARRAY + NPY_ARRAY_CARRAY_RO + NPY_ARRAY_FARRAY + NPY_ARRAY_FARRAY_RO + NPY_ARRAY_DEFAULT + + NPY_ARRAY_IN_ARRAY + NPY_ARRAY_OUT_ARRAY + NPY_ARRAY_INOUT_ARRAY + NPY_ARRAY_IN_FARRAY + NPY_ARRAY_OUT_FARRAY + NPY_ARRAY_INOUT_FARRAY + + NPY_ARRAY_UPDATE_ALL + + cdef enum: + NPY_MAXDIMS # 64 on NumPy 2.x and 32 on NumPy 1.x + NPY_RAVEL_AXIS # Used for functions like PyArray_Mean + + ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *) + + ctypedef struct PyArray_ArrayDescr: + # shape is a tuple, but Cython doesn't support "tuple shape" + # inside a non-PyObject declaration, so we have to declare it + # as just a PyObject*. + PyObject* shape + + ctypedef struct PyArray_Descr: + pass + + ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]: + # Use PyDataType_* macros when possible, however there are no macros + # for accessing some of the fields, so some are defined. + cdef PyTypeObject* typeobj + cdef char kind + cdef char type + # Numpy sometimes mutates this without warning (e.g. it'll + # sometimes change "|" to "<" in shared dtype objects on + # little-endian machines). If this matters to you, use + # PyArray_IsNativeByteOrder(dtype.byteorder) instead of + # directly accessing this field. + cdef char byteorder + # Flags are not directly accessible on Cython <3. Use PyDataType_FLAGS. + # cdef char flags + cdef int type_num + # itemsize/elsize, alignment, fields, names, and subarray must + # use the `PyDataType_*` accessor macros. With Cython 3 you can + # still use getter attributes `dtype.itemsize` + + ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]: + # Use through macros + pass + + ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]: + cdef int numiter + cdef npy_intp size, index + cdef int nd + cdef npy_intp *dimensions + cdef void **iters + + ctypedef struct PyArrayObject: + # For use in situations where ndarray can't replace PyArrayObject*, + # like PyArrayObject**. + pass + + ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]: + cdef __cythonbufferdefaults__ = {"mode": "strided"} + + cdef: + # Only taking a few of the most commonly used and stable fields. + # One should use PyArray_* macros instead to access the C fields. + char *data + int ndim "nd" + npy_intp *shape "dimensions" + npy_intp *strides + dtype descr # deprecated since NumPy 1.7 ! + PyObject* base # NOT PUBLIC, DO NOT USE ! + + + int _import_array() except -1 + # A second definition so _import_array isn't marked as used when we use it here. + # Do not use - subject to change any time. + int __pyx_import_array "_import_array"() except -1 + + # + # Macros from ndarrayobject.h + # + bint PyArray_CHKFLAGS(ndarray m, int flags) nogil + bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil + bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil + bint PyArray_ISCONTIGUOUS(ndarray m) nogil + bint PyArray_ISWRITEABLE(ndarray m) nogil + bint PyArray_ISALIGNED(ndarray m) nogil + + int PyArray_NDIM(ndarray) nogil + bint PyArray_ISONESEGMENT(ndarray) nogil + bint PyArray_ISFORTRAN(ndarray) nogil + int PyArray_FORTRANIF(ndarray) nogil + + void* PyArray_DATA(ndarray) nogil + char* PyArray_BYTES(ndarray) nogil + + npy_intp* PyArray_DIMS(ndarray) nogil + npy_intp* PyArray_STRIDES(ndarray) nogil + npy_intp PyArray_DIM(ndarray, size_t) nogil + npy_intp PyArray_STRIDE(ndarray, size_t) nogil + + PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference! + PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype! + PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr. + int PyArray_FLAGS(ndarray) nogil + void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7 + void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7 + npy_intp PyArray_ITEMSIZE(ndarray) nogil + int PyArray_TYPE(ndarray arr) nogil + + object PyArray_GETITEM(ndarray arr, void *itemptr) + int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1 + + bint PyTypeNum_ISBOOL(int) nogil + bint PyTypeNum_ISUNSIGNED(int) nogil + bint PyTypeNum_ISSIGNED(int) nogil + bint PyTypeNum_ISINTEGER(int) nogil + bint PyTypeNum_ISFLOAT(int) nogil + bint PyTypeNum_ISNUMBER(int) nogil + bint PyTypeNum_ISSTRING(int) nogil + bint PyTypeNum_ISCOMPLEX(int) nogil + bint PyTypeNum_ISFLEXIBLE(int) nogil + bint PyTypeNum_ISUSERDEF(int) nogil + bint PyTypeNum_ISEXTENDED(int) nogil + bint PyTypeNum_ISOBJECT(int) nogil + + npy_intp PyDataType_ELSIZE(dtype) nogil + npy_intp PyDataType_ALIGNMENT(dtype) nogil + PyObject* PyDataType_METADATA(dtype) nogil + PyArray_ArrayDescr* PyDataType_SUBARRAY(dtype) nogil + PyObject* PyDataType_NAMES(dtype) nogil + PyObject* PyDataType_FIELDS(dtype) nogil + + bint PyDataType_ISBOOL(dtype) nogil + bint PyDataType_ISUNSIGNED(dtype) nogil + bint PyDataType_ISSIGNED(dtype) nogil + bint PyDataType_ISINTEGER(dtype) nogil + bint PyDataType_ISFLOAT(dtype) nogil + bint PyDataType_ISNUMBER(dtype) nogil + bint PyDataType_ISSTRING(dtype) nogil + bint PyDataType_ISCOMPLEX(dtype) nogil + bint PyDataType_ISFLEXIBLE(dtype) nogil + bint PyDataType_ISUSERDEF(dtype) nogil + bint PyDataType_ISEXTENDED(dtype) nogil + bint PyDataType_ISOBJECT(dtype) nogil + bint PyDataType_HASFIELDS(dtype) nogil + bint PyDataType_HASSUBARRAY(dtype) nogil + npy_uint64 PyDataType_FLAGS(dtype) nogil + + bint PyArray_ISBOOL(ndarray) nogil + bint PyArray_ISUNSIGNED(ndarray) nogil + bint PyArray_ISSIGNED(ndarray) nogil + bint PyArray_ISINTEGER(ndarray) nogil + bint PyArray_ISFLOAT(ndarray) nogil + bint PyArray_ISNUMBER(ndarray) nogil + bint PyArray_ISSTRING(ndarray) nogil + bint PyArray_ISCOMPLEX(ndarray) nogil + bint PyArray_ISFLEXIBLE(ndarray) nogil + bint PyArray_ISUSERDEF(ndarray) nogil + bint PyArray_ISEXTENDED(ndarray) nogil + bint PyArray_ISOBJECT(ndarray) nogil + bint PyArray_HASFIELDS(ndarray) nogil + + bint PyArray_ISVARIABLE(ndarray) nogil + + bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil + bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder + bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder + bint PyArray_ISNOTSWAPPED(ndarray) nogil + bint PyArray_ISBYTESWAPPED(ndarray) nogil + + bint PyArray_FLAGSWAP(ndarray, int) nogil + + bint PyArray_ISCARRAY(ndarray) nogil + bint PyArray_ISCARRAY_RO(ndarray) nogil + bint PyArray_ISFARRAY(ndarray) nogil + bint PyArray_ISFARRAY_RO(ndarray) nogil + bint PyArray_ISBEHAVED(ndarray) nogil + bint PyArray_ISBEHAVED_RO(ndarray) nogil + + + bint PyDataType_ISNOTSWAPPED(dtype) nogil + bint PyDataType_ISBYTESWAPPED(dtype) nogil + + bint PyArray_DescrCheck(object) + + bint PyArray_Check(object) + bint PyArray_CheckExact(object) + + # Cannot be supported due to out arg: + # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&) + # bint PyArray_HasArrayInterface(op, out) + + + bint PyArray_IsZeroDim(object) + # Cannot be supported due to ## ## in macro: + # bint PyArray_IsScalar(object, verbatim work) + bint PyArray_CheckScalar(object) + bint PyArray_IsPythonNumber(object) + bint PyArray_IsPythonScalar(object) + bint PyArray_IsAnyScalar(object) + bint PyArray_CheckAnyScalar(object) + + ndarray PyArray_GETCONTIGUOUS(ndarray) + bint PyArray_SAMESHAPE(ndarray, ndarray) nogil + npy_intp PyArray_SIZE(ndarray) nogil + npy_intp PyArray_NBYTES(ndarray) nogil + + object PyArray_FROM_O(object) + object PyArray_FROM_OF(object m, int flags) + object PyArray_FROM_OT(object m, int type) + object PyArray_FROM_OTF(object m, int type, int flags) + object PyArray_FROMANY(object m, int type, int min, int max, int flags) + object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran) + object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran) + void PyArray_FILLWBYTE(ndarray, int val) + object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth) + unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2) + bint PyArray_EquivByteorders(int b1, int b2) nogil + object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum) + object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data) + #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr) + object PyArray_ToScalar(void* data, ndarray arr) + + void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil + void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil + void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil + void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil + + # Cannot be supported due to out arg + # void PyArray_DESCR_REPLACE(descr) + + + object PyArray_Copy(ndarray) + object PyArray_FromObject(object op, int type, int min_depth, int max_depth) + object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth) + object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth) + + object PyArray_Cast(ndarray mp, int type_num) + object PyArray_Take(ndarray ap, object items, int axis) + object PyArray_Put(ndarray ap, object items, object values) + + void PyArray_ITER_RESET(flatiter it) nogil + void PyArray_ITER_NEXT(flatiter it) nogil + void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil + void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil + void* PyArray_ITER_DATA(flatiter it) nogil + bint PyArray_ITER_NOTDONE(flatiter it) nogil + + void PyArray_MultiIter_RESET(broadcast multi) nogil + void PyArray_MultiIter_NEXT(broadcast multi) nogil + void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil + void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil + void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil + void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil + bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil + npy_intp PyArray_MultiIter_SIZE(broadcast multi) nogil + int PyArray_MultiIter_NDIM(broadcast multi) nogil + npy_intp PyArray_MultiIter_INDEX(broadcast multi) nogil + int PyArray_MultiIter_NUMITER(broadcast multi) nogil + npy_intp* PyArray_MultiIter_DIMS(broadcast multi) nogil + void** PyArray_MultiIter_ITERS(broadcast multi) nogil + + # Functions from __multiarray_api.h + + # Functions taking dtype and returning object/ndarray are disabled + # for now as they steal dtype references. I'm conservative and disable + # more than is probably needed until it can be checked further. + int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF... + int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF... + dtype PyArray_DescrFromType (int) + object PyArray_TypeObjectFromType (int) + char * PyArray_Zero (ndarray) + char * PyArray_One (ndarray) + #object PyArray_CastToType (ndarray, dtype, int) + int PyArray_CanCastSafely (int, int) # writes errors + npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors + int PyArray_ObjectType (object, int) except 0 + dtype PyArray_DescrFromObject (object, dtype) + #ndarray* PyArray_ConvertToCommonType (object, int *) + dtype PyArray_DescrFromScalar (object) + dtype PyArray_DescrFromTypeObject (object) + npy_intp PyArray_Size (object) + #object PyArray_Scalar (void *, dtype, object) + #object PyArray_FromScalar (object, dtype) + void PyArray_ScalarAsCtype (object, void *) + #int PyArray_CastScalarToCtype (object, void *, dtype) + #int PyArray_CastScalarDirect (object, dtype, void *, int) + #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int) + #object PyArray_FromAny (object, dtype, int, int, int, object) + object PyArray_EnsureArray (object) + object PyArray_EnsureAnyArray (object) + #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *) + #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *) + #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp) + #object PyArray_FromIter (object, dtype, npy_intp) + object PyArray_Return (ndarray) + #object PyArray_GetField (ndarray, dtype, int) + #int PyArray_SetField (ndarray, dtype, int, object) except -1 + object PyArray_Byteswap (ndarray, npy_bool) + object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER) + int PyArray_CopyInto (ndarray, ndarray) except -1 + int PyArray_CopyAnyInto (ndarray, ndarray) except -1 + int PyArray_CopyObject (ndarray, object) except -1 + object PyArray_NewCopy (ndarray, NPY_ORDER) + object PyArray_ToList (ndarray) + object PyArray_ToString (ndarray, NPY_ORDER) + int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1 + int PyArray_Dump (object, object, int) except -1 + object PyArray_Dumps (object, int) + int PyArray_ValidType (int) # Cannot error + void PyArray_UpdateFlags (ndarray, int) + object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object) + #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object) + #dtype PyArray_DescrNew (dtype) + dtype PyArray_DescrNewFromType (int) + double PyArray_GetPriority (object, double) # clears errors as of 1.25 + object PyArray_IterNew (object) + object PyArray_MultiIterNew (int, ...) + + int PyArray_PyIntAsInt (object) except? -1 + npy_intp PyArray_PyIntAsIntp (object) + int PyArray_Broadcast (broadcast) except -1 + int PyArray_FillWithScalar (ndarray, object) except -1 + npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *) + dtype PyArray_DescrNewByteorder (dtype, char) + object PyArray_IterAllButAxis (object, int *) + #object PyArray_CheckFromAny (object, dtype, int, int, int, object) + #object PyArray_FromArray (ndarray, dtype, int) + object PyArray_FromInterface (object) + object PyArray_FromStructInterface (object) + #object PyArray_FromArrayAttr (object, dtype, object) + #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*) + int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND) + npy_bool PyArray_CanCastScalar (type, type) + int PyArray_RemoveSmallest (broadcast) except -1 + int PyArray_ElementStrides (object) + void PyArray_Item_INCREF (char *, dtype) except * + void PyArray_Item_XDECREF (char *, dtype) except * + object PyArray_Transpose (ndarray, PyArray_Dims *) + object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE) + object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE) + object PyArray_PutMask (ndarray, object, object) + object PyArray_Repeat (ndarray, object, int) + object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE) + int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1 + object PyArray_ArgSort (ndarray, int, NPY_SORTKIND) + object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *) + object PyArray_ArgMax (ndarray, int, ndarray) + object PyArray_ArgMin (ndarray, int, ndarray) + object PyArray_Reshape (ndarray, object) + object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER) + object PyArray_Squeeze (ndarray) + #object PyArray_View (ndarray, dtype, type) + object PyArray_SwapAxes (ndarray, int, int) + object PyArray_Max (ndarray, int, ndarray) + object PyArray_Min (ndarray, int, ndarray) + object PyArray_Ptp (ndarray, int, ndarray) + object PyArray_Mean (ndarray, int, int, ndarray) + object PyArray_Trace (ndarray, int, int, int, int, ndarray) + object PyArray_Diagonal (ndarray, int, int, int) + object PyArray_Clip (ndarray, object, object, ndarray) + object PyArray_Conjugate (ndarray, ndarray) + object PyArray_Nonzero (ndarray) + object PyArray_Std (ndarray, int, int, ndarray, int) + object PyArray_Sum (ndarray, int, int, ndarray) + object PyArray_CumSum (ndarray, int, int, ndarray) + object PyArray_Prod (ndarray, int, int, ndarray) + object PyArray_CumProd (ndarray, int, int, ndarray) + object PyArray_All (ndarray, int, ndarray) + object PyArray_Any (ndarray, int, ndarray) + object PyArray_Compress (ndarray, object, int, ndarray) + object PyArray_Flatten (ndarray, NPY_ORDER) + object PyArray_Ravel (ndarray, NPY_ORDER) + npy_intp PyArray_MultiplyList (npy_intp *, int) + int PyArray_MultiplyIntList (int *, int) + void * PyArray_GetPtr (ndarray, npy_intp*) + int PyArray_CompareLists (npy_intp *, npy_intp *, int) + #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype) + int PyArray_Free (object, void *) + #int PyArray_Converter (object, object*) + int PyArray_IntpFromSequence (object, npy_intp *, int) except -1 + object PyArray_Concatenate (object, int) + object PyArray_InnerProduct (object, object) + object PyArray_MatrixProduct (object, object) + object PyArray_Correlate (object, object, int) + #int PyArray_DescrConverter (object, dtype*) except 0 + #int PyArray_DescrConverter2 (object, dtype*) except 0 + int PyArray_IntpConverter (object, PyArray_Dims *) except 0 + #int PyArray_BufferConverter (object, chunk) except 0 + int PyArray_AxisConverter (object, int *) except 0 + int PyArray_BoolConverter (object, npy_bool *) except 0 + int PyArray_ByteorderConverter (object, char *) except 0 + int PyArray_OrderConverter (object, NPY_ORDER *) except 0 + unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors + #object PyArray_Zeros (int, npy_intp *, dtype, int) + #object PyArray_Empty (int, npy_intp *, dtype, int) + object PyArray_Where (object, object, object) + object PyArray_Arange (double, double, double, int) + #object PyArray_ArangeObj (object, object, object, dtype) + int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0 + object PyArray_LexSort (object, int) + object PyArray_Round (ndarray, int, ndarray) + unsigned char PyArray_EquivTypenums (int, int) + int PyArray_RegisterDataType (dtype) except -1 + int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1 + int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1 + #void PyArray_InitArrFuncs (PyArray_ArrFuncs *) + object PyArray_IntTupleFromIntp (int, npy_intp *) + int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0 + #int PyArray_OutputConverter (object, ndarray*) except 0 + object PyArray_BroadcastToShape (object, npy_intp *, int) + #int PyArray_DescrAlignConverter (object, dtype*) except 0 + #int PyArray_DescrAlignConverter2 (object, dtype*) except 0 + int PyArray_SearchsideConverter (object, void *) except 0 + object PyArray_CheckAxis (ndarray, int *, int) + npy_intp PyArray_OverflowMultiplyList (npy_intp *, int) + int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead. + + # The memory handler functions require the NumPy 1.22 API + # and may require defining NPY_TARGET_VERSION + ctypedef struct PyDataMemAllocator: + void *ctx + void* (*malloc) (void *ctx, size_t size) + void* (*calloc) (void *ctx, size_t nelem, size_t elsize) + void* (*realloc) (void *ctx, void *ptr, size_t new_size) + void (*free) (void *ctx, void *ptr, size_t size) + + ctypedef struct PyDataMem_Handler: + char* name + npy_uint8 version + PyDataMemAllocator allocator + + object PyDataMem_SetHandler(object handler) + object PyDataMem_GetHandler() + + # additional datetime related functions are defined below + + +# Typedefs that matches the runtime dtype objects in +# the numpy module. + +# The ones that are commented out needs an IFDEF function +# in Cython to enable them only on the right systems. + +ctypedef npy_int8 int8_t +ctypedef npy_int16 int16_t +ctypedef npy_int32 int32_t +ctypedef npy_int64 int64_t + +ctypedef npy_uint8 uint8_t +ctypedef npy_uint16 uint16_t +ctypedef npy_uint32 uint32_t +ctypedef npy_uint64 uint64_t + +ctypedef npy_float32 float32_t +ctypedef npy_float64 float64_t +#ctypedef npy_float80 float80_t +#ctypedef npy_float128 float128_t + +ctypedef float complex complex64_t +ctypedef double complex complex128_t + +ctypedef npy_longlong longlong_t +ctypedef npy_ulonglong ulonglong_t + +ctypedef npy_intp intp_t +ctypedef npy_uintp uintp_t + +ctypedef npy_double float_t +ctypedef npy_double double_t +ctypedef npy_longdouble longdouble_t + +ctypedef float complex cfloat_t +ctypedef double complex cdouble_t +ctypedef double complex complex_t +ctypedef long double complex clongdouble_t + +cdef inline object PyArray_MultiIterNew1(a): + return PyArray_MultiIterNew(1, a) + +cdef inline object PyArray_MultiIterNew2(a, b): + return PyArray_MultiIterNew(2, a, b) + +cdef inline object PyArray_MultiIterNew3(a, b, c): + return PyArray_MultiIterNew(3, a, b, c) + +cdef inline object PyArray_MultiIterNew4(a, b, c, d): + return PyArray_MultiIterNew(4, a, b, c, d) + +cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): + return PyArray_MultiIterNew(5, a, b, c, d, e) + +cdef inline tuple PyDataType_SHAPE(dtype d): + if PyDataType_HASSUBARRAY(d): + return d.subarray.shape + else: + return () + + +cdef extern from "numpy/ndarrayobject.h": + PyTypeObject PyTimedeltaArrType_Type + PyTypeObject PyDatetimeArrType_Type + ctypedef int64_t npy_timedelta + ctypedef int64_t npy_datetime + +cdef extern from "numpy/ndarraytypes.h": + ctypedef struct PyArray_DatetimeMetaData: + NPY_DATETIMEUNIT base + int64_t num + + ctypedef struct npy_datetimestruct: + int64_t year + int32_t month, day, hour, min, sec, us, ps, as + + # Iterator API added in v1.6 + # + # These don't match the definition in the C API because Cython can't wrap + # function pointers that return functions. + # https://github.com/cython/cython/issues/6720 + ctypedef int (*NpyIter_IterNextFunc "NpyIter_IterNextFunc *")(NpyIter* it) noexcept nogil + ctypedef void (*NpyIter_GetMultiIndexFunc "NpyIter_GetMultiIndexFunc *")(NpyIter* it, npy_intp* outcoords) noexcept nogil + +cdef extern from "numpy/arrayscalars.h": + + # abstract types + ctypedef class numpy.generic [object PyObject]: + pass + ctypedef class numpy.number [object PyObject]: + pass + ctypedef class numpy.integer [object PyObject]: + pass + ctypedef class numpy.signedinteger [object PyObject]: + pass + ctypedef class numpy.unsignedinteger [object PyObject]: + pass + ctypedef class numpy.inexact [object PyObject]: + pass + ctypedef class numpy.floating [object PyObject]: + pass + ctypedef class numpy.complexfloating [object PyObject]: + pass + ctypedef class numpy.flexible [object PyObject]: + pass + ctypedef class numpy.character [object PyObject]: + pass + + ctypedef struct PyDatetimeScalarObject: + # PyObject_HEAD + npy_datetime obval + PyArray_DatetimeMetaData obmeta + + ctypedef struct PyTimedeltaScalarObject: + # PyObject_HEAD + npy_timedelta obval + PyArray_DatetimeMetaData obmeta + + ctypedef enum NPY_DATETIMEUNIT: + NPY_FR_Y + NPY_FR_M + NPY_FR_W + NPY_FR_D + NPY_FR_B + NPY_FR_h + NPY_FR_m + NPY_FR_s + NPY_FR_ms + NPY_FR_us + NPY_FR_ns + NPY_FR_ps + NPY_FR_fs + NPY_FR_as + NPY_FR_GENERIC + + +cdef extern from "numpy/arrayobject.h": + # These are part of the C-API defined in `__multiarray_api.h` + + # NumPy internal definitions in datetime_strings.c: + int get_datetime_iso_8601_strlen "NpyDatetime_GetDatetimeISO8601StrLen" ( + int local, NPY_DATETIMEUNIT base) + int make_iso_8601_datetime "NpyDatetime_MakeISO8601Datetime" ( + npy_datetimestruct *dts, char *outstr, npy_intp outlen, + int local, int utc, NPY_DATETIMEUNIT base, int tzoffset, + NPY_CASTING casting) except -1 + + # NumPy internal definition in datetime.c: + # May return 1 to indicate that object does not appear to be a datetime + # (returns 0 on success). + int convert_pydatetime_to_datetimestruct "NpyDatetime_ConvertPyDateTimeToDatetimeStruct" ( + PyObject *obj, npy_datetimestruct *out, + NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) except -1 + int convert_datetime64_to_datetimestruct "NpyDatetime_ConvertDatetime64ToDatetimeStruct" ( + PyArray_DatetimeMetaData *meta, npy_datetime dt, + npy_datetimestruct *out) except -1 + int convert_datetimestruct_to_datetime64 "NpyDatetime_ConvertDatetimeStructToDatetime64"( + PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, + npy_datetime *out) except -1 + + +# +# ufunc API +# + +cdef extern from "numpy/ufuncobject.h": + + ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *) + + ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]: + cdef: + int nin, nout, nargs + int identity + PyUFuncGenericFunction *functions + void **data + int ntypes + int check_return + char *name + char *types + char *doc + void *ptr + PyObject *obj + PyObject *userloops + + cdef enum: + PyUFunc_Zero + PyUFunc_One + PyUFunc_None + # deprecated + UFUNC_FPE_DIVIDEBYZERO + UFUNC_FPE_OVERFLOW + UFUNC_FPE_UNDERFLOW + UFUNC_FPE_INVALID + # use these instead + NPY_FPE_DIVIDEBYZERO + NPY_FPE_OVERFLOW + NPY_FPE_UNDERFLOW + NPY_FPE_INVALID + + object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *, + void **, char *, int, int, int, int, char *, char *, int) + int PyUFunc_RegisterLoopForType(ufunc, int, + PyUFuncGenericFunction, int *, void *) except -1 + void PyUFunc_f_f_As_d_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_d_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_f_f \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_g_g \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_F_F_As_D_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_F_F \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_D_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_G_G \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_O_O \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_ff_f_As_dd_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_ff_f \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_dd_d \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_gg_g \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_FF_F_As_DD_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_DD_D \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_FF_F \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_GG_G \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_OO_O \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_O_O_method \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_OO_O_method \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_On_Om \ + (char **, npy_intp *, npy_intp *, void *) + void PyUFunc_clearfperr() + int PyUFunc_getfperr() + int PyUFunc_ReplaceLoopBySignature \ + (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *) + object PyUFunc_FromFuncAndDataAndSignature \ + (PyUFuncGenericFunction *, void **, char *, int, int, int, + int, char *, char *, int, char *) + + int _import_umath() except -1 + +cdef inline void set_array_base(ndarray arr, object base): + Py_INCREF(base) # important to do this before stealing the reference below! + PyArray_SetBaseObject(arr, base) + +cdef inline object get_array_base(ndarray arr): + base = PyArray_BASE(arr) + if base is NULL: + return None + return base + +# Versions of the import_* functions which are more suitable for +# Cython code. +cdef inline int import_array() except -1: + try: + __pyx_import_array() + except Exception: + raise ImportError("numpy._core.multiarray failed to import") + +cdef inline int import_umath() except -1: + try: + _import_umath() + except Exception: + raise ImportError("numpy._core.umath failed to import") + +cdef inline int import_ufunc() except -1: + try: + _import_umath() + except Exception: + raise ImportError("numpy._core.umath failed to import") + + +cdef inline bint is_timedelta64_object(object obj): + """ + Cython equivalent of `isinstance(obj, np.timedelta64)` + + Parameters + ---------- + obj : object + + Returns + ------- + bool + """ + return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) + + +cdef inline bint is_datetime64_object(object obj): + """ + Cython equivalent of `isinstance(obj, np.datetime64)` + + Parameters + ---------- + obj : object + + Returns + ------- + bool + """ + return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) + + +cdef inline npy_datetime get_datetime64_value(object obj) nogil: + """ + returns the int64 value underlying scalar numpy datetime64 object + + Note that to interpret this as a datetime, the corresponding unit is + also needed. That can be found using `get_datetime64_unit`. + """ + return (obj).obval + + +cdef inline npy_timedelta get_timedelta64_value(object obj) nogil: + """ + returns the int64 value underlying scalar numpy timedelta64 object + """ + return (obj).obval + + +cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil: + """ + returns the unit part of the dtype for a numpy datetime64 object. + """ + return (obj).obmeta.base + + +cdef extern from "numpy/arrayobject.h": + + ctypedef struct NpyIter: + pass + + cdef enum: + NPY_FAIL + NPY_SUCCEED + + cdef enum: + # Track an index representing C order + NPY_ITER_C_INDEX + # Track an index representing Fortran order + NPY_ITER_F_INDEX + # Track a multi-index + NPY_ITER_MULTI_INDEX + # User code external to the iterator does the 1-dimensional innermost loop + NPY_ITER_EXTERNAL_LOOP + # Convert all the operands to a common data type + NPY_ITER_COMMON_DTYPE + # Operands may hold references, requiring API access during iteration + NPY_ITER_REFS_OK + # Zero-sized operands should be permitted, iteration checks IterSize for 0 + NPY_ITER_ZEROSIZE_OK + # Permits reductions (size-0 stride with dimension size > 1) + NPY_ITER_REDUCE_OK + # Enables sub-range iteration + NPY_ITER_RANGED + # Enables buffering + NPY_ITER_BUFFERED + # When buffering is enabled, grows the inner loop if possible + NPY_ITER_GROWINNER + # Delay allocation of buffers until first Reset* call + NPY_ITER_DELAY_BUFALLOC + # When NPY_KEEPORDER is specified, disable reversing negative-stride axes + NPY_ITER_DONT_NEGATE_STRIDES + NPY_ITER_COPY_IF_OVERLAP + # The operand will be read from and written to + NPY_ITER_READWRITE + # The operand will only be read from + NPY_ITER_READONLY + # The operand will only be written to + NPY_ITER_WRITEONLY + # The operand's data must be in native byte order + NPY_ITER_NBO + # The operand's data must be aligned + NPY_ITER_ALIGNED + # The operand's data must be contiguous (within the inner loop) + NPY_ITER_CONTIG + # The operand may be copied to satisfy requirements + NPY_ITER_COPY + # The operand may be copied with WRITEBACKIFCOPY to satisfy requirements + NPY_ITER_UPDATEIFCOPY + # Allocate the operand if it is NULL + NPY_ITER_ALLOCATE + # If an operand is allocated, don't use any subtype + NPY_ITER_NO_SUBTYPE + # This is a virtual array slot, operand is NULL but temporary data is there + NPY_ITER_VIRTUAL + # Require that the dimension match the iterator dimensions exactly + NPY_ITER_NO_BROADCAST + # A mask is being used on this array, affects buffer -> array copy + NPY_ITER_WRITEMASKED + # This array is the mask for all WRITEMASKED operands + NPY_ITER_ARRAYMASK + # Assume iterator order data access for COPY_IF_OVERLAP + NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE + + # construction and destruction functions + NpyIter* NpyIter_New(ndarray arr, npy_uint32 flags, NPY_ORDER order, + NPY_CASTING casting, dtype datatype) except NULL + NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags, + NPY_ORDER order, NPY_CASTING casting, npy_uint32* + op_flags, PyArray_Descr** op_dtypes) except NULL + NpyIter* NpyIter_AdvancedNew(npy_intp nop, PyArrayObject** op, + npy_uint32 flags, NPY_ORDER order, + NPY_CASTING casting, npy_uint32* op_flags, + PyArray_Descr** op_dtypes, int oa_ndim, + int** op_axes, const npy_intp* itershape, + npy_intp buffersize) except NULL + NpyIter* NpyIter_Copy(NpyIter* it) except NULL + int NpyIter_RemoveAxis(NpyIter* it, int axis) except NPY_FAIL + int NpyIter_RemoveMultiIndex(NpyIter* it) except NPY_FAIL + int NpyIter_EnableExternalLoop(NpyIter* it) except NPY_FAIL + int NpyIter_Deallocate(NpyIter* it) except NPY_FAIL + int NpyIter_Reset(NpyIter* it, char** errmsg) except NPY_FAIL + int NpyIter_ResetToIterIndexRange(NpyIter* it, npy_intp istart, + npy_intp iend, char** errmsg) except NPY_FAIL + int NpyIter_ResetBasePointers(NpyIter* it, char** baseptrs, char** errmsg) except NPY_FAIL + int NpyIter_GotoMultiIndex(NpyIter* it, const npy_intp* multi_index) except NPY_FAIL + int NpyIter_GotoIndex(NpyIter* it, npy_intp index) except NPY_FAIL + npy_intp NpyIter_GetIterSize(NpyIter* it) nogil + npy_intp NpyIter_GetIterIndex(NpyIter* it) nogil + void NpyIter_GetIterIndexRange(NpyIter* it, npy_intp* istart, + npy_intp* iend) nogil + int NpyIter_GotoIterIndex(NpyIter* it, npy_intp iterindex) except NPY_FAIL + npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* it) nogil + npy_bool NpyIter_HasExternalLoop(NpyIter* it) nogil + npy_bool NpyIter_HasMultiIndex(NpyIter* it) nogil + npy_bool NpyIter_HasIndex(NpyIter* it) nogil + npy_bool NpyIter_RequiresBuffering(NpyIter* it) nogil + npy_bool NpyIter_IsBuffered(NpyIter* it) nogil + npy_bool NpyIter_IsGrowInner(NpyIter* it) nogil + npy_intp NpyIter_GetBufferSize(NpyIter* it) nogil + int NpyIter_GetNDim(NpyIter* it) nogil + int NpyIter_GetNOp(NpyIter* it) nogil + npy_intp* NpyIter_GetAxisStrideArray(NpyIter* it, int axis) except NULL + int NpyIter_GetShape(NpyIter* it, npy_intp* outshape) nogil + PyArray_Descr** NpyIter_GetDescrArray(NpyIter* it) + PyArrayObject** NpyIter_GetOperandArray(NpyIter* it) + ndarray NpyIter_GetIterView(NpyIter* it, npy_intp i) + void NpyIter_GetReadFlags(NpyIter* it, char* outreadflags) + void NpyIter_GetWriteFlags(NpyIter* it, char* outwriteflags) + int NpyIter_CreateCompatibleStrides(NpyIter* it, npy_intp itemsize, + npy_intp* outstrides) except NPY_FAIL + npy_bool NpyIter_IsFirstVisit(NpyIter* it, int iop) nogil + # functions for iterating an NpyIter object + # + # These don't match the definition in the C API because Cython can't wrap + # function pointers that return functions. + NpyIter_IterNextFunc* NpyIter_GetIterNext(NpyIter* it, char** errmsg) except NULL + NpyIter_GetMultiIndexFunc* NpyIter_GetGetMultiIndex(NpyIter* it, + char** errmsg) except NULL + char** NpyIter_GetDataPtrArray(NpyIter* it) nogil + char** NpyIter_GetInitialDataPtrArray(NpyIter* it) nogil + npy_intp* NpyIter_GetIndexPtr(NpyIter* it) + npy_intp* NpyIter_GetInnerStrideArray(NpyIter* it) nogil + npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* it) nogil + void NpyIter_GetInnerFixedStrideArray(NpyIter* it, npy_intp* outstrides) nogil + npy_bool NpyIter_IterationNeedsAPI(NpyIter* it) nogil + void NpyIter_DebugPrint(NpyIter* it) + +# NpyString API +cdef extern from "numpy/ndarraytypes.h": + ctypedef struct npy_string_allocator: + pass + + ctypedef struct npy_packed_static_string: + pass + + ctypedef struct npy_static_string: + size_t size + const char *buf + + ctypedef struct PyArray_StringDTypeObject: + PyArray_Descr base + PyObject *na_object + char coerce + char has_nan_na + char has_string_na + char array_owned + npy_static_string default_string + npy_static_string na_name + npy_string_allocator *allocator + +cdef extern from "numpy/arrayobject.h": + npy_string_allocator *NpyString_acquire_allocator(const PyArray_StringDTypeObject *descr) + void NpyString_acquire_allocators(size_t n_descriptors, PyArray_Descr *const descrs[], npy_string_allocator *allocators[]) + void NpyString_release_allocator(npy_string_allocator *allocator) + void NpyString_release_allocators(size_t length, npy_string_allocator *allocators[]) + int NpyString_load(npy_string_allocator *allocator, const npy_packed_static_string *packed_string, npy_static_string *unpacked_string) + int NpyString_pack_null(npy_string_allocator *allocator, npy_packed_static_string *packed_string) + int NpyString_pack(npy_string_allocator *allocator, npy_packed_static_string *packed_string, const char *buf, size_t size) diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.py b/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef7c1ed7678aeb40101965a153fa5ba24579a544 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.py @@ -0,0 +1,942 @@ +""" +NumPy +===== + +Provides + 1. An array object of arbitrary homogeneous items + 2. Fast mathematical operations over arrays + 3. Linear Algebra, Fourier Transforms, Random Number Generation + +How to use the documentation +---------------------------- +Documentation is available in two forms: docstrings provided +with the code, and a loose standing reference guide, available from +`the NumPy homepage `_. + +We recommend exploring the docstrings using +`IPython `_, an advanced Python shell with +TAB-completion and introspection capabilities. See below for further +instructions. + +The docstring examples assume that `numpy` has been imported as ``np``:: + + >>> import numpy as np + +Code snippets are indicated by three greater-than signs:: + + >>> x = 42 + >>> x = x + 1 + +Use the built-in ``help`` function to view a function's docstring:: + + >>> help(np.sort) + ... # doctest: +SKIP + +For some objects, ``np.info(obj)`` may provide additional help. This is +particularly true if you see the line "Help on ufunc object:" at the top +of the help() page. Ufuncs are implemented in C, not Python, for speed. +The native Python help() does not know how to view their help, but our +np.info() function does. + +Available subpackages +--------------------- +lib + Basic functions used by several sub-packages. +random + Core Random Tools +linalg + Core Linear Algebra Tools +fft + Core FFT routines +polynomial + Polynomial tools +testing + NumPy testing tools +distutils + Enhancements to distutils with support for + Fortran compilers support and more (for Python <= 3.11) + +Utilities +--------- +test + Run numpy unittests +show_config + Show numpy build configuration +__version__ + NumPy version string + +Viewing documentation using IPython +----------------------------------- + +Start IPython and import `numpy` usually under the alias ``np``: `import +numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste +examples into the shell. To see which functions are available in `numpy`, +type ``np.`` (where ```` refers to the TAB key), or use +``np.*cos*?`` (where ```` refers to the ENTER key) to narrow +down the list. To view the docstring for a function, use +``np.cos?`` (to view the docstring) and ``np.cos??`` (to view +the source code). + +Copies vs. in-place operation +----------------------------- +Most of the functions in `numpy` return a copy of the array argument +(e.g., `np.sort`). In-place versions of these functions are often +available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. +Exceptions to this rule are documented. + +""" +import os +import sys +import warnings + +# If a version with git hash was stored, use that instead +from . import version +from ._expired_attrs_2_0 import __expired_attributes__ +from ._globals import _CopyMode, _NoValue +from .version import __version__ + +# We first need to detect if we're being called as part of the numpy setup +# procedure itself in a reliable manner. +try: + __NUMPY_SETUP__ # noqa: B018 +except NameError: + __NUMPY_SETUP__ = False + +if __NUMPY_SETUP__: + sys.stderr.write('Running from numpy source directory.\n') +else: + # Allow distributors to run custom init code before importing numpy._core + from . import _distributor_init + + try: + from numpy.__config__ import show_config + except ImportError as e: + if isinstance(e, ModuleNotFoundError) and e.name == "numpy.__config__": + # The __config__ module itself was not found, so add this info: + msg = """Error importing numpy: you should not try to import numpy from + its source directory; please exit the numpy source tree, and relaunch + your python interpreter from there.""" + raise ImportError(msg) from e + raise + + from . import _core + from ._core import ( + False_, + ScalarType, + True_, + abs, + absolute, + acos, + acosh, + add, + all, + allclose, + amax, + amin, + any, + arange, + arccos, + arccosh, + arcsin, + arcsinh, + arctan, + arctan2, + arctanh, + argmax, + argmin, + argpartition, + argsort, + argwhere, + around, + array, + array2string, + array_equal, + array_equiv, + array_repr, + array_str, + asanyarray, + asarray, + ascontiguousarray, + asfortranarray, + asin, + asinh, + astype, + atan, + atan2, + atanh, + atleast_1d, + atleast_2d, + atleast_3d, + base_repr, + binary_repr, + bitwise_and, + bitwise_count, + bitwise_invert, + bitwise_left_shift, + bitwise_not, + bitwise_or, + bitwise_right_shift, + bitwise_xor, + block, + bool, + bool_, + broadcast, + busday_count, + busday_offset, + busdaycalendar, + byte, + bytes_, + can_cast, + cbrt, + cdouble, + ceil, + character, + choose, + clip, + clongdouble, + complex64, + complex128, + complexfloating, + compress, + concat, + concatenate, + conj, + conjugate, + convolve, + copysign, + copyto, + correlate, + cos, + cosh, + count_nonzero, + cross, + csingle, + cumprod, + cumsum, + cumulative_prod, + cumulative_sum, + datetime64, + datetime_as_string, + datetime_data, + deg2rad, + degrees, + diagonal, + divide, + divmod, + dot, + double, + dtype, + e, + einsum, + einsum_path, + empty, + empty_like, + equal, + errstate, + euler_gamma, + exp, + exp2, + expm1, + fabs, + finfo, + flatiter, + flatnonzero, + flexible, + float16, + float32, + float64, + float_power, + floating, + floor, + floor_divide, + fmax, + fmin, + fmod, + format_float_positional, + format_float_scientific, + frexp, + from_dlpack, + frombuffer, + fromfile, + fromfunction, + fromiter, + frompyfunc, + fromstring, + full, + full_like, + gcd, + generic, + geomspace, + get_printoptions, + getbufsize, + geterr, + geterrcall, + greater, + greater_equal, + half, + heaviside, + hstack, + hypot, + identity, + iinfo, + indices, + inexact, + inf, + inner, + int8, + int16, + int32, + int64, + int_, + intc, + integer, + intp, + invert, + is_busday, + isclose, + isdtype, + isfinite, + isfortran, + isinf, + isnan, + isnat, + isscalar, + issubdtype, + lcm, + ldexp, + left_shift, + less, + less_equal, + lexsort, + linspace, + little_endian, + log, + log1p, + log2, + log10, + logaddexp, + logaddexp2, + logical_and, + logical_not, + logical_or, + logical_xor, + logspace, + long, + longdouble, + longlong, + matmul, + matrix_transpose, + matvec, + max, + maximum, + may_share_memory, + mean, + memmap, + min, + min_scalar_type, + minimum, + mod, + modf, + moveaxis, + multiply, + nan, + ndarray, + ndim, + nditer, + negative, + nested_iters, + newaxis, + nextafter, + nonzero, + not_equal, + number, + object_, + ones, + ones_like, + outer, + partition, + permute_dims, + pi, + positive, + pow, + power, + printoptions, + prod, + promote_types, + ptp, + put, + putmask, + rad2deg, + radians, + ravel, + recarray, + reciprocal, + record, + remainder, + repeat, + require, + reshape, + resize, + result_type, + right_shift, + rint, + roll, + rollaxis, + round, + sctypeDict, + searchsorted, + set_printoptions, + setbufsize, + seterr, + seterrcall, + shape, + shares_memory, + short, + sign, + signbit, + signedinteger, + sin, + single, + sinh, + size, + sort, + spacing, + sqrt, + square, + squeeze, + stack, + std, + str_, + subtract, + sum, + swapaxes, + take, + tan, + tanh, + tensordot, + timedelta64, + trace, + transpose, + true_divide, + trunc, + typecodes, + ubyte, + ufunc, + uint, + uint8, + uint16, + uint32, + uint64, + uintc, + uintp, + ulong, + ulonglong, + unsignedinteger, + unstack, + ushort, + var, + vdot, + vecdot, + vecmat, + void, + vstack, + where, + zeros, + zeros_like, + ) + + # NOTE: It's still under discussion whether these aliases + # should be removed. + for ta in ["float96", "float128", "complex192", "complex256"]: + try: + globals()[ta] = getattr(_core, ta) + except AttributeError: + pass + del ta + + from . import lib, matrixlib as _mat + from .lib import scimath as emath + from .lib._arraypad_impl import pad + from .lib._arraysetops_impl import ( + ediff1d, + intersect1d, + isin, + setdiff1d, + setxor1d, + union1d, + unique, + unique_all, + unique_counts, + unique_inverse, + unique_values, + ) + from .lib._function_base_impl import ( + angle, + append, + asarray_chkfinite, + average, + bartlett, + bincount, + blackman, + copy, + corrcoef, + cov, + delete, + diff, + digitize, + extract, + flip, + gradient, + hamming, + hanning, + i0, + insert, + interp, + iterable, + kaiser, + median, + meshgrid, + percentile, + piecewise, + place, + quantile, + rot90, + select, + sinc, + sort_complex, + trapezoid, + trim_zeros, + unwrap, + vectorize, + ) + from .lib._histograms_impl import histogram, histogram_bin_edges, histogramdd + from .lib._index_tricks_impl import ( + c_, + diag_indices, + diag_indices_from, + fill_diagonal, + index_exp, + ix_, + mgrid, + ndenumerate, + ndindex, + ogrid, + r_, + ravel_multi_index, + s_, + unravel_index, + ) + from .lib._nanfunctions_impl import ( + nanargmax, + nanargmin, + nancumprod, + nancumsum, + nanmax, + nanmean, + nanmedian, + nanmin, + nanpercentile, + nanprod, + nanquantile, + nanstd, + nansum, + nanvar, + ) + from .lib._npyio_impl import ( + fromregex, + genfromtxt, + load, + loadtxt, + packbits, + save, + savetxt, + savez, + savez_compressed, + unpackbits, + ) + from .lib._polynomial_impl import ( + poly, + poly1d, + polyadd, + polyder, + polydiv, + polyfit, + polyint, + polymul, + polysub, + polyval, + roots, + ) + from .lib._shape_base_impl import ( + apply_along_axis, + apply_over_axes, + array_split, + column_stack, + dsplit, + dstack, + expand_dims, + hsplit, + kron, + put_along_axis, + row_stack, + split, + take_along_axis, + tile, + vsplit, + ) + from .lib._stride_tricks_impl import ( + broadcast_arrays, + broadcast_shapes, + broadcast_to, + ) + from .lib._twodim_base_impl import ( + diag, + diagflat, + eye, + fliplr, + flipud, + histogram2d, + mask_indices, + tri, + tril, + tril_indices, + tril_indices_from, + triu, + triu_indices, + triu_indices_from, + vander, + ) + from .lib._type_check_impl import ( + common_type, + imag, + iscomplex, + iscomplexobj, + isreal, + isrealobj, + mintypecode, + nan_to_num, + real, + real_if_close, + typename, + ) + from .lib._ufunclike_impl import fix, isneginf, isposinf + from .lib._utils_impl import get_include, info, show_runtime + from .matrixlib import asmatrix, bmat, matrix + + # public submodules are imported lazily, therefore are accessible from + # __getattr__. Note that `distutils` (deprecated) and `array_api` + # (experimental label) are not added here, because `from numpy import *` + # must not raise any warnings - that's too disruptive. + __numpy_submodules__ = { + "linalg", "fft", "dtypes", "random", "polynomial", "ma", + "exceptions", "lib", "ctypeslib", "testing", "typing", + "f2py", "test", "rec", "char", "core", "strings", + } + + # We build warning messages for former attributes + _msg = ( + "module 'numpy' has no attribute '{n}'.\n" + "`np.{n}` was a deprecated alias for the builtin `{n}`. " + "To avoid this error in existing code, use `{n}` by itself. " + "Doing this will not modify any behavior and is safe. {extended_msg}\n" + "The aliases was originally deprecated in NumPy 1.20; for more " + "details and guidance see the original release note at:\n" + " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations") + + _specific_msg = ( + "If you specifically wanted the numpy scalar type, use `np.{}` here.") + + _int_extended_msg = ( + "When replacing `np.{}`, you may wish to use e.g. `np.int64` " + "or `np.int32` to specify the precision. If you wish to review " + "your current use, check the release note link for " + "additional information.") + + _type_info = [ + ("object", ""), # The NumPy scalar only exists by name. + ("float", _specific_msg.format("float64")), + ("complex", _specific_msg.format("complex128")), + ("str", _specific_msg.format("str_")), + ("int", _int_extended_msg.format("int"))] + + __former_attrs__ = { + n: _msg.format(n=n, extended_msg=extended_msg) + for n, extended_msg in _type_info + } + + # Some of these could be defined right away, but most were aliases to + # the Python objects and only removed in NumPy 1.24. Defining them should + # probably wait for NumPy 1.26 or 2.0. + # When defined, these should possibly not be added to `__all__` to avoid + # import with `from numpy import *`. + __future_scalars__ = {"str", "bytes", "object"} + + __array_api_version__ = "2024.12" + + from ._array_api_info import __array_namespace_info__ + + __all__ = list( + __numpy_submodules__ | + set(_core.__all__) | + set(_mat.__all__) | + set(lib._histograms_impl.__all__) | + set(lib._nanfunctions_impl.__all__) | + set(lib._function_base_impl.__all__) | + set(lib._twodim_base_impl.__all__) | + set(lib._shape_base_impl.__all__) | + set(lib._type_check_impl.__all__) | + set(lib._arraysetops_impl.__all__) | + set(lib._ufunclike_impl.__all__) | + set(lib._arraypad_impl.__all__) | + set(lib._utils_impl.__all__) | + set(lib._stride_tricks_impl.__all__) | + set(lib._polynomial_impl.__all__) | + set(lib._npyio_impl.__all__) | + set(lib._index_tricks_impl.__all__) | + {"emath", "show_config", "__version__", "__array_namespace_info__"} + ) + + # Filter out Cython harmless warnings + warnings.filterwarnings("ignore", message="numpy.dtype size changed") + warnings.filterwarnings("ignore", message="numpy.ufunc size changed") + warnings.filterwarnings("ignore", message="numpy.ndarray size changed") + + def __getattr__(attr): + # Warn for expired attributes + import warnings + + if attr == "linalg": + import numpy.linalg as linalg + return linalg + elif attr == "fft": + import numpy.fft as fft + return fft + elif attr == "dtypes": + import numpy.dtypes as dtypes + return dtypes + elif attr == "random": + import numpy.random as random + return random + elif attr == "polynomial": + import numpy.polynomial as polynomial + return polynomial + elif attr == "ma": + import numpy.ma as ma + return ma + elif attr == "ctypeslib": + import numpy.ctypeslib as ctypeslib + return ctypeslib + elif attr == "exceptions": + import numpy.exceptions as exceptions + return exceptions + elif attr == "testing": + import numpy.testing as testing + return testing + elif attr == "matlib": + import numpy.matlib as matlib + return matlib + elif attr == "f2py": + import numpy.f2py as f2py + return f2py + elif attr == "typing": + import numpy.typing as typing + return typing + elif attr == "rec": + import numpy.rec as rec + return rec + elif attr == "char": + import numpy.char as char + return char + elif attr == "array_api": + raise AttributeError("`numpy.array_api` is not available from " + "numpy 2.0 onwards", name=None) + elif attr == "core": + import numpy.core as core + return core + elif attr == "strings": + import numpy.strings as strings + return strings + elif attr == "distutils": + if 'distutils' in __numpy_submodules__: + import numpy.distutils as distutils + return distutils + else: + raise AttributeError("`numpy.distutils` is not available from " + "Python 3.12 onwards", name=None) + + if attr in __future_scalars__: + # And future warnings for those that will change, but also give + # the AttributeError + warnings.warn( + f"In the future `np.{attr}` will be defined as the " + "corresponding NumPy scalar.", FutureWarning, stacklevel=2) + + if attr in __former_attrs__: + raise AttributeError(__former_attrs__[attr], name=None) + + if attr in __expired_attributes__: + raise AttributeError( + f"`np.{attr}` was removed in the NumPy 2.0 release. " + f"{__expired_attributes__[attr]}", + name=None + ) + + if attr == "chararray": + warnings.warn( + "`np.chararray` is deprecated and will be removed from " + "the main namespace in the future. Use an array with a string " + "or bytes dtype instead.", DeprecationWarning, stacklevel=2) + import numpy.char as char + return char.chararray + + raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") + + def __dir__(): + public_symbols = ( + globals().keys() | __numpy_submodules__ + ) + public_symbols -= { + "matrixlib", "matlib", "tests", "conftest", "version", + "distutils", "array_api" + } + return list(public_symbols) + + # Pytest testing + from numpy._pytesttester import PytestTester + test = PytestTester(__name__) + del PytestTester + + def _sanity_check(): + """ + Quick sanity checks for common bugs caused by environment. + There are some cases e.g. with wrong BLAS ABI that cause wrong + results under specific runtime conditions that are not necessarily + achieved during test suite runs, and it is useful to catch those early. + + See https://github.com/numpy/numpy/issues/8577 and other + similar bug reports. + + """ + try: + x = ones(2, dtype=float32) + if not abs(x.dot(x) - float32(2.0)) < 1e-5: + raise AssertionError + except AssertionError: + msg = ("The current Numpy installation ({!r}) fails to " + "pass simple sanity checks. This can be caused for example " + "by incorrect BLAS library being linked in, or by mixing " + "package managers (pip, conda, apt, ...). Search closed " + "numpy issues for similar problems.") + raise RuntimeError(msg.format(__file__)) from None + + _sanity_check() + del _sanity_check + + def _mac_os_check(): + """ + Quick Sanity check for Mac OS look for accelerate build bugs. + Testing numpy polyfit calls init_dgelsd(LAPACK) + """ + try: + c = array([3., 2., 1.]) + x = linspace(0, 2, 5) + y = polyval(c, x) + _ = polyfit(x, y, 2, cov=True) + except ValueError: + pass + + if sys.platform == "darwin": + from . import exceptions + with warnings.catch_warnings(record=True) as w: + _mac_os_check() + # Throw runtime error, if the test failed + # Check for warning and report the error_message + if len(w) > 0: + for _wn in w: + if _wn.category is exceptions.RankWarning: + # Ignore other warnings, they may not be relevant (see gh-25433) + error_message = ( + f"{_wn.category.__name__}: {_wn.message}" + ) + msg = ( + "Polyfit sanity test emitted a warning, most likely due " + "to using a buggy Accelerate backend." + "\nIf you compiled yourself, more information is available at:" # noqa: E501 + "\nhttps://numpy.org/devdocs/building/index.html" + "\nOtherwise report this to the vendor " + f"that provided NumPy.\n\n{error_message}\n") + raise RuntimeError(msg) + del _wn + del w + del _mac_os_check + + def blas_fpe_check(): + # Check if BLAS adds spurious FPEs, mostly seen on M4 arms with Accelerate. + with errstate(all='raise'): + x = ones((20, 20)) + try: + x @ x + except FloatingPointError: + res = _core._multiarray_umath._blas_supports_fpe(False) + if res: # res was not modified (hardcoded to True for now) + warnings.warn( + "Spurious warnings given by blas but suppression not " + "set up on this platform. Please open a NumPy issue.", + UserWarning, stacklevel=2) + + blas_fpe_check() + del blas_fpe_check + + def hugepage_setup(): + """ + We usually use madvise hugepages support, but on some old kernels it + is slow and thus better avoided. Specifically kernel version 4.6 + had a bug fix which probably fixed this: + https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff + """ + use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None) + if sys.platform == "linux" and use_hugepage is None: + # If there is an issue with parsing the kernel version, + # set use_hugepage to 0. Usage of LooseVersion will handle + # the kernel version parsing better, but avoided since it + # will increase the import time. + # See: #16679 for related discussion. + try: + use_hugepage = 1 + kernel_version = os.uname().release.split(".")[:2] + kernel_version = tuple(int(v) for v in kernel_version) + if kernel_version < (4, 6): + use_hugepage = 0 + except ValueError: + use_hugepage = 0 + elif use_hugepage is None: + # This is not Linux, so it should not matter, just enable anyway + use_hugepage = 1 + else: + use_hugepage = int(use_hugepage) + return use_hugepage + + # Note that this will currently only make a difference on Linux + _core.multiarray._set_madvise_hugepage(hugepage_setup()) + del hugepage_setup + + # Give a warning if NumPy is reloaded or imported on a sub-interpreter + # We do this from python, since the C-module may not be reloaded and + # it is tidier organized. + _core.multiarray._multiarray_umath._reload_guard() + + # TODO: Remove the environment variable entirely now that it is "weak" + if (os.environ.get("NPY_PROMOTION_STATE", "weak") != "weak"): + warnings.warn( + "NPY_PROMOTION_STATE was a temporary feature for NumPy 2.0 " + "transition and is ignored after NumPy 2.2.", + UserWarning, stacklevel=2) + + # Tell PyInstaller where to find hook-numpy.py + def _pyinstaller_hooks_dir(): + from pathlib import Path + return [str(Path(__file__).with_name("_pyinstaller").resolve())] + + +# Remove symbols imported for internal use +del os, sys, warnings diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..28bbe31ca98a35eb6e576af2ca959d1cb4a148b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/__init__.pyi @@ -0,0 +1,6202 @@ +# ruff: noqa: I001 +import builtins +import sys +import mmap +import ctypes as ct +import array as _array +import datetime as dt +import inspect +from abc import abstractmethod +from types import EllipsisType, ModuleType, TracebackType, MappingProxyType, GenericAlias +from decimal import Decimal +from fractions import Fraction +from uuid import UUID + +import numpy as np +from numpy.__config__ import show as show_config +from numpy._pytesttester import PytestTester +from numpy._core._internal import _ctypes + +from numpy._typing import ( # type: ignore[deprecated] + # Arrays + ArrayLike, + NDArray, + _SupportsArray, + _NestedSequence, + _ArrayLike, + _ArrayLikeBool_co, + _ArrayLikeUInt_co, + _ArrayLikeInt, + _ArrayLikeInt_co, + _ArrayLikeFloat64_co, + _ArrayLikeFloat_co, + _ArrayLikeComplex128_co, + _ArrayLikeComplex_co, + _ArrayLikeNumber_co, + _ArrayLikeObject_co, + _ArrayLikeBytes_co, + _ArrayLikeStr_co, + _ArrayLikeString_co, + _ArrayLikeTD64_co, + _ArrayLikeDT64_co, + # DTypes + DTypeLike, + _DTypeLike, + _DTypeLikeVoid, + _VoidDTypeLike, + # Shapes + _AnyShape, + _Shape, + _ShapeLike, + # Scalars + _CharLike_co, + _IntLike_co, + _FloatLike_co, + _TD64Like_co, + _NumberLike_co, + _ScalarLike_co, + # `number` precision + NBitBase, + # NOTE: Do not remove the extended precision bit-types even if seemingly unused; + # they're used by the mypy plugin + _128Bit, + _96Bit, + _64Bit, + _32Bit, + _16Bit, + _8Bit, + _NBitByte, + _NBitShort, + _NBitIntC, + _NBitIntP, + _NBitLong, + _NBitLongLong, + _NBitHalf, + _NBitSingle, + _NBitDouble, + _NBitLongDouble, + # Character codes + _BoolCodes, + _UInt8Codes, + _UInt16Codes, + _UInt32Codes, + _UInt64Codes, + _Int8Codes, + _Int16Codes, + _Int32Codes, + _Int64Codes, + _Float16Codes, + _Float32Codes, + _Float64Codes, + _Complex64Codes, + _Complex128Codes, + _ByteCodes, + _ShortCodes, + _IntCCodes, + _IntPCodes, + _LongCodes, + _LongLongCodes, + _UByteCodes, + _UShortCodes, + _UIntCCodes, + _UIntPCodes, + _ULongCodes, + _ULongLongCodes, + _HalfCodes, + _SingleCodes, + _DoubleCodes, + _LongDoubleCodes, + _CSingleCodes, + _CDoubleCodes, + _CLongDoubleCodes, + _DT64Codes, + _TD64Codes, + _StrCodes, + _BytesCodes, + _VoidCodes, + _ObjectCodes, + _StringCodes, + _UnsignedIntegerCodes, + _SignedIntegerCodes, + _IntegerCodes, + _FloatingCodes, + _ComplexFloatingCodes, + _InexactCodes, + _CharacterCodes, + # Ufuncs + _UFunc_Nin1_Nout1, + _UFunc_Nin2_Nout1, + _UFunc_Nin1_Nout2, + _UFunc_Nin2_Nout2, + _GUFunc_Nin2_Nout1, +) + +# NOTE: Numpy's mypy plugin is used for removing the types unavailable to the specific platform +from numpy._typing._extended_precision import ( + float96, + float128, + complex192, + complex256, +) + +from numpy._array_api_info import __array_namespace_info__ + +from collections.abc import ( + Callable, + Iterable, + Iterator, + Mapping, + Sequence, +) + +if sys.version_info >= (3, 12): + from collections.abc import Buffer as _SupportsBuffer +else: + _SupportsBuffer: TypeAlias = ( + bytes + | bytearray + | memoryview + | _array.array[Any] + | mmap.mmap + | NDArray[Any] + | generic + ) + +from typing import ( + Any, + ClassVar, + Final, + Generic, + Literal as L, + LiteralString, + Never, + NoReturn, + Protocol, + Self, + SupportsComplex, + SupportsFloat, + SupportsInt, + SupportsIndex, + TypeAlias, + TypedDict, + final, + overload, + type_check_only, +) + +# NOTE: `typing_extensions` and `_typeshed` are always available in `.pyi` stubs, even +# if not available at runtime. This is because the `typeshed` stubs for the standard +# library include `typing_extensions` stubs: +# https://github.com/python/typeshed/blob/main/stdlib/typing_extensions.pyi +from _typeshed import Incomplete, StrOrBytesPath, SupportsFlush, SupportsLenAndGetItem, SupportsWrite +from typing_extensions import CapsuleType, TypeVar, deprecated, override + +from numpy import ( + char, + core, + ctypeslib, + dtypes, + exceptions, + f2py, + fft, + lib, + linalg, + ma, + polynomial, + random, + rec, + strings, + testing, + typing, +) + +# available through `__getattr__`, but not in `__all__` or `__dir__` +from numpy import ( + __config__ as __config__, + matlib as matlib, + matrixlib as matrixlib, + version as version, +) +if sys.version_info < (3, 12): + from numpy import distutils as distutils + +from numpy._core.records import ( + record, + recarray, +) + +from numpy._core.function_base import ( + linspace, + logspace, + geomspace, +) + +from numpy._core.fromnumeric import ( + take, + reshape, + choose, + repeat, + put, + swapaxes, + transpose, + matrix_transpose, + partition, + argpartition, + sort, + argsort, + argmax, + argmin, + searchsorted, + resize, + squeeze, + diagonal, + trace, + ravel, + nonzero, + shape, + compress, + clip, + sum, + all, + any, + cumsum, + cumulative_sum, + ptp, + max, + min, + amax, + amin, + prod, + cumprod, + cumulative_prod, + ndim, + size, + around, + round, + mean, + std, + var, +) + +from numpy._core._asarray import ( + require, +) + +from numpy._core._type_aliases import ( + sctypeDict, +) + +from numpy._core._ufunc_config import ( + seterr, + geterr, + setbufsize, + getbufsize, + seterrcall, + geterrcall, + errstate, +) + +from numpy._core.arrayprint import ( + set_printoptions, + get_printoptions, + array2string, + format_float_scientific, + format_float_positional, + array_repr, + array_str, + printoptions, +) + +from numpy._core.einsumfunc import ( + einsum, + einsum_path, +) +from numpy._core.getlimits import ( + finfo, + iinfo, +) + +from numpy._core.multiarray import ( + array, + empty_like, + empty, + zeros, + concatenate, + inner, + where, + lexsort, + can_cast, + min_scalar_type, + result_type, + dot, + vdot, + bincount, + copyto, + putmask, + packbits, + unpackbits, + shares_memory, + may_share_memory, + asarray, + asanyarray, + ascontiguousarray, + asfortranarray, + arange, + busday_count, + busday_offset, + datetime_as_string, + datetime_data, + frombuffer, + fromfile, + fromiter, + is_busday, + promote_types, + fromstring, + frompyfunc, + nested_iters, + flagsobj, +) + +from numpy._core.numeric import ( + zeros_like, + ones, + ones_like, + full, + full_like, + count_nonzero, + isfortran, + argwhere, + flatnonzero, + correlate, + convolve, + outer, + tensordot, + roll, + rollaxis, + moveaxis, + cross, + indices, + fromfunction, + isscalar, + binary_repr, + base_repr, + identity, + allclose, + isclose, + array_equal, + array_equiv, + astype, +) + +from numpy._core.numerictypes import ( + isdtype, + issubdtype, + ScalarType, + typecodes, +) + +from numpy._core.shape_base import ( + atleast_1d, + atleast_2d, + atleast_3d, + block, + hstack, + stack, + vstack, + unstack, +) + +from ._expired_attrs_2_0 import __expired_attributes__ as __expired_attributes__ +from ._globals import _CopyMode as _CopyMode +from ._globals import _NoValue as _NoValue, _NoValueType + +from numpy.lib import ( + scimath as emath, +) + +from numpy.lib._arraypad_impl import ( + pad, +) + +from numpy.lib._arraysetops_impl import ( + ediff1d, + intersect1d, + isin, + setdiff1d, + setxor1d, + union1d, + unique, + unique_all, + unique_counts, + unique_inverse, + unique_values, +) + +from numpy.lib._function_base_impl import ( # type: ignore[deprecated] + select, + piecewise, + trim_zeros, + copy, + iterable, + percentile, + diff, + gradient, + angle, + unwrap, + sort_complex, + flip, + rot90, + extract, + place, + asarray_chkfinite, + average, + digitize, + cov, + corrcoef, + median, + sinc, + hamming, + hanning, + bartlett, + blackman, + kaiser, + trapezoid, + i0, + meshgrid, + delete, + insert, + append, + interp, + quantile, + vectorize, +) + +from numpy.lib._histograms_impl import ( + histogram_bin_edges, + histogram, + histogramdd, +) + +from numpy.lib._index_tricks_impl import ( + ndenumerate, + ndindex, + ravel_multi_index, + unravel_index, + mgrid, + ogrid, + r_, + c_, + s_, + index_exp, + ix_, + fill_diagonal, + diag_indices, + diag_indices_from, +) + +from numpy.lib._nanfunctions_impl import ( + nansum, + nanmax, + nanmin, + nanargmax, + nanargmin, + nanmean, + nanmedian, + nanpercentile, + nanvar, + nanstd, + nanprod, + nancumsum, + nancumprod, + nanquantile, +) + +from numpy.lib._npyio_impl import ( + savetxt, + loadtxt, + genfromtxt, + load, + save, + savez, + savez_compressed, + fromregex, +) + +from numpy.lib._polynomial_impl import ( + poly, + roots, + polyint, + polyder, + polyadd, + polysub, + polymul, + polydiv, + polyval, + polyfit, +) + +from numpy.lib._shape_base_impl import ( # type: ignore[deprecated] + column_stack, + row_stack, + dstack, + array_split, + split, + hsplit, + vsplit, + dsplit, + apply_over_axes, + expand_dims, + apply_along_axis, + kron, + tile, + take_along_axis, + put_along_axis, +) + +from numpy.lib._stride_tricks_impl import ( + broadcast_to, + broadcast_arrays, + broadcast_shapes, +) + +from numpy.lib._twodim_base_impl import ( + diag, + diagflat, + eye, + fliplr, + flipud, + tri, + triu, + tril, + vander, + histogram2d, + mask_indices, + tril_indices, + tril_indices_from, + triu_indices, + triu_indices_from, +) + +from numpy.lib._type_check_impl import ( + mintypecode, + real, + imag, + iscomplex, + isreal, + iscomplexobj, + isrealobj, + nan_to_num, + real_if_close, + typename, + common_type, +) + +from numpy.lib._ufunclike_impl import ( + fix, + isposinf, + isneginf, +) + +from numpy.lib._utils_impl import ( + get_include, + info, + show_runtime, +) + +from numpy.matrixlib import ( + asmatrix, + bmat, + matrix, +) + +__all__ = [ # noqa: RUF022 + # __numpy_submodules__ + "char", "core", "ctypeslib", "dtypes", "exceptions", "f2py", "fft", "lib", "linalg", + "ma", "polynomial", "random", "rec", "strings", "test", "testing", "typing", + + # _core.__all__ + "abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2", "bitwise_invert", + "bitwise_left_shift", "bitwise_right_shift", "concat", "pow", "permute_dims", + "memmap", "sctypeDict", "record", "recarray", + + # _core.numeric.__all__ + "newaxis", "ndarray", "flatiter", "nditer", "nested_iters", "ufunc", "arange", + "array", "asarray", "asanyarray", "ascontiguousarray", "asfortranarray", "zeros", + "count_nonzero", "empty", "broadcast", "dtype", "fromstring", "fromfile", + "frombuffer", "from_dlpack", "where", "argwhere", "copyto", "concatenate", + "lexsort", "astype", "can_cast", "promote_types", "min_scalar_type", "result_type", + "isfortran", "empty_like", "zeros_like", "ones_like", "correlate", "convolve", + "inner", "dot", "outer", "vdot", "roll", "rollaxis", "moveaxis", "cross", + "tensordot", "little_endian", "fromiter", "array_equal", "array_equiv", "indices", + "fromfunction", "isclose", "isscalar", "binary_repr", "base_repr", "ones", + "identity", "allclose", "putmask", "flatnonzero", "inf", "nan", "False_", "True_", + "bitwise_not", "full", "full_like", "matmul", "vecdot", "vecmat", + "shares_memory", "may_share_memory", + "all", "amax", "amin", "any", "argmax", "argmin", "argpartition", "argsort", + "around", "choose", "clip", "compress", "cumprod", "cumsum", "cumulative_prod", + "cumulative_sum", "diagonal", "mean", "max", "min", "matrix_transpose", "ndim", + "nonzero", "partition", "prod", "ptp", "put", "ravel", "repeat", "reshape", + "resize", "round", "searchsorted", "shape", "size", "sort", "squeeze", "std", "sum", + "swapaxes", "take", "trace", "transpose", "var", + "absolute", "add", "arccos", "arccosh", "arcsin", "arcsinh", "arctan", "arctan2", + "arctanh", "bitwise_and", "bitwise_or", "bitwise_xor", "cbrt", "ceil", "conj", + "conjugate", "copysign", "cos", "cosh", "bitwise_count", "deg2rad", "degrees", + "divide", "divmod", "e", "equal", "euler_gamma", "exp", "exp2", "expm1", "fabs", + "floor", "floor_divide", "float_power", "fmax", "fmin", "fmod", "frexp", + "frompyfunc", "gcd", "greater", "greater_equal", "heaviside", "hypot", "invert", + "isfinite", "isinf", "isnan", "isnat", "lcm", "ldexp", "left_shift", "less", + "less_equal", "log", "log10", "log1p", "log2", "logaddexp", "logaddexp2", + "logical_and", "logical_not", "logical_or", "logical_xor", "matvec", "maximum", "minimum", + "mod", "modf", "multiply", "negative", "nextafter", "not_equal", "pi", "positive", + "power", "rad2deg", "radians", "reciprocal", "remainder", "right_shift", "rint", + "sign", "signbit", "sin", "sinh", "spacing", "sqrt", "square", "subtract", "tan", + "tanh", "true_divide", "trunc", "ScalarType", "typecodes", "issubdtype", + "datetime_data", "datetime_as_string", "busday_offset", "busday_count", "is_busday", + "busdaycalendar", "isdtype", + "complexfloating", "character", "unsignedinteger", "inexact", "generic", "floating", + "integer", "signedinteger", "number", "flexible", "bool", "float16", "float32", + "float64", "longdouble", "complex64", "complex128", "clongdouble", + "bytes_", "str_", "void", "object_", "datetime64", "timedelta64", "int8", "byte", + "uint8", "ubyte", "int16", "short", "uint16", "ushort", "int32", "intc", "uint32", + "uintc", "int64", "long", "uint64", "ulong", "longlong", "ulonglong", "intp", + "uintp", "double", "cdouble", "single", "csingle", "half", "bool_", "int_", "uint", + "float96", "float128", "complex192", "complex256", + "array2string", "array_str", "array_repr", "set_printoptions", "get_printoptions", + "printoptions", "format_float_positional", "format_float_scientific", "require", + "seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall", + "errstate", + # _core.function_base.__all__ + "logspace", "linspace", "geomspace", + # _core.getlimits.__all__ + "finfo", "iinfo", + # _core.shape_base.__all__ + "atleast_1d", "atleast_2d", "atleast_3d", "block", "hstack", "stack", "unstack", + "vstack", + # _core.einsumfunc.__all__ + "einsum", "einsum_path", + # matrixlib.__all__ + "matrix", "bmat", "asmatrix", + # lib._histograms_impl.__all__ + "histogram", "histogramdd", "histogram_bin_edges", + # lib._nanfunctions_impl.__all__ + "nansum", "nanmax", "nanmin", "nanargmax", "nanargmin", "nanmean", "nanmedian", + "nanpercentile", "nanvar", "nanstd", "nanprod", "nancumsum", "nancumprod", + "nanquantile", + # lib._function_base_impl.__all__ + "select", "piecewise", "trim_zeros", "copy", "iterable", "percentile", "diff", + "gradient", "angle", "unwrap", "sort_complex", "flip", "rot90", "extract", "place", + "vectorize", "asarray_chkfinite", "average", "bincount", "digitize", "cov", + "corrcoef", "median", "sinc", "hamming", "hanning", "bartlett", "blackman", + "kaiser", "trapezoid", "i0", "meshgrid", "delete", "insert", "append", + "interp", "quantile", + # lib._twodim_base_impl.__all__ + "diag", "diagflat", "eye", "fliplr", "flipud", "tri", "triu", "tril", "vander", + "histogram2d", "mask_indices", "tril_indices", "tril_indices_from", "triu_indices", + "triu_indices_from", + # lib._shape_base_impl.__all__ + "column_stack", "dstack", "array_split", "split", "hsplit", "vsplit", "dsplit", + "apply_over_axes", "expand_dims", "apply_along_axis", "kron", "tile", + "take_along_axis", "put_along_axis", "row_stack", + # lib._type_check_impl.__all__ + "iscomplexobj", "isrealobj", "imag", "iscomplex", "isreal", "nan_to_num", "real", + "real_if_close", "typename", "mintypecode", "common_type", + # lib._arraysetops_impl.__all__ + "ediff1d", "intersect1d", "isin", "setdiff1d", "setxor1d", "union1d", + "unique", "unique_all", "unique_counts", "unique_inverse", "unique_values", + # lib._ufunclike_impl.__all__ + "fix", "isneginf", "isposinf", + # lib._arraypad_impl.__all__ + "pad", + # lib._utils_impl.__all__ + "get_include", "info", "show_runtime", + # lib._stride_tricks_impl.__all__ + "broadcast_to", "broadcast_arrays", "broadcast_shapes", + # lib._polynomial_impl.__all__ + "poly", "roots", "polyint", "polyder", "polyadd", "polysub", "polymul", "polydiv", + "polyval", "poly1d", "polyfit", + # lib._npyio_impl.__all__ + "savetxt", "loadtxt", "genfromtxt", "load", "save", "savez", "savez_compressed", + "packbits", "unpackbits", "fromregex", + # lib._index_tricks_impl.__all__ + "ravel_multi_index", "unravel_index", "mgrid", "ogrid", "r_", "c_", "s_", + "index_exp", "ix_", "ndenumerate", "ndindex", "fill_diagonal", "diag_indices", + "diag_indices_from", + + # __init__.__all__ + "emath", "show_config", "__version__", "__array_namespace_info__", +] # fmt: skip + +### Constrained types (for internal use only) +# Only use these for functions; never as generic type parameter. + +_AnyStr = TypeVar("_AnyStr", LiteralString, str, bytes) +_AnyShapeT = TypeVar( + "_AnyShapeT", + tuple[()], # 0-d + tuple[int], # 1-d + tuple[int, int], # 2-d + tuple[int, int, int], # 3-d + tuple[int, int, int, int], # 4-d + tuple[int, int, int, int, int], # 5-d + tuple[int, int, int, int, int, int], # 6-d + tuple[int, int, int, int, int, int, int], # 7-d + tuple[int, int, int, int, int, int, int, int], # 8-d + tuple[int, ...], # N-d +) +_AnyTD64Item = TypeVar("_AnyTD64Item", dt.timedelta, int, None, dt.timedelta | int | None) +_AnyDT64Arg = TypeVar("_AnyDT64Arg", dt.datetime, dt.date, None) +_AnyDT64Item = TypeVar("_AnyDT64Item", dt.datetime, dt.date, int, None, dt.date, int | None) +_AnyDate = TypeVar("_AnyDate", dt.date, dt.datetime) +_AnyDateOrTime = TypeVar("_AnyDateOrTime", dt.date, dt.datetime, dt.timedelta) + +### Type parameters (for internal use only) + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) +_RealT_co = TypeVar("_RealT_co", covariant=True) +_ImagT_co = TypeVar("_ImagT_co", covariant=True) + +_DTypeT = TypeVar("_DTypeT", bound=dtype) +_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, default=dtype, covariant=True) +_FlexDTypeT = TypeVar("_FlexDTypeT", bound=dtype[flexible]) + +_ArrayT = TypeVar("_ArrayT", bound=ndarray) +_ArrayT_co = TypeVar("_ArrayT_co", bound=ndarray, default=ndarray, covariant=True) +_BoolArrayT = TypeVar("_BoolArrayT", bound=NDArray[np.bool]) +_IntegerArrayT = TypeVar("_IntegerArrayT", bound=NDArray[integer]) +_IntegralArrayT = TypeVar("_IntegralArrayT", bound=NDArray[np.bool | integer | object_]) +_FloatingArrayT = TypeVar("_FloatingArrayT", bound=NDArray[floating]) +_FloatingTimedeltaArrayT = TypeVar("_FloatingTimedeltaArrayT", bound=NDArray[floating | timedelta64]) +_ComplexFloatingArrayT = TypeVar("_ComplexFloatingArrayT", bound=NDArray[complexfloating]) +_InexactArrayT = TypeVar("_InexactArrayT", bound=NDArray[inexact]) +_InexactTimedeltaArrayT = TypeVar("_InexactTimedeltaArrayT", bound=NDArray[inexact | timedelta64]) +_NumberArrayT = TypeVar("_NumberArrayT", bound=NDArray[number]) +_NumberCharacterArrayT = TypeVar("_NumberCharacterArrayT", bound=ndarray[Any, dtype[number | character] | dtypes.StringDType]) +_TimedeltaArrayT = TypeVar("_TimedeltaArrayT", bound=NDArray[timedelta64]) +_TimeArrayT = TypeVar("_TimeArrayT", bound=NDArray[datetime64 | timedelta64]) +_ObjectArrayT = TypeVar("_ObjectArrayT", bound=NDArray[object_]) +_BytesArrayT = TypeVar("_BytesArrayT", bound=NDArray[bytes_]) +_StringArrayT = TypeVar("_StringArrayT", bound=ndarray[Any, dtype[str_] | dtypes.StringDType]) +_RealArrayT = TypeVar("_RealArrayT", bound=NDArray[floating | integer | timedelta64 | np.bool | object_]) +_NumericArrayT = TypeVar("_NumericArrayT", bound=NDArray[number | timedelta64 | object_]) + +_ShapeT = TypeVar("_ShapeT", bound=_Shape) +_Shape1T = TypeVar("_Shape1T", bound=tuple[int, *tuple[int, ...]]) +_ShapeT_co = TypeVar("_ShapeT_co", bound=_Shape, default=_AnyShape, covariant=True) +_2DShapeT_co = TypeVar("_2DShapeT_co", bound=_2D, default=_2D, covariant=True) +_1NShapeT = TypeVar("_1NShapeT", bound=tuple[L[1], *tuple[L[1], ...]]) # (1,) | (1, 1) | (1, 1, 1) | ... + +_ScalarT = TypeVar("_ScalarT", bound=generic) +_ScalarT_co = TypeVar("_ScalarT_co", bound=generic, default=Any, covariant=True) +_NumberT = TypeVar("_NumberT", bound=number) +_InexactT = TypeVar("_InexactT", bound=inexact) +_RealNumberT = TypeVar("_RealNumberT", bound=floating | integer) +_IntegerT = TypeVar("_IntegerT", bound=integer) +_NonObjectScalarT = TypeVar("_NonObjectScalarT", bound=np.bool | number | flexible | datetime64 | timedelta64) + +_NBit = TypeVar("_NBit", bound=NBitBase, default=Any) # pyright: ignore[reportDeprecated] +_NBit1 = TypeVar("_NBit1", bound=NBitBase, default=Any) # pyright: ignore[reportDeprecated] +_NBit2 = TypeVar("_NBit2", bound=NBitBase, default=_NBit1) # pyright: ignore[reportDeprecated] + +_ItemT_co = TypeVar("_ItemT_co", default=Any, covariant=True) +_BoolItemT = TypeVar("_BoolItemT", bound=builtins.bool) +_BoolItemT_co = TypeVar("_BoolItemT_co", bound=builtins.bool, default=builtins.bool, covariant=True) +_NumberItemT_co = TypeVar("_NumberItemT_co", bound=complex, default=int | float | complex, covariant=True) +_InexactItemT_co = TypeVar("_InexactItemT_co", bound=complex, default=float | complex, covariant=True) +_FlexibleItemT_co = TypeVar( + "_FlexibleItemT_co", + bound=_CharLike_co | tuple[Any, ...], + default=_CharLike_co | tuple[Any, ...], + covariant=True, +) +_CharacterItemT_co = TypeVar("_CharacterItemT_co", bound=_CharLike_co, default=_CharLike_co, covariant=True) +_TD64ItemT_co = TypeVar("_TD64ItemT_co", bound=dt.timedelta | int | None, default=dt.timedelta | int | None, covariant=True) +_DT64ItemT_co = TypeVar("_DT64ItemT_co", bound=dt.date | int | None, default=dt.date | int | None, covariant=True) +_TD64UnitT = TypeVar("_TD64UnitT", bound=_TD64Unit, default=_TD64Unit) +_BoolOrIntArrayT = TypeVar("_BoolOrIntArrayT", bound=NDArray[integer | np.bool]) + +### Type Aliases (for internal use only) + +_Falsy: TypeAlias = L[False, 0] | np.bool[L[False]] +_Truthy: TypeAlias = L[True, 1] | np.bool[L[True]] + +_1D: TypeAlias = tuple[int] +_2D: TypeAlias = tuple[int, int] +_2Tuple: TypeAlias = tuple[_T, _T] + +_ArrayUInt_co: TypeAlias = NDArray[unsignedinteger | np.bool] +_ArrayInt_co: TypeAlias = NDArray[integer | np.bool] +_ArrayFloat64_co: TypeAlias = NDArray[floating[_64Bit] | float32 | float16 | integer | np.bool] +_ArrayFloat_co: TypeAlias = NDArray[floating | integer | np.bool] +_ArrayComplex128_co: TypeAlias = NDArray[number[_64Bit] | number[_32Bit] | float16 | integer | np.bool] +_ArrayComplex_co: TypeAlias = NDArray[inexact | integer | np.bool] +_ArrayNumber_co: TypeAlias = NDArray[number | np.bool] +_ArrayTD64_co: TypeAlias = NDArray[timedelta64 | integer | np.bool] + +_Float64_co: TypeAlias = float | floating[_64Bit] | float32 | float16 | integer | np.bool +_Complex64_co: TypeAlias = number[_32Bit] | number[_16Bit] | number[_8Bit] | builtins.bool | np.bool +_Complex128_co: TypeAlias = complex | number[_64Bit] | _Complex64_co + +_ToIndex: TypeAlias = SupportsIndex | slice | EllipsisType | _ArrayLikeInt_co | None +_ToIndices: TypeAlias = _ToIndex | tuple[_ToIndex, ...] + +_UnsignedIntegerCType: TypeAlias = type[ + ct.c_uint8 | ct.c_uint16 | ct.c_uint32 | ct.c_uint64 + | ct.c_ushort | ct.c_uint | ct.c_ulong | ct.c_ulonglong + | ct.c_size_t | ct.c_void_p +] # fmt: skip +_SignedIntegerCType: TypeAlias = type[ + ct.c_int8 | ct.c_int16 | ct.c_int32 | ct.c_int64 + | ct.c_short | ct.c_int | ct.c_long | ct.c_longlong + | ct.c_ssize_t +] # fmt: skip +_FloatingCType: TypeAlias = type[ct.c_float | ct.c_double | ct.c_longdouble] +_IntegerCType: TypeAlias = _UnsignedIntegerCType | _SignedIntegerCType + +# some commonly used builtin types that are known to result in a +# `dtype[object_]`, when their *type* is passed to the `dtype` constructor +# NOTE: `builtins.object` should not be included here +_BuiltinObjectLike: TypeAlias = ( + slice | Decimal | Fraction | UUID + | dt.date | dt.time | dt.timedelta | dt.tzinfo + | tuple[Any, ...] | list[Any] | set[Any] | frozenset[Any] | dict[Any, Any] +) # fmt: skip + +# Introduce an alias for `dtype` to avoid naming conflicts. +_dtype: TypeAlias = dtype[_ScalarT] + +_ByteOrderChar: TypeAlias = L["<", ">", "=", "|"] +# can be anything, is case-insensitive, and only the first character matters +_ByteOrder: TypeAlias = L[ + "S", # swap the current order (default) + "<", "L", "little", # little-endian + ">", "B", "big", # big endian + "=", "N", "native", # native order + "|", "I", # ignore +] # fmt: skip +_DTypeKind: TypeAlias = L[ + "b", # boolean + "i", # signed integer + "u", # unsigned integer + "f", # floating-point + "c", # complex floating-point + "m", # timedelta64 + "M", # datetime64 + "O", # python object + "S", # byte-string (fixed-width) + "U", # unicode-string (fixed-width) + "V", # void + "T", # unicode-string (variable-width) +] +_DTypeChar: TypeAlias = L[ + "?", # bool + "b", # byte + "B", # ubyte + "h", # short + "H", # ushort + "i", # intc + "I", # uintc + "l", # long + "L", # ulong + "q", # longlong + "Q", # ulonglong + "e", # half + "f", # single + "d", # double + "g", # longdouble + "F", # csingle + "D", # cdouble + "G", # clongdouble + "O", # object + "S", # bytes_ (S0) + "a", # bytes_ (deprecated) + "U", # str_ + "V", # void + "M", # datetime64 + "m", # timedelta64 + "c", # bytes_ (S1) + "T", # StringDType +] +_DTypeNum: TypeAlias = L[ + 0, # bool + 1, # byte + 2, # ubyte + 3, # short + 4, # ushort + 5, # intc + 6, # uintc + 7, # long + 8, # ulong + 9, # longlong + 10, # ulonglong + 23, # half + 11, # single + 12, # double + 13, # longdouble + 14, # csingle + 15, # cdouble + 16, # clongdouble + 17, # object + 18, # bytes_ + 19, # str_ + 20, # void + 21, # datetime64 + 22, # timedelta64 + 25, # no type + 256, # user-defined + 2056, # StringDType +] +_DTypeBuiltinKind: TypeAlias = L[0, 1, 2] + +_ArrayAPIVersion: TypeAlias = L["2021.12", "2022.12", "2023.12", "2024.12"] + +_CastingKind: TypeAlias = L["no", "equiv", "safe", "same_kind", "same_value", "unsafe"] + +_OrderKACF: TypeAlias = L["K", "A", "C", "F"] | None +_OrderACF: TypeAlias = L["A", "C", "F"] | None +_OrderCF: TypeAlias = L["C", "F"] | None # noqa: PYI047 + +_ModeKind: TypeAlias = L["raise", "wrap", "clip"] +_PartitionKind: TypeAlias = L["introselect"] +# in practice, only the first case-insensitive character is considered (so e.g. +# "QuantumSort3000" will be interpreted as quicksort). +_SortKind: TypeAlias = L[ + "Q", "quick", "quicksort", + "M", "merge", "mergesort", + "H", "heap", "heapsort", + "S", "stable", "stablesort", +] +_SortSide: TypeAlias = L["left", "right"] + +_ConvertibleToInt: TypeAlias = SupportsInt | SupportsIndex | _CharLike_co +_ConvertibleToFloat: TypeAlias = SupportsFloat | SupportsIndex | _CharLike_co +_ConvertibleToComplex: TypeAlias = SupportsComplex | SupportsFloat | SupportsIndex | _CharLike_co +_ConvertibleToTD64: TypeAlias = dt.timedelta | int | _CharLike_co | character | number | timedelta64 | np.bool | None +_ConvertibleToDT64: TypeAlias = dt.date | int | _CharLike_co | character | number | datetime64 | np.bool | None + +_NDIterFlagsKind: TypeAlias = L[ + "buffered", + "c_index", + "copy_if_overlap", + "common_dtype", + "delay_bufalloc", + "external_loop", + "f_index", + "grow_inner", "growinner", + "multi_index", + "ranged", + "refs_ok", + "reduce_ok", + "zerosize_ok", +] +_NDIterFlagsOp: TypeAlias = L[ + "aligned", + "allocate", + "arraymask", + "copy", + "config", + "nbo", + "no_subtype", + "no_broadcast", + "overlap_assume_elementwise", + "readonly", + "readwrite", + "updateifcopy", + "virtual", + "writeonly", + "writemasked", +] + +_MemMapModeKind: TypeAlias = L[ + "readonly", "r", + "copyonwrite", "c", + "readwrite", "r+", + "write", "w+", +] + +_DT64Date: TypeAlias = _HasDateAttributes | L["TODAY", "today", b"TODAY", b"today"] +_DT64Now: TypeAlias = L["NOW", "now", b"NOW", b"now"] +_NaTValue: TypeAlias = L["NAT", "NaT", "nat", b"NAT", b"NaT", b"nat"] + +_MonthUnit: TypeAlias = L["Y", "M", b"Y", b"M"] +_DayUnit: TypeAlias = L["W", "D", b"W", b"D"] +_DateUnit: TypeAlias = L[_MonthUnit, _DayUnit] +_NativeTimeUnit: TypeAlias = L["h", "m", "s", "ms", "us", "μs", b"h", b"m", b"s", b"ms", b"us"] +_IntTimeUnit: TypeAlias = L["ns", "ps", "fs", "as", b"ns", b"ps", b"fs", b"as"] +_TimeUnit: TypeAlias = L[_NativeTimeUnit, _IntTimeUnit] +_NativeTD64Unit: TypeAlias = L[_DayUnit, _NativeTimeUnit] +_IntTD64Unit: TypeAlias = L[_MonthUnit, _IntTimeUnit] +_TD64Unit: TypeAlias = L[_DateUnit, _TimeUnit] +_TimeUnitSpec: TypeAlias = _TD64UnitT | tuple[_TD64UnitT, SupportsIndex] + +### TypedDict's (for internal use only) + +@type_check_only +class _FormerAttrsDict(TypedDict): + object: LiteralString + float: LiteralString + complex: LiteralString + str: LiteralString + int: LiteralString + +### Protocols (for internal use only) + +@final +@type_check_only +class _SupportsLT(Protocol): + def __lt__(self, other: Any, /) -> Any: ... + +@final +@type_check_only +class _SupportsLE(Protocol): + def __le__(self, other: Any, /) -> Any: ... + +@final +@type_check_only +class _SupportsGT(Protocol): + def __gt__(self, other: Any, /) -> Any: ... + +@final +@type_check_only +class _SupportsGE(Protocol): + def __ge__(self, other: Any, /) -> Any: ... + +@type_check_only +class _SupportsFileMethods(SupportsFlush, Protocol): + # Protocol for representing file-like-objects accepted by `ndarray.tofile` and `fromfile` + def fileno(self) -> SupportsIndex: ... + def tell(self) -> SupportsIndex: ... + def seek(self, offset: int, whence: int, /) -> object: ... + +@type_check_only +class _SupportsFileMethodsRW(SupportsWrite[bytes], _SupportsFileMethods, Protocol): ... + +@type_check_only +class _SupportsDLPack(Protocol[_T_contra]): + def __dlpack__(self, /, *, stream: _T_contra | None = None) -> CapsuleType: ... + +@type_check_only +class _HasDType(Protocol[_T_co]): + @property + def dtype(self, /) -> _T_co: ... + +@type_check_only +class _HasRealAndImag(Protocol[_RealT_co, _ImagT_co]): + @property + def real(self, /) -> _RealT_co: ... + @property + def imag(self, /) -> _ImagT_co: ... + +@type_check_only +class _HasTypeWithRealAndImag(Protocol[_RealT_co, _ImagT_co]): + @property + def type(self, /) -> type[_HasRealAndImag[_RealT_co, _ImagT_co]]: ... + +@type_check_only +class _HasDTypeWithRealAndImag(Protocol[_RealT_co, _ImagT_co]): + @property + def dtype(self, /) -> _HasTypeWithRealAndImag[_RealT_co, _ImagT_co]: ... + +@type_check_only +class _HasDateAttributes(Protocol): + # The `datetime64` constructors requires an object with the three attributes below, + # and thus supports datetime duck typing + @property + def day(self) -> int: ... + @property + def month(self) -> int: ... + @property + def year(self) -> int: ... + +### Mixins (for internal use only) + +@type_check_only +class _RealMixin: + @property + def real(self) -> Self: ... + @property + def imag(self) -> Self: ... + +@type_check_only +class _RoundMixin: + @overload + def __round__(self, /, ndigits: None = None) -> int: ... + @overload + def __round__(self, /, ndigits: SupportsIndex) -> Self: ... + +@type_check_only +class _IntegralMixin(_RealMixin): + @property + def numerator(self) -> Self: ... + @property + def denominator(self) -> L[1]: ... + + def is_integer(self, /) -> L[True]: ... + +### Public API + +__version__: Final[LiteralString] = ... + +e: Final[float] = ... +euler_gamma: Final[float] = ... +pi: Final[float] = ... +inf: Final[float] = ... +nan: Final[float] = ... +little_endian: Final[builtins.bool] = ... +False_: Final[np.bool[L[False]]] = ... +True_: Final[np.bool[L[True]]] = ... +newaxis: Final[None] = None + +# not in __all__ +__NUMPY_SETUP__: Final[L[False]] = False +__numpy_submodules__: Final[set[LiteralString]] = ... +__former_attrs__: Final[_FormerAttrsDict] = ... +__future_scalars__: Final[set[L["bytes", "str", "object"]]] = ... +__array_api_version__: Final[L["2024.12"]] = "2024.12" +test: Final[PytestTester] = ... + +@type_check_only +class _DTypeMeta(type): + @property + def type(cls, /) -> type[generic] | None: ... + @property + def _abstract(cls, /) -> bool: ... + @property + def _is_numeric(cls, /) -> bool: ... + @property + def _parametric(cls, /) -> bool: ... + @property + def _legacy(cls, /) -> bool: ... + +@final +class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta): + names: tuple[builtins.str, ...] | None + def __hash__(self) -> int: ... + + # `None` results in the default dtype + @overload + def __new__( + cls, + dtype: type[float64 | ct.c_double] | _Float64Codes | _DoubleCodes | None, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ... + ) -> dtype[float64]: ... + + # Overload for `dtype` instances, scalar types, and instances that have a + # `dtype: dtype[_ScalarT]` attribute + @overload + def __new__( + cls, + dtype: _DTypeLike[_ScalarT], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[_ScalarT]: ... + + # Builtin types + # + # NOTE: Typecheckers act as if `bool <: int <: float <: complex <: object`, + # even though at runtime `int`, `float`, and `complex` aren't subtypes.. + # This makes it impossible to express e.g. "a float that isn't an int", + # since type checkers treat `_: float` like `_: float | int`. + # + # For more details, see: + # - https://github.com/numpy/numpy/issues/27032#issuecomment-2278958251 + # - https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex + @overload + def __new__( + cls, + dtype: type[builtins.bool | np.bool | ct.c_bool] | _BoolCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[np.bool]: ... + @overload + def __new__( + cls, + dtype: type[int], # also accepts `type[builtins.bool]` + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[int_ | np.bool]: ... + @overload + def __new__( + cls, + dtype: type[float], # also accepts `type[int | bool]` + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[float64 | int_ | np.bool]: ... + @overload + def __new__( + cls, + dtype: type[complex], # also accepts `type[float | int | bool]` + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[complex128 | float64 | int_ | np.bool]: ... + @overload + def __new__( + cls, + dtype: type[bytes | ct.c_char] | _BytesCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[bytes_]: ... + @overload + def __new__( + cls, + dtype: type[str] | _StrCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[str_]: ... + # NOTE: These `memoryview` overloads assume PEP 688, which requires mypy to + # be run with the (undocumented) `--disable-memoryview-promotion` flag, + # This will be the default in a future mypy release, see: + # https://github.com/python/mypy/issues/15313 + # Pyright / Pylance requires setting `disableBytesTypePromotions=true`, + # which is the default in strict mode + @overload + def __new__( + cls, + dtype: type[void | memoryview] | _VoidDTypeLike | _VoidCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[void]: ... + # NOTE: `_: type[object]` would also accept e.g. `type[object | complex]`, + # and is therefore not included here + @overload + def __new__( + cls, + dtype: type[object_ | _BuiltinObjectLike | ct.py_object[Any]] | _ObjectCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[object_]: ... + + # `unsignedinteger` string-based representations and ctypes + @overload + def __new__( + cls, + dtype: _UInt8Codes | _UByteCodes | type[ct.c_uint8 | ct.c_ubyte], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uint8]: ... + @overload + def __new__( + cls, + dtype: _UInt16Codes | _UShortCodes | type[ct.c_uint16 | ct.c_ushort], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uint16]: ... + @overload + def __new__( + cls, + dtype: _UInt32Codes | _UIntCCodes | type[ct.c_uint32 | ct.c_uint], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uint32]: ... + @overload + def __new__( + cls, + dtype: _UInt64Codes | _ULongLongCodes | type[ct.c_uint64 | ct.c_ulonglong], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uint64]: ... + @overload + def __new__( + cls, + dtype: _UIntPCodes | type[ct.c_void_p | ct.c_size_t], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[uintp]: ... + @overload + def __new__( + cls, + dtype: _ULongCodes | type[ct.c_ulong], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[ulong]: ... + + # `signedinteger` string-based representations and ctypes + @overload + def __new__( + cls, + dtype: _Int8Codes | _ByteCodes | type[ct.c_int8 | ct.c_byte], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[int8]: ... + @overload + def __new__( + cls, + dtype: _Int16Codes | _ShortCodes | type[ct.c_int16 | ct.c_short], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[int16]: ... + @overload + def __new__( + cls, + dtype: _Int32Codes | _IntCCodes | type[ct.c_int32 | ct.c_int], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[int32]: ... + @overload + def __new__( + cls, + dtype: _Int64Codes | _LongLongCodes | type[ct.c_int64 | ct.c_longlong], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[int64]: ... + @overload + def __new__( + cls, + dtype: _IntPCodes | type[intp | ct.c_ssize_t], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[intp]: ... + @overload + def __new__( + cls, + dtype: _LongCodes | type[ct.c_long], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[long]: ... + + # `floating` string-based representations and ctypes + @overload + def __new__( + cls, + dtype: _Float16Codes | _HalfCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[float16]: ... + @overload + def __new__( + cls, + dtype: _Float32Codes | _SingleCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[float32]: ... + # float64 codes are covered by overload 1 + @overload + def __new__( + cls, + dtype: _LongDoubleCodes | type[ct.c_longdouble], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[longdouble]: ... + + # `complexfloating` string-based representations + @overload + def __new__( + cls, + dtype: _Complex64Codes | _CSingleCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[complex64]: ... + @overload + def __new__( + cls, + dtype: _Complex128Codes | _CDoubleCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[complex128]: ... + @overload + def __new__( + cls, + dtype: _CLongDoubleCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[clongdouble]: ... + + # Miscellaneous string-based representations and ctypes + @overload + def __new__( + cls, + dtype: _TD64Codes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[timedelta64]: ... + @overload + def __new__( + cls, + dtype: _DT64Codes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[datetime64]: ... + + # `StringDType` requires special treatment because it has no scalar type + @overload + def __new__( + cls, + dtype: dtypes.StringDType | _StringCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtypes.StringDType: ... + + # Combined char-codes and ctypes, analogous to the scalar-type hierarchy + @overload + def __new__( + cls, + dtype: _UnsignedIntegerCodes | _UnsignedIntegerCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[unsignedinteger]: ... + @overload + def __new__( + cls, + dtype: _SignedIntegerCodes | _SignedIntegerCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[signedinteger]: ... + @overload + def __new__( + cls, + dtype: _IntegerCodes | _IntegerCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[integer]: ... + @overload + def __new__( + cls, + dtype: _FloatingCodes | _FloatingCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[floating]: ... + @overload + def __new__( + cls, + dtype: _ComplexFloatingCodes, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[complexfloating]: ... + @overload + def __new__( + cls, + dtype: _InexactCodes | _FloatingCType, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[inexact]: ... + @overload + def __new__( + cls, + dtype: _CharacterCodes | type[bytes | builtins.str | ct.c_char], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[str, Any] = ..., + ) -> dtype[character]: ... + + # Handle strings that can't be expressed as literals; i.e. "S1", "S2", ... + @overload + def __new__( + cls, + dtype: builtins.str, + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype: ... + + # Catch-all overload for object-likes + # NOTE: `object_ | Any` is NOT equivalent to `Any`. It is specified to behave + # like a "sum type" (a.k.a. variant type, discriminated union, or tagged union). + # So the union of a type and `Any` is not the same "union type" that all other + # unions are (by definition). + # https://typing.python.org/en/latest/spec/concepts.html#union-types + @overload + def __new__( + cls, + dtype: type[object], + align: builtins.bool = False, + copy: builtins.bool = False, + *, + metadata: dict[builtins.str, Any] = ..., + ) -> dtype[object_ | Any]: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + @overload + def __getitem__(self: dtype[void], key: list[builtins.str], /) -> dtype[void]: ... + @overload + def __getitem__(self: dtype[void], key: builtins.str | SupportsIndex, /) -> dtype: ... + + # NOTE: In the future 1-based multiplications will also yield `flexible` dtypes + @overload + def __mul__(self: _DTypeT, value: L[1], /) -> _DTypeT: ... + @overload + def __mul__(self: _FlexDTypeT, value: SupportsIndex, /) -> _FlexDTypeT: ... + @overload + def __mul__(self, value: SupportsIndex, /) -> dtype[void]: ... + + # NOTE: `__rmul__` seems to be broken when used in combination with + # literals as of mypy 0.902. Set the return-type to `dtype` for + # now for non-flexible dtypes. + @overload + def __rmul__(self: _FlexDTypeT, value: SupportsIndex, /) -> _FlexDTypeT: ... + @overload + def __rmul__(self, value: SupportsIndex, /) -> dtype: ... + + def __gt__(self, other: DTypeLike | None, /) -> builtins.bool: ... + def __ge__(self, other: DTypeLike | None, /) -> builtins.bool: ... + def __lt__(self, other: DTypeLike | None, /) -> builtins.bool: ... + def __le__(self, other: DTypeLike | None, /) -> builtins.bool: ... + + # Explicitly defined `__eq__` and `__ne__` to get around mypy's + # `strict_equality` option; even though their signatures are + # identical to their `object`-based counterpart + def __eq__(self, other: Any, /) -> builtins.bool: ... + def __ne__(self, other: Any, /) -> builtins.bool: ... + + @property + def alignment(self) -> int: ... + @property + def base(self) -> dtype: ... + @property + def byteorder(self) -> _ByteOrderChar: ... + @property + def char(self) -> _DTypeChar: ... + @property + def descr(self) -> list[tuple[LiteralString, LiteralString] | tuple[LiteralString, LiteralString, _Shape]]: ... + @property + def fields(self,) -> MappingProxyType[LiteralString, tuple[dtype, int] | tuple[dtype, int, Any]] | None: ... + @property + def flags(self) -> int: ... + @property + def hasobject(self) -> builtins.bool: ... + @property + def isbuiltin(self) -> _DTypeBuiltinKind: ... + @property + def isnative(self) -> builtins.bool: ... + @property + def isalignedstruct(self) -> builtins.bool: ... + @property + def itemsize(self) -> int: ... + @property + def kind(self) -> _DTypeKind: ... + @property + def metadata(self) -> MappingProxyType[builtins.str, Any] | None: ... + @property + def name(self) -> LiteralString: ... + @property + def num(self) -> _DTypeNum: ... + @property + def shape(self) -> _AnyShape: ... + @property + def ndim(self) -> int: ... + @property + def subdtype(self) -> tuple[dtype, _AnyShape] | None: ... + def newbyteorder(self, new_order: _ByteOrder = ..., /) -> Self: ... + @property + def str(self) -> LiteralString: ... + @property + def type(self) -> type[_ScalarT_co]: ... + +@final +class flatiter(Generic[_ArrayT_co]): + __hash__: ClassVar[None] = None # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride] + + @property + def base(self, /) -> _ArrayT_co: ... + @property + def coords(self: flatiter[ndarray[_ShapeT]], /) -> _ShapeT: ... + @property + def index(self, /) -> int: ... + + # iteration + def __len__(self, /) -> int: ... + def __iter__(self, /) -> Self: ... + def __next__(self: flatiter[NDArray[_ScalarT]], /) -> _ScalarT: ... + + # indexing + @overload # nd: _[()] + def __getitem__(self, key: tuple[()], /) -> _ArrayT_co: ... + @overload # 0d; _[] + def __getitem__(self: flatiter[NDArray[_ScalarT]], key: int | integer, /) -> _ScalarT: ... + @overload # 1d; _[[*]], _[:], _[...] + def __getitem__( + self: flatiter[ndarray[Any, _DTypeT]], + key: list[int] | slice | EllipsisType | flatiter[NDArray[integer]], + /, + ) -> ndarray[tuple[int], _DTypeT]: ... + @overload # 2d; _[[*[*]]] + def __getitem__( + self: flatiter[ndarray[Any, _DTypeT]], + key: list[list[int]], + /, + ) -> ndarray[tuple[int, int], _DTypeT]: ... + @overload # ?d + def __getitem__( + self: flatiter[ndarray[Any, _DTypeT]], + key: NDArray[integer] | _NestedSequence[int], + /, + ) -> ndarray[_AnyShape, _DTypeT]: ... + + # NOTE: `__setitem__` operates via `unsafe` casting rules, and can thus accept any + # type accepted by the relevant underlying `np.generic` constructor, which isn't + # known statically. So we cannot meaningfully annotate the value parameter. + def __setitem__(self, key: slice | EllipsisType | _ArrayLikeInt, val: object, /) -> None: ... + + # NOTE: `dtype` and `copy` are no-ops at runtime, so we don't support them here to + # avoid confusion + def __array__( + self: flatiter[ndarray[Any, _DTypeT]], + dtype: None = None, + /, + *, + copy: None = None, + ) -> ndarray[tuple[int], _DTypeT]: ... + + # This returns a flat copy of the underlying array, not of the iterator itself + def copy(self: flatiter[ndarray[Any, _DTypeT]], /) -> ndarray[tuple[int], _DTypeT]: ... + +@type_check_only +class _ArrayOrScalarCommon: + @property + def real(self, /) -> Any: ... + @property + def imag(self, /) -> Any: ... + @property + def T(self) -> Self: ... + @property + def mT(self) -> Self: ... + @property + def data(self) -> memoryview: ... + @property + def flags(self) -> flagsobj: ... + @property + def itemsize(self) -> int: ... + @property + def nbytes(self) -> int: ... + @property + def device(self) -> L["cpu"]: ... + + def __bool__(self, /) -> builtins.bool: ... + def __int__(self, /) -> int: ... + def __float__(self, /) -> float: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: dict[int, Any] | None, /) -> Self: ... + + # TODO: How to deal with the non-commutative nature of `==` and `!=`? + # xref numpy/numpy#17368 + def __eq__(self, other: Any, /) -> Any: ... + def __ne__(self, other: Any, /) -> Any: ... + + def copy(self, order: _OrderKACF = ...) -> Self: ... + def dump(self, file: StrOrBytesPath | SupportsWrite[bytes]) -> None: ... + def dumps(self) -> bytes: ... + def tobytes(self, order: _OrderKACF = ...) -> bytes: ... + def tofile(self, fid: StrOrBytesPath | _SupportsFileMethods, /, sep: str = "", format: str = "%s") -> None: ... + # generics and 0d arrays return builtin scalars + def tolist(self) -> Any: ... + def to_device(self, device: L["cpu"], /, *, stream: int | Any | None = ...) -> Self: ... + + # NOTE: for `generic`, these two methods don't do anything + def fill(self, /, value: Incomplete) -> None: ... + def put(self, indices: _ArrayLikeInt_co, values: ArrayLike, /, mode: _ModeKind = "raise") -> None: ... + + # NOTE: even on `generic` this seems to work + def setflags( + self, + /, + *, + write: builtins.bool | None = None, + align: builtins.bool | None = None, + uic: builtins.bool | None = None, + ) -> None: ... + + @property + def __array_interface__(self) -> dict[str, Any]: ... + @property + def __array_priority__(self) -> float: ... + @property + def __array_struct__(self) -> CapsuleType: ... # builtins.PyCapsule + def __array_namespace__(self, /, *, api_version: _ArrayAPIVersion | None = None) -> ModuleType: ... + def __setstate__(self, state: tuple[ + SupportsIndex, # version + _ShapeLike, # Shape + _DTypeT_co, # DType + np.bool, # F-continuous + bytes | list[Any], # Data + ], /) -> None: ... + + def conj(self) -> Self: ... + def conjugate(self) -> Self: ... + + def argsort( + self, + axis: SupportsIndex | None = ..., + kind: _SortKind | None = ..., + order: str | Sequence[str] | None = ..., + *, + stable: builtins.bool | None = ..., + ) -> NDArray[intp]: ... + + @overload # axis=None (default), out=None (default), keepdims=False (default) + def argmax(self, /, axis: None = None, out: None = None, *, keepdims: L[False] = False) -> intp: ... + @overload # axis=index, out=None (default) + def argmax(self, /, axis: SupportsIndex, out: None = None, *, keepdims: builtins.bool = False) -> Any: ... + @overload # axis=index, out=ndarray + def argmax(self, /, axis: SupportsIndex | None, out: _BoolOrIntArrayT, *, keepdims: builtins.bool = False) -> _BoolOrIntArrayT: ... + @overload + def argmax(self, /, axis: SupportsIndex | None = None, *, out: _BoolOrIntArrayT, keepdims: builtins.bool = False) -> _BoolOrIntArrayT: ... + + @overload # axis=None (default), out=None (default), keepdims=False (default) + def argmin(self, /, axis: None = None, out: None = None, *, keepdims: L[False] = False) -> intp: ... + @overload # axis=index, out=None (default) + def argmin(self, /, axis: SupportsIndex, out: None = None, *, keepdims: builtins.bool = False) -> Any: ... + @overload # axis=index, out=ndarray + def argmin(self, /, axis: SupportsIndex | None, out: _BoolOrIntArrayT, *, keepdims: builtins.bool = False) -> _BoolOrIntArrayT: ... + @overload + def argmin(self, /, axis: SupportsIndex | None = None, *, out: _BoolOrIntArrayT, keepdims: builtins.bool = False) -> _BoolOrIntArrayT: ... + + # Keep in sync with `MaskedArray.round` + @overload # out=None (default) + def round(self, /, decimals: SupportsIndex = 0, out: None = None) -> Self: ... + @overload # out=ndarray + def round(self, /, decimals: SupportsIndex, out: _ArrayT) -> _ArrayT: ... + @overload + def round(self, /, decimals: SupportsIndex = 0, *, out: _ArrayT) -> _ArrayT: ... + + @overload # out=None (default) + def choose(self, /, choices: ArrayLike, out: None = None, mode: _ModeKind = "raise") -> NDArray[Any]: ... + @overload # out=ndarray + def choose(self, /, choices: ArrayLike, out: _ArrayT, mode: _ModeKind = "raise") -> _ArrayT: ... + + # TODO: Annotate kwargs with an unpacked `TypedDict` + @overload # out: None (default) + def clip(self, /, min: ArrayLike, max: ArrayLike | None = None, out: None = None, **kwargs: Any) -> NDArray[Any]: ... + @overload + def clip(self, /, min: None, max: ArrayLike, out: None = None, **kwargs: Any) -> NDArray[Any]: ... + @overload + def clip(self, /, min: None = None, *, max: ArrayLike, out: None = None, **kwargs: Any) -> NDArray[Any]: ... + @overload # out: ndarray + def clip(self, /, min: ArrayLike, max: ArrayLike | None, out: _ArrayT, **kwargs: Any) -> _ArrayT: ... + @overload + def clip(self, /, min: ArrayLike, max: ArrayLike | None = None, *, out: _ArrayT, **kwargs: Any) -> _ArrayT: ... + @overload + def clip(self, /, min: None, max: ArrayLike, out: _ArrayT, **kwargs: Any) -> _ArrayT: ... + @overload + def clip(self, /, min: None = None, *, max: ArrayLike, out: _ArrayT, **kwargs: Any) -> _ArrayT: ... + + @overload + def compress(self, /, condition: _ArrayLikeInt_co, axis: SupportsIndex | None = None, out: None = None) -> NDArray[Any]: ... + @overload + def compress(self, /, condition: _ArrayLikeInt_co, axis: SupportsIndex | None, out: _ArrayT) -> _ArrayT: ... + @overload + def compress(self, /, condition: _ArrayLikeInt_co, axis: SupportsIndex | None = None, *, out: _ArrayT) -> _ArrayT: ... + + # Keep in sync with `MaskedArray.cumprod` + @overload # out: None (default) + def cumprod(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, out: None = None) -> NDArray[Any]: ... + @overload # out: ndarray + def cumprod(self, /, axis: SupportsIndex | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def cumprod(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + + # Keep in sync with `MaskedArray.cumsum` + @overload # out: None (default) + def cumsum(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, out: None = None) -> NDArray[Any]: ... + @overload # out: ndarray + def cumsum(self, /, axis: SupportsIndex | None, dtype: DTypeLike | None, out: _ArrayT) -> _ArrayT: ... + @overload + def cumsum(self, /, axis: SupportsIndex | None = None, dtype: DTypeLike | None = None, *, out: _ArrayT) -> _ArrayT: ... + + @overload + def max( + self, + /, + axis: _ShapeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def max( + self, + /, + axis: _ShapeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def max( + self, + /, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def min( + self, + /, + axis: _ShapeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def min( + self, + /, + axis: _ShapeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def min( + self, + /, + axis: _ShapeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def sum( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def sum( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def sum( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def prod( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def prod( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def prod( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + initial: _NumberLike_co | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def mean( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> Any: ... + @overload + def mean( + self, + /, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def mean( + self, + /, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def std( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + ddof: float = 0, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> Any: ... + @overload + def std( + self, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + ddof: float = 0, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def std( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ddof: float = 0, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> _ArrayT: ... + + @overload + def var( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + out: None = None, + ddof: float = 0, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> Any: ... + @overload + def var( + self, + axis: _ShapeLike | None, + dtype: DTypeLike | None, + out: _ArrayT, + ddof: float = 0, + *, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> _ArrayT: ... + @overload + def var( + self, + axis: _ShapeLike | None = None, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ddof: float = 0, + keepdims: builtins.bool | _NoValueType = ..., + where: _ArrayLikeBool_co | _NoValueType = ..., + mean: _ArrayLikeNumber_co | _NoValueType = ..., + correction: float | _NoValueType = ..., + ) -> _ArrayT: ... + +class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]): + __hash__: ClassVar[None] # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride] + @property + def base(self) -> NDArray[Any] | None: ... + @property + def ndim(self) -> int: ... + @property + def size(self) -> int: ... + @property + def real(self: _HasDTypeWithRealAndImag[_ScalarT, object], /) -> ndarray[_ShapeT_co, dtype[_ScalarT]]: ... + @real.setter + def real(self, value: ArrayLike, /) -> None: ... + @property + def imag(self: _HasDTypeWithRealAndImag[object, _ScalarT], /) -> ndarray[_ShapeT_co, dtype[_ScalarT]]: ... + @imag.setter + def imag(self, value: ArrayLike, /) -> None: ... + + def __new__( + cls, + shape: _ShapeLike, + dtype: DTypeLike | None = ..., + buffer: _SupportsBuffer | None = ..., + offset: SupportsIndex = ..., + strides: _ShapeLike | None = ..., + order: _OrderKACF = ..., + ) -> Self: ... + + if sys.version_info >= (3, 12): + def __buffer__(self, flags: int, /) -> memoryview: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + @overload + def __array__(self, dtype: None = None, /, *, copy: builtins.bool | None = None) -> ndarray[_ShapeT_co, _DTypeT_co]: ... + @overload + def __array__(self, dtype: _DTypeT, /, *, copy: builtins.bool | None = None) -> ndarray[_ShapeT_co, _DTypeT]: ... + + def __array_ufunc__( + self, + ufunc: ufunc, + method: L["__call__", "reduce", "reduceat", "accumulate", "outer", "at"], + *inputs: Any, + **kwargs: Any, + ) -> Any: ... + + def __array_function__( + self, + func: Callable[..., Any], + types: Iterable[type], + args: Iterable[Any], + kwargs: Mapping[str, Any], + ) -> Any: ... + + # NOTE: In practice any object is accepted by `obj`, but as `__array_finalize__` + # is a pseudo-abstract method the type has been narrowed down in order to + # grant subclasses a bit more flexibility + def __array_finalize__(self, obj: NDArray[Any] | None, /) -> None: ... + + def __array_wrap__( + self, + array: ndarray[_ShapeT, _DTypeT], + context: tuple[ufunc, tuple[Any, ...], int] | None = ..., + return_scalar: builtins.bool = ..., + /, + ) -> ndarray[_ShapeT, _DTypeT]: ... + + # Keep in sync with `MaskedArray.__getitem__` + @overload + def __getitem__(self, key: _ArrayInt_co | tuple[_ArrayInt_co, ...], /) -> ndarray[_AnyShape, _DTypeT_co]: ... + @overload + def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> Any: ... + @overload + def __getitem__(self, key: _ToIndices, /) -> ndarray[_AnyShape, _DTypeT_co]: ... + @overload # can be of any shape + def __getitem__(self: NDArray[void], key: str, /) -> ndarray[_ShapeT_co | _AnyShape]: ... + @overload + def __getitem__(self: NDArray[void], key: list[str], /) -> ndarray[_ShapeT_co | _AnyShape, dtype[void]]: ... + + @overload # flexible | object_ | bool + def __setitem__( + self: ndarray[Any, dtype[flexible | object_ | np.bool] | dtypes.StringDType], + key: _ToIndices, + value: object, + /, + ) -> None: ... + @overload # integer + def __setitem__( + self: NDArray[integer], + key: _ToIndices, + value: _ConvertibleToInt | _NestedSequence[_ConvertibleToInt] | _ArrayLikeInt_co, + /, + ) -> None: ... + @overload # floating + def __setitem__( + self: NDArray[floating], + key: _ToIndices, + value: _ConvertibleToFloat | _NestedSequence[_ConvertibleToFloat | None] | _ArrayLikeFloat_co | None, + /, + ) -> None: ... + @overload # complexfloating + def __setitem__( + self: NDArray[complexfloating], + key: _ToIndices, + value: _ConvertibleToComplex | _NestedSequence[_ConvertibleToComplex | None] | _ArrayLikeNumber_co | None, + /, + ) -> None: ... + @overload # timedelta64 + def __setitem__( + self: NDArray[timedelta64], + key: _ToIndices, + value: _ConvertibleToTD64 | _NestedSequence[_ConvertibleToTD64], + /, + ) -> None: ... + @overload # datetime64 + def __setitem__( + self: NDArray[datetime64], + key: _ToIndices, + value: _ConvertibleToDT64 | _NestedSequence[_ConvertibleToDT64], + /, + ) -> None: ... + @overload # void + def __setitem__(self: NDArray[void], key: str | list[str], value: object, /) -> None: ... + @overload # catch-all + def __setitem__(self, key: _ToIndices, value: ArrayLike, /) -> None: ... + + @property + def ctypes(self) -> _ctypes[int]: ... + + # + @property + def shape(self) -> _ShapeT_co: ... + @shape.setter + @deprecated("In-place shape modification will be deprecated in NumPy 2.5.", category=PendingDeprecationWarning) + def shape(self, value: _ShapeLike) -> None: ... + + # + @property + def strides(self) -> _Shape: ... + @strides.setter + @deprecated("Setting the strides on a NumPy array has been deprecated in NumPy 2.4") + def strides(self, value: _ShapeLike) -> None: ... + + # + def byteswap(self, inplace: builtins.bool = ...) -> Self: ... + @property + def flat(self) -> flatiter[Self]: ... + + @overload # use the same output type as that of the underlying `generic` + def item(self: NDArray[generic[_T]], i0: SupportsIndex | tuple[SupportsIndex, ...] = ..., /, *args: SupportsIndex) -> _T: ... + @overload # special casing for `StringDType`, which has no scalar type + def item( + self: ndarray[Any, dtypes.StringDType], + arg0: SupportsIndex | tuple[SupportsIndex, ...] = ..., + /, + *args: SupportsIndex, + ) -> str: ... + + # keep in sync with `ma.MaskedArray.tolist` + @overload # this first overload prevents mypy from over-eagerly selecting `tuple[()]` in case of `_AnyShape` + def tolist(self: ndarray[tuple[Never], dtype[generic[_T]]], /) -> Any: ... + @overload + def tolist(self: ndarray[tuple[()], dtype[generic[_T]]], /) -> _T: ... + @overload + def tolist(self: ndarray[tuple[int], dtype[generic[_T]]], /) -> list[_T]: ... + @overload + def tolist(self: ndarray[tuple[int, int], dtype[generic[_T]]], /) -> list[list[_T]]: ... + @overload + def tolist(self: ndarray[tuple[int, int, int], dtype[generic[_T]]], /) -> list[list[list[_T]]]: ... + @overload + def tolist(self, /) -> Any: ... + + @overload + def resize(self, new_shape: _ShapeLike, /, *, refcheck: builtins.bool = True) -> None: ... + @overload + def resize(self, /, *new_shape: SupportsIndex, refcheck: builtins.bool = True) -> None: ... + + # keep in sync with `ma.MaskedArray.squeeze` + def squeeze( + self, + /, + axis: SupportsIndex | tuple[SupportsIndex, ...] | None = ..., + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + + def swapaxes(self, axis1: SupportsIndex, axis2: SupportsIndex, /) -> Self: ... + + @overload + def transpose(self, axes: _ShapeLike | None, /) -> Self: ... + @overload + def transpose(self, /, *axes: SupportsIndex) -> Self: ... + + @overload + def all( + self, + axis: None = None, + out: None = None, + keepdims: L[False, 0] = False, + *, + where: _ArrayLikeBool_co = True + ) -> np.bool: ... + @overload + def all( + self, + axis: int | tuple[int, ...] | None = None, + out: None = None, + keepdims: SupportsIndex = False, + *, + where: _ArrayLikeBool_co = True, + ) -> np.bool | NDArray[np.bool]: ... + @overload + def all( + self, + axis: int | tuple[int, ...] | None, + out: _ArrayT, + keepdims: SupportsIndex = False, + *, + where: _ArrayLikeBool_co = True, + ) -> _ArrayT: ... + @overload + def all( + self, + axis: int | tuple[int, ...] | None = None, + *, + out: _ArrayT, + keepdims: SupportsIndex = False, + where: _ArrayLikeBool_co = True, + ) -> _ArrayT: ... + + @overload + def any( + self, + axis: None = None, + out: None = None, + keepdims: L[False, 0] = False, + *, + where: _ArrayLikeBool_co = True + ) -> np.bool: ... + @overload + def any( + self, + axis: int | tuple[int, ...] | None = None, + out: None = None, + keepdims: SupportsIndex = False, + *, + where: _ArrayLikeBool_co = True, + ) -> np.bool | NDArray[np.bool]: ... + @overload + def any( + self, + axis: int | tuple[int, ...] | None, + out: _ArrayT, + keepdims: SupportsIndex = False, + *, + where: _ArrayLikeBool_co = True, + ) -> _ArrayT: ... + @overload + def any( + self, + axis: int | tuple[int, ...] | None = None, + *, + out: _ArrayT, + keepdims: SupportsIndex = False, + where: _ArrayLikeBool_co = True, + ) -> _ArrayT: ... + + # + @overload + def partition( + self, + kth: _ArrayLikeInt, + /, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: None = None, + ) -> None: ... + @overload + def partition( + self: NDArray[void], + kth: _ArrayLikeInt, + /, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, + ) -> None: ... + + # + @overload + def argpartition( + self, + kth: _ArrayLikeInt, + /, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: None = None, + ) -> NDArray[intp]: ... + @overload + def argpartition( + self: NDArray[void], + kth: _ArrayLikeInt, + /, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, + ) -> NDArray[intp]: ... + + # keep in sync with `ma.MaskedArray.diagonal` + def diagonal( + self, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + + # 1D + 1D returns a scalar; + # all other with at least 1 non-0D array return an ndarray. + @overload + def dot(self, b: _ScalarLike_co, /, out: None = None) -> NDArray[Any]: ... + @overload + def dot(self, b: ArrayLike, /, out: None = None) -> Any: ... + @overload + def dot(self, b: ArrayLike, /, out: _ArrayT) -> _ArrayT: ... + + # `nonzero()` raises for 0d arrays/generics + def nonzero(self) -> tuple[ndarray[tuple[int], np.dtype[intp]], ...]: ... + + @overload + def searchsorted( + self, # >= 1D array + v: _ScalarLike_co, # 0D array-like + /, + side: _SortSide = "left", + sorter: _ArrayLikeInt_co | None = None, + ) -> intp: ... + @overload + def searchsorted( + self, # >= 1D array + v: ArrayLike, + /, + side: _SortSide = "left", + sorter: _ArrayLikeInt_co | None = None, + ) -> NDArray[intp]: ... + + def sort( + self, + /, + axis: SupportsIndex = -1, + kind: _SortKind | None = None, + order: str | Sequence[str] | None = None, + *, + stable: builtins.bool | None = None, + ) -> None: ... + + # Keep in sync with `MaskedArray.trace` + @overload + def trace( + self, # >= 2D array + /, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + dtype: DTypeLike | None = None, + out: None = None, + ) -> Any: ... + @overload + def trace( + self, # >= 2D array + /, + offset: SupportsIndex = 0, + axis1: SupportsIndex = 0, + axis2: SupportsIndex = 1, + dtype: DTypeLike | None = None, + *, + out: _ArrayT, + ) -> _ArrayT: ... + @overload + def trace( + self, # >= 2D array + /, + offset: SupportsIndex, + axis1: SupportsIndex, + axis2: SupportsIndex, + dtype: DTypeLike | None, + out: _ArrayT, + ) -> _ArrayT: ... + + @overload + def take( + self: NDArray[_ScalarT], + indices: _IntLike_co, + /, + axis: SupportsIndex | None = ..., + out: None = None, + mode: _ModeKind = ..., + ) -> _ScalarT: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None = ..., + out: None = None, + mode: _ModeKind = ..., + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None = ..., + *, + out: _ArrayT, + mode: _ModeKind = ..., + ) -> _ArrayT: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None, + out: _ArrayT, + mode: _ModeKind = ..., + ) -> _ArrayT: ... + + # keep in sync with `ma.MaskedArray.repeat` + @overload + def repeat(self, repeats: _ArrayLikeInt_co, /, axis: None = None) -> ndarray[tuple[int], _DTypeT_co]: ... + @overload + def repeat(self, repeats: _ArrayLikeInt_co, /, axis: SupportsIndex) -> ndarray[_AnyShape, _DTypeT_co]: ... + + # keep in sync with `ma.MaskedArray.flatten` and `ma.MaskedArray.ravel` + def flatten(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], _DTypeT_co]: ... + def ravel(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], _DTypeT_co]: ... + + # Keep in sync with `MaskedArray.reshape` + # NOTE: reshape also accepts negative integers, so we can't use integer literals + @overload # (None) + def reshape(self, shape: None, /, *, order: _OrderACF = "C", copy: builtins.bool | None = None) -> Self: ... + @overload # (empty_sequence) + def reshape( # type: ignore[overload-overlap] # mypy false positive + self, + shape: Sequence[Never], + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[()], _DTypeT_co]: ... + @overload # (() | (int) | (int, int) | ....) # up to 8-d + def reshape( + self, + shape: _AnyShapeT, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[_AnyShapeT, _DTypeT_co]: ... + @overload # (index) + def reshape( + self, + size1: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[int], _DTypeT_co]: ... + @overload # (index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[int, int], _DTypeT_co]: ... + @overload # (index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[int, int, int], _DTypeT_co]: ... + @overload # (index, index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + size4: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[int, int, int, int], _DTypeT_co]: ... + @overload # (int, *(index, ...)) + def reshape( + self, + size0: SupportsIndex, + /, + *shape: SupportsIndex, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + @overload # (sequence[index]) + def reshape( + self, + shape: Sequence[SupportsIndex], + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[_AnyShape, _DTypeT_co]: ... + + @overload + def astype( + self, + dtype: _DTypeLike[_ScalarT], + order: _OrderKACF = ..., + casting: _CastingKind = ..., + subok: builtins.bool = ..., + copy: builtins.bool | _CopyMode = ..., + ) -> ndarray[_ShapeT_co, dtype[_ScalarT]]: ... + @overload + def astype( + self, + dtype: DTypeLike | None, + order: _OrderKACF = ..., + casting: _CastingKind = ..., + subok: builtins.bool = ..., + copy: builtins.bool | _CopyMode = ..., + ) -> ndarray[_ShapeT_co, dtype]: ... + + # + @overload # () + def view(self, /) -> Self: ... + @overload # (dtype: T) + def view(self, /, dtype: _DTypeT | _HasDType[_DTypeT]) -> ndarray[_ShapeT_co, _DTypeT]: ... + @overload # (dtype: dtype[T]) + def view(self, /, dtype: _DTypeLike[_ScalarT]) -> ndarray[_ShapeT_co, dtype[_ScalarT]]: ... + @overload # (type: T) + def view(self, /, *, type: type[_ArrayT]) -> _ArrayT: ... + @overload # (_: T) + def view(self, /, dtype: type[_ArrayT]) -> _ArrayT: ... + @overload # (dtype: ?) + def view(self, /, dtype: DTypeLike) -> ndarray[_ShapeT_co, dtype]: ... + @overload # (dtype: ?, type: T) + def view(self, /, dtype: DTypeLike, type: type[_ArrayT]) -> _ArrayT: ... + + def setfield(self, val: ArrayLike, /, dtype: DTypeLike, offset: SupportsIndex = 0) -> None: ... + @overload + def getfield(self, /, dtype: _DTypeLike[_ScalarT], offset: SupportsIndex = 0) -> NDArray[_ScalarT]: ... + @overload + def getfield(self, /, dtype: DTypeLike, offset: SupportsIndex = 0) -> NDArray[Any]: ... + + def __index__(self: NDArray[integer], /) -> int: ... + def __complex__(self: NDArray[number | np.bool | object_], /) -> complex: ... + + def __len__(self) -> int: ... + def __contains__(self, value: object, /) -> builtins.bool: ... + + # NOTE: This weird `Never` tuple works around a strange mypy issue where it assigns + # `tuple[int]` to `tuple[Never]` or `tuple[int, int]` to `tuple[Never, Never]`. + # This way the bug only occurs for 9-D arrays, which are probably not very common. + @overload + def __iter__( + self: ndarray[tuple[Never, Never, Never, Never, Never, Never, Never, Never, Never], Any], / + ) -> Iterator[Any]: ... + @overload # == 1-d & dtype[T \ object_] + def __iter__(self: ndarray[tuple[int], dtype[_NonObjectScalarT]], /) -> Iterator[_NonObjectScalarT]: ... + @overload # == 1-d & StringDType + def __iter__(self: ndarray[tuple[int], dtypes.StringDType], /) -> Iterator[str]: ... + @overload # >= 2-d + def __iter__(self: ndarray[tuple[int, int, *tuple[int, ...]], _DTypeT], /) -> Iterator[ndarray[_AnyShape, _DTypeT]]: ... + @overload # ?-d + def __iter__(self, /) -> Iterator[Any]: ... + + # + @overload + def __lt__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co, /) -> NDArray[np.bool]: ... + @overload + def __lt__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[np.bool]: ... + @overload + def __lt__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[np.bool]: ... + @overload + def __lt__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[np.bool]: ... + @overload + def __lt__( + self: ndarray[Any, dtype[str_] | dtypes.StringDType], other: _ArrayLikeStr_co | _ArrayLikeString_co, / + ) -> NDArray[np.bool]: ... + @overload + def __lt__(self: NDArray[object_], other: object, /) -> NDArray[np.bool]: ... + @overload + def __lt__(self, other: _ArrayLikeObject_co, /) -> NDArray[np.bool]: ... + + # + @overload + def __le__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co, /) -> NDArray[np.bool]: ... + @overload + def __le__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[np.bool]: ... + @overload + def __le__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[np.bool]: ... + @overload + def __le__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[np.bool]: ... + @overload + def __le__( + self: ndarray[Any, dtype[str_] | dtypes.StringDType], other: _ArrayLikeStr_co | _ArrayLikeString_co, / + ) -> NDArray[np.bool]: ... + @overload + def __le__(self: NDArray[object_], other: object, /) -> NDArray[np.bool]: ... + @overload + def __le__(self, other: _ArrayLikeObject_co, /) -> NDArray[np.bool]: ... + + # + @overload + def __gt__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co, /) -> NDArray[np.bool]: ... + @overload + def __gt__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[np.bool]: ... + @overload + def __gt__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[np.bool]: ... + @overload + def __gt__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[np.bool]: ... + @overload + def __gt__( + self: ndarray[Any, dtype[str_] | dtypes.StringDType], other: _ArrayLikeStr_co | _ArrayLikeString_co, / + ) -> NDArray[np.bool]: ... + @overload + def __gt__(self: NDArray[object_], other: object, /) -> NDArray[np.bool]: ... + @overload + def __gt__(self, other: _ArrayLikeObject_co, /) -> NDArray[np.bool]: ... + + # + @overload + def __ge__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co, /) -> NDArray[np.bool]: ... + @overload + def __ge__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[np.bool]: ... + @overload + def __ge__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[np.bool]: ... + @overload + def __ge__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[np.bool]: ... + @overload + def __ge__( + self: ndarray[Any, dtype[str_] | dtypes.StringDType], other: _ArrayLikeStr_co | _ArrayLikeString_co, / + ) -> NDArray[np.bool]: ... + @overload + def __ge__(self: NDArray[object_], other: object, /) -> NDArray[np.bool]: ... + @overload + def __ge__(self, other: _ArrayLikeObject_co, /) -> NDArray[np.bool]: ... + + # Unary ops + + # TODO: Uncomment once https://github.com/python/mypy/issues/14070 is fixed + # @overload + # def __abs__(self: ndarray[_ShapeT, dtypes.Complex64DType], /) -> ndarray[_ShapeT, dtypes.Float32DType]: ... + # @overload + # def __abs__(self: ndarray[_ShapeT, dtypes.Complex128DType], /) -> ndarray[_ShapeT, dtypes.Float64DType]: ... + # @overload + # def __abs__(self: ndarray[_ShapeT, dtypes.CLongDoubleDType], /) -> ndarray[_ShapeT, dtypes.LongDoubleDType]: ... + # @overload + # def __abs__(self: ndarray[_ShapeT, dtype[complex128]], /) -> ndarray[_ShapeT, dtype[float64]]: ... + @overload + def __abs__(self: ndarray[_ShapeT, dtype[complexfloating[_NBit]]], /) -> ndarray[_ShapeT, dtype[floating[_NBit]]]: ... + @overload + def __abs__(self: _RealArrayT, /) -> _RealArrayT: ... + + def __invert__(self: _IntegralArrayT, /) -> _IntegralArrayT: ... # noqa: PYI019 + def __neg__(self: _NumericArrayT, /) -> _NumericArrayT: ... # noqa: PYI019 + def __pos__(self: _NumericArrayT, /) -> _NumericArrayT: ... # noqa: PYI019 + + # Binary ops + + # TODO: Support the "1d @ 1d -> scalar" case + @overload + def __matmul__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... + @overload + def __matmul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __matmul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __matmul__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __matmul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __matmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __matmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... + @overload + def __matmul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __matmul__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __matmul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload # signature equivalent to __matmul__ + def __rmatmul__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... + @overload + def __rmatmul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rmatmul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rmatmul__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __rmatmul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __rmatmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rmatmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... + @overload + def __rmatmul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __rmatmul__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rmatmul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __mod__(self: NDArray[_RealNumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __mod__(self: NDArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __mod__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __mod__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mod__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __mod__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __mod__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __mod__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload # signature equivalent to __mod__ + def __rmod__(self: NDArray[_RealNumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __rmod__(self: NDArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rmod__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rmod__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmod__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __rmod__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __rmod__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rmod__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __divmod__(self: NDArray[_RealNumberT], rhs: int | np.bool, /) -> _2Tuple[ndarray[_ShapeT_co, dtype[_RealNumberT]]]: ... + @overload + def __divmod__(self: NDArray[_RealNumberT], rhs: _ArrayLikeBool_co, /) -> _2Tuple[NDArray[_RealNumberT]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: NDArray[np.bool], rhs: _ArrayLikeBool_co, /) -> _2Tuple[NDArray[int8]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: NDArray[np.bool], rhs: _ArrayLike[_RealNumberT], /) -> _2Tuple[NDArray[_RealNumberT]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: NDArray[float64], rhs: _ArrayLikeFloat64_co, /) -> _2Tuple[NDArray[float64]]: ... + @overload + def __divmod__(self: _ArrayFloat64_co, rhs: _ArrayLike[floating[_64Bit]], /) -> _2Tuple[NDArray[float64]]: ... + @overload + def __divmod__(self: _ArrayUInt_co, rhs: _ArrayLikeUInt_co, /) -> _2Tuple[NDArray[unsignedinteger]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: _ArrayInt_co, rhs: _ArrayLikeInt_co, /) -> _2Tuple[NDArray[signedinteger]]: ... # type: ignore[overload-overlap] + @overload + def __divmod__(self: _ArrayFloat_co, rhs: _ArrayLikeFloat_co, /) -> _2Tuple[NDArray[floating]]: ... + @overload + def __divmod__(self: NDArray[timedelta64], rhs: _ArrayLike[timedelta64], /) -> tuple[NDArray[int64], NDArray[timedelta64]]: ... + + @overload # signature equivalent to __divmod__ + def __rdivmod__(self: NDArray[_RealNumberT], lhs: int | np.bool, /) -> _2Tuple[ndarray[_ShapeT_co, dtype[_RealNumberT]]]: ... + @overload + def __rdivmod__(self: NDArray[_RealNumberT], lhs: _ArrayLikeBool_co, /) -> _2Tuple[NDArray[_RealNumberT]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: NDArray[np.bool], lhs: _ArrayLikeBool_co, /) -> _2Tuple[NDArray[int8]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: NDArray[np.bool], lhs: _ArrayLike[_RealNumberT], /) -> _2Tuple[NDArray[_RealNumberT]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: NDArray[float64], lhs: _ArrayLikeFloat64_co, /) -> _2Tuple[NDArray[float64]]: ... + @overload + def __rdivmod__(self: _ArrayFloat64_co, lhs: _ArrayLike[floating[_64Bit]], /) -> _2Tuple[NDArray[float64]]: ... + @overload + def __rdivmod__(self: _ArrayUInt_co, lhs: _ArrayLikeUInt_co, /) -> _2Tuple[NDArray[unsignedinteger]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: _ArrayInt_co, lhs: _ArrayLikeInt_co, /) -> _2Tuple[NDArray[signedinteger]]: ... # type: ignore[overload-overlap] + @overload + def __rdivmod__(self: _ArrayFloat_co, lhs: _ArrayLikeFloat_co, /) -> _2Tuple[NDArray[floating]]: ... + @overload + def __rdivmod__(self: NDArray[timedelta64], lhs: _ArrayLike[timedelta64], /) -> tuple[NDArray[int64], NDArray[timedelta64]]: ... + + # Keep in sync with `MaskedArray.__add__` + @overload + def __add__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __add__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __add__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __add__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __add__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __add__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... # type: ignore[overload-overlap] + @overload + def __add__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... + @overload + def __add__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co, /) -> NDArray[datetime64]: ... + @overload + def __add__(self: NDArray[datetime64], other: _ArrayLikeTD64_co, /) -> NDArray[datetime64]: ... + @overload + def __add__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[bytes_]: ... + @overload + def __add__(self: NDArray[str_], other: _ArrayLikeStr_co, /) -> NDArray[str_]: ... + @overload + def __add__( + self: ndarray[Any, dtypes.StringDType], + other: _ArrayLikeStr_co | _ArrayLikeString_co, + /, + ) -> ndarray[tuple[Any, ...], dtypes.StringDType]: ... + @overload + def __add__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __add__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__radd__` + @overload # signature equivalent to __add__ + def __radd__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __radd__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __radd__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __radd__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __radd__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __radd__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... # type: ignore[overload-overlap] + @overload + def __radd__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... + @overload + def __radd__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co, /) -> NDArray[datetime64]: ... + @overload + def __radd__(self: NDArray[datetime64], other: _ArrayLikeTD64_co, /) -> NDArray[datetime64]: ... + @overload + def __radd__(self: NDArray[bytes_], other: _ArrayLikeBytes_co, /) -> NDArray[bytes_]: ... + @overload + def __radd__(self: NDArray[str_], other: _ArrayLikeStr_co, /) -> NDArray[str_]: ... + @overload + def __radd__( + self: ndarray[Any, dtypes.StringDType], + other: _ArrayLikeStr_co | _ArrayLikeString_co, + /, + ) -> ndarray[tuple[Any, ...], dtypes.StringDType]: ... + @overload + def __radd__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __radd__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__sub__` + @overload + def __sub__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __sub__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __sub__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __sub__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __sub__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __sub__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __sub__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... # type: ignore[overload-overlap] + @overload + def __sub__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... + @overload + def __sub__(self: NDArray[datetime64], other: _ArrayLikeTD64_co, /) -> NDArray[datetime64]: ... + @overload + def __sub__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[timedelta64]: ... + @overload + def __sub__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __sub__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rsub__` + @overload + def __rsub__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rsub__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __rsub__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rsub__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rsub__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __rsub__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __rsub__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... # type: ignore[overload-overlap] + @overload + def __rsub__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co, /) -> NDArray[timedelta64]: ... + @overload + def __rsub__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co, /) -> NDArray[datetime64]: ... + @overload + def __rsub__(self: NDArray[datetime64], other: _ArrayLikeDT64_co, /) -> NDArray[timedelta64]: ... + @overload + def __rsub__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rsub__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__mul__` + @overload + def __mul__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __mul__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __mul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __mul__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __mul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __mul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __mul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... + @overload + def __mul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __mul__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> NDArray[timedelta64]: ... + @overload + def __mul__(self: _ArrayFloat_co, other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __mul__( + self: ndarray[Any, dtype[character] | dtypes.StringDType], + other: _ArrayLikeInt, + /, + ) -> ndarray[tuple[Any, ...], _DTypeT_co]: ... + @overload + def __mul__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __mul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rmul__` + @overload # signature equivalent to __mul__ + def __rmul__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rmul__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rmul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rmul__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __rmul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __rmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ... + @overload + def __rmul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __rmul__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> NDArray[timedelta64]: ... + @overload + def __rmul__(self: _ArrayFloat_co, other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __rmul__( + self: ndarray[Any, dtype[character] | dtypes.StringDType], + other: _ArrayLikeInt, + /, + ) -> ndarray[tuple[Any, ...], _DTypeT_co]: ... + @overload + def __rmul__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rmul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__truediv__` + @overload + def __truediv__(self: _ArrayInt_co | NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __truediv__(self: _ArrayFloat64_co, other: _ArrayLikeInt_co | _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __truediv__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __truediv__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __truediv__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __truediv__(self: _ArrayFloat_co, other: _ArrayLike[floating], /) -> NDArray[floating]: ... + @overload + def __truediv__(self: NDArray[complexfloating], other: _ArrayLikeNumber_co, /) -> NDArray[complexfloating]: ... + @overload + def __truediv__(self: _ArrayNumber_co, other: _ArrayLike[complexfloating], /) -> NDArray[complexfloating]: ... + @overload + def __truediv__(self: NDArray[inexact], other: _ArrayLikeNumber_co, /) -> NDArray[inexact]: ... + @overload + def __truediv__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __truediv__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[float64]: ... + @overload + def __truediv__(self: NDArray[timedelta64], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __truediv__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> NDArray[timedelta64]: ... + @overload + def __truediv__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __truediv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rtruediv__` + @overload + def __rtruediv__(self: _ArrayInt_co | NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rtruediv__(self: _ArrayFloat64_co, other: _ArrayLikeInt_co | _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rtruediv__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ... + @overload + def __rtruediv__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ... + @overload + def __rtruediv__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __rtruediv__(self: _ArrayFloat_co, other: _ArrayLike[floating], /) -> NDArray[floating]: ... + @overload + def __rtruediv__(self: NDArray[complexfloating], other: _ArrayLikeNumber_co, /) -> NDArray[complexfloating]: ... + @overload + def __rtruediv__(self: _ArrayNumber_co, other: _ArrayLike[complexfloating], /) -> NDArray[complexfloating]: ... + @overload + def __rtruediv__(self: NDArray[inexact], other: _ArrayLikeNumber_co, /) -> NDArray[inexact]: ... + @overload + def __rtruediv__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ... + @overload + def __rtruediv__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[float64]: ... + @overload + def __rtruediv__(self: NDArray[integer | floating], other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __rtruediv__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rtruediv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__floordiv__` + @overload + def __floordiv__(self: NDArray[_RealNumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __floordiv__(self: NDArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __floordiv__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __floordiv__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __floordiv__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __floordiv__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[int64]: ... + @overload + def __floordiv__(self: NDArray[timedelta64], other: _ArrayLikeBool_co, /) -> NoReturn: ... + @overload + def __floordiv__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> NDArray[timedelta64]: ... + @overload + def __floordiv__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __floordiv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rfloordiv__` + @overload + def __rfloordiv__(self: NDArray[_RealNumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_RealNumberT]]: ... + @overload + def __rfloordiv__(self: NDArray[_RealNumberT], other: _ArrayLikeBool_co, /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ... + @overload + def __rfloordiv__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ... + @overload + def __rfloordiv__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rfloordiv__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ... + @overload + def __rfloordiv__(self: NDArray[timedelta64], other: _ArrayLike[timedelta64], /) -> NDArray[int64]: ... + @overload + def __rfloordiv__(self: NDArray[floating | integer], other: _ArrayLike[timedelta64], /) -> NDArray[timedelta64]: ... + @overload + def __rfloordiv__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rfloordiv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # Keep in sync with `MaskedArray.__pow__` + @overload + def __pow__(self: NDArray[_NumberT], other: int | np.bool, mod: None = None, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __pow__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: NDArray[np.bool], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], mod: None = None, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, mod: None = None, /) -> NDArray[float64]: ... + @overload + def __pow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], mod: None = None, /) -> NDArray[float64]: ... + @overload + def __pow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, mod: None = None, /) -> NDArray[complex128]: ... + @overload + def __pow__( + self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], mod: None = None, / + ) -> NDArray[complex128]: ... + @overload + def __pow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, mod: None = None, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _ArrayInt_co, other: _ArrayLikeInt_co, mod: None = None, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, mod: None = None, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __pow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, mod: None = None, /) -> NDArray[complexfloating]: ... + @overload + def __pow__(self: NDArray[number], other: _ArrayLikeNumber_co, mod: None = None, /) -> NDArray[number]: ... + @overload + def __pow__(self: NDArray[object_], other: Any, mod: None = None, /) -> Any: ... + @overload + def __pow__(self: NDArray[Any], other: _ArrayLikeObject_co, mod: None = None, /) -> Any: ... + + # Keep in sync with `MaskedArray.__rpow__` + @overload + def __rpow__(self: NDArray[_NumberT], other: int | np.bool, mod: None = None, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ... + @overload + def __rpow__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: NDArray[np.bool], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[int8]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], mod: None = None, /) -> NDArray[_NumberT]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, mod: None = None, /) -> NDArray[float64]: ... + @overload + def __rpow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], mod: None = None, /) -> NDArray[float64]: ... + @overload + def __rpow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, mod: None = None, /) -> NDArray[complex128]: ... + @overload + def __rpow__( + self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], mod: None = None, / + ) -> NDArray[complex128]: ... + @overload + def __rpow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, mod: None = None, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _ArrayInt_co, other: _ArrayLikeInt_co, mod: None = None, /) -> NDArray[signedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, mod: None = None, /) -> NDArray[floating]: ... # type: ignore[overload-overlap] + @overload + def __rpow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, mod: None = None, /) -> NDArray[complexfloating]: ... + @overload + def __rpow__(self: NDArray[number], other: _ArrayLikeNumber_co, mod: None = None, /) -> NDArray[number]: ... + @overload + def __rpow__(self: NDArray[object_], other: Any, mod: None = None, /) -> Any: ... + @overload + def __rpow__(self: NDArray[Any], other: _ArrayLikeObject_co, mod: None = None, /) -> Any: ... + + @overload + def __lshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... + @overload + def __lshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __lshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __lshift__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __lshift__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rlshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... + @overload + def __rlshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rlshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rlshift__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rlshift__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... + @overload + def __rshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rshift__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rshift__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rrshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ... + @overload + def __rrshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rrshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rrshift__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rrshift__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __and__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __and__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __and__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __and__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __and__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rand__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __rand__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rand__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rand__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rand__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __xor__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __xor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __xor__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __xor__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __xor__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __rxor__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __rxor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __rxor__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __rxor__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __rxor__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __or__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __or__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __or__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __or__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __or__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + @overload + def __ror__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ... + @overload + def __ror__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ... # type: ignore[overload-overlap] + @overload + def __ror__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ... + @overload + def __ror__(self: NDArray[object_], other: Any, /) -> Any: ... + @overload + def __ror__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ... + + # `np.generic` does not support inplace operations + + # NOTE: Inplace ops generally use "same_kind" casting w.r.t. to the left + # operand. An exception to this rule are unsigned integers though, which + # also accepts a signed integer for the right operand as long it is a 0D + # object and its value is >= 0 + # NOTE: Due to a mypy bug, overloading on e.g. `self: NDArray[SCT_floating]` won't + # work, as this will lead to `false negatives` when using these inplace ops. + + # += + @overload # type: ignore[misc] + def __iadd__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __iadd__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __iadd__(self: _InexactArrayT, other: _ArrayLikeFloat_co, /) -> _InexactArrayT: ... + @overload + def __iadd__(self: _NumberArrayT, other: _ArrayLikeInt_co, /) -> _NumberArrayT: ... + @overload + def __iadd__(self: _TimeArrayT, other: _ArrayLikeTD64_co, /) -> _TimeArrayT: ... + @overload + def __iadd__(self: _BytesArrayT, other: _ArrayLikeBytes_co, /) -> _BytesArrayT: ... + @overload + def __iadd__(self: _StringArrayT, other: _ArrayLikeStr_co | _ArrayLikeString_co, /) -> _StringArrayT: ... + @overload + def __iadd__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # -= + @overload # type: ignore[misc] + def __isub__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __isub__(self: _InexactArrayT, other: _ArrayLikeFloat_co, /) -> _InexactArrayT: ... + @overload + def __isub__(self: _NumberArrayT, other: _ArrayLikeInt_co, /) -> _NumberArrayT: ... + @overload + def __isub__(self: _TimeArrayT, other: _ArrayLikeTD64_co, /) -> _TimeArrayT: ... + @overload + def __isub__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # *= + @overload # type: ignore[misc] + def __imul__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __imul__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __imul__(self: _InexactTimedeltaArrayT, other: _ArrayLikeFloat_co, /) -> _InexactTimedeltaArrayT: ... + @overload + def __imul__(self: _NumberCharacterArrayT, other: _ArrayLikeInt_co, /) -> _NumberCharacterArrayT: ... + @overload + def __imul__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # @= + @overload # type: ignore[misc] + def __imatmul__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __imatmul__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __imatmul__(self: _InexactArrayT, other: _ArrayLikeFloat_co, /) -> _InexactArrayT: ... + @overload + def __imatmul__(self: _NumberArrayT, other: _ArrayLikeInt_co, /) -> _NumberArrayT: ... + @overload + def __imatmul__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # **= + @overload # type: ignore[misc] + def __ipow__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __ipow__(self: _InexactArrayT, other: _ArrayLikeFloat_co, /) -> _InexactArrayT: ... + @overload + def __ipow__(self: _NumberArrayT, other: _ArrayLikeInt_co, /) -> _NumberArrayT: ... + @overload + def __ipow__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # /= + @overload # type: ignore[misc] + def __itruediv__(self: _ComplexFloatingArrayT, other: _ArrayLikeComplex_co, /) -> _ComplexFloatingArrayT: ... + @overload + def __itruediv__(self: _InexactTimedeltaArrayT, other: _ArrayLikeFloat_co, /) -> _InexactTimedeltaArrayT: ... + @overload + def __itruediv__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # //= + # keep in sync with `__imod__` + @overload # type: ignore[misc] + def __ifloordiv__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __ifloordiv__(self: _FloatingTimedeltaArrayT, other: _ArrayLikeFloat_co, /) -> _FloatingTimedeltaArrayT: ... + @overload + def __ifloordiv__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # %= + # keep in sync with `__ifloordiv__` + @overload # type: ignore[misc] + def __imod__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __imod__(self: _FloatingArrayT, other: _ArrayLikeFloat_co, /) -> _FloatingArrayT: ... + @overload + def __imod__(self: _TimedeltaArrayT, other: _ArrayLike[timedelta64], /) -> _TimedeltaArrayT: ... + @overload + def __imod__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # <<= + # keep in sync with `__irshift__` + @overload # type: ignore[misc] + def __ilshift__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __ilshift__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # >>= + # keep in sync with `__ilshift__` + @overload # type: ignore[misc] + def __irshift__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __irshift__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # &= + # keep in sync with `__ixor__` and `__ior__` + @overload # type: ignore[misc] + def __iand__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __iand__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __iand__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # ^= + # keep in sync with `__iand__` and `__ior__` + @overload # type: ignore[misc] + def __ixor__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __ixor__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __ixor__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # |= + # keep in sync with `__iand__` and `__ixor__` + @overload # type: ignore[misc] + def __ior__(self: _BoolArrayT, other: _ArrayLikeBool_co, /) -> _BoolArrayT: ... + @overload + def __ior__(self: _IntegerArrayT, other: _ArrayLikeInt_co, /) -> _IntegerArrayT: ... + @overload + def __ior__(self: _ObjectArrayT, other: object, /) -> _ObjectArrayT: ... + + # + def __dlpack__( + self: NDArray[number], + /, + *, + stream: int | Any | None = None, + max_version: tuple[int, int] | None = None, + dl_device: tuple[int, int] | None = None, + copy: builtins.bool | None = None, + ) -> CapsuleType: ... + def __dlpack_device__(self, /) -> tuple[L[1], L[0]]: ... + + # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype` + @property + def dtype(self) -> _DTypeT_co: ... + +# NOTE: while `np.generic` is not technically an instance of `ABCMeta`, +# the `@abstractmethod` decorator is herein used to (forcefully) deny +# the creation of `np.generic` instances. +# The `# type: ignore` comments are necessary to silence mypy errors regarding +# the missing `ABCMeta` metaclass. +# See https://github.com/numpy/numpy-stubs/pull/80 for more details. +class generic(_ArrayOrScalarCommon, Generic[_ItemT_co]): + @abstractmethod + def __new__(cls, /, *args: Any, **kwargs: Any) -> Self: ... + + # NOTE: Technically this doesn't exist at runtime, but it is unlikely to lead to + # type-unsafe situations (the abstract scalar types cannot be instantiated + # themselves) and is convenient to have, so we include it regardless. See + # https://github.com/numpy/numpy/issues/30445 for use-cases and discussion. + def __hash__(self, /) -> int: ... + + if sys.version_info >= (3, 12): + def __buffer__(self, flags: int, /) -> memoryview: ... + + @overload + def __array__(self, dtype: None = None, /) -> ndarray[tuple[()], dtype[Self]]: ... + @overload + def __array__(self, dtype: _DTypeT, /) -> ndarray[tuple[()], _DTypeT]: ... + + @overload + def __array_wrap__( + self, + array: ndarray[_ShapeT, _DTypeT], + context: tuple[ufunc, tuple[object, ...], int] | None, + return_scalar: L[False], + /, + ) -> ndarray[_ShapeT, _DTypeT]: ... + @overload + def __array_wrap__( + self, + array: ndarray[tuple[()], dtype[_ScalarT]], + context: tuple[ufunc, tuple[object, ...], int] | None = None, + return_scalar: L[True] = True, + /, + ) -> _ScalarT: ... + @overload + def __array_wrap__( + self, + array: ndarray[_Shape1T, _DTypeT], + context: tuple[ufunc, tuple[object, ...], int] | None = None, + return_scalar: L[True] = True, + /, + ) -> ndarray[_Shape1T, _DTypeT]: ... + @overload + def __array_wrap__( + self, + array: ndarray[_ShapeT, dtype[_ScalarT]], + context: tuple[ufunc, tuple[object, ...], int] | None = None, + return_scalar: L[True] = True, + /, + ) -> _ScalarT | ndarray[_ShapeT, dtype[_ScalarT]]: ... + + @property + def base(self) -> None: ... + @property + def ndim(self) -> L[0]: ... + @property + def size(self) -> L[1]: ... + @property + def shape(self) -> tuple[()]: ... + @property + def strides(self) -> tuple[()]: ... + @property + def flat(self) -> flatiter[ndarray[tuple[int], dtype[Self]]]: ... + + @overload + def item(self, /) -> _ItemT_co: ... + @overload + def item(self, arg0: L[0, -1] | tuple[L[0, -1]] | tuple[()] = ..., /) -> _ItemT_co: ... + @override + def tolist(self, /) -> _ItemT_co: ... + + # NOTE: these technically exist, but will always raise when called + def trace( # type: ignore[misc] + self: Never, + /, + offset: L[0] = 0, + axis1: L[0] = 0, + axis2: L[1] = 1, + dtype: None = None, + out: None = None, + ) -> Never: ... + def diagonal(self: Never, /, offset: L[0] = 0, axis1: L[0] = 0, axis2: L[1] = 1) -> Never: ... # type: ignore[misc] + def swapaxes(self: Never, axis1: Never, axis2: Never, /) -> Never: ... # type: ignore[misc] + def sort(self: Never, /, axis: L[-1] = -1, kind: None = None, order: None = None, *, stable: None = None) -> Never: ... # type: ignore[misc] + def nonzero(self: Never, /) -> Never: ... # type: ignore[misc] + def setfield(self: Never, val: Never, /, dtype: Never, offset: L[0] = 0) -> None: ... # type: ignore[misc] + def searchsorted(self: Never, v: Never, /, side: L["left"] = "left", sorter: None = None) -> Never: ... # type: ignore[misc] + + # NOTE: this wont't raise, but won't do anything either + @overload + def resize(self, /, *, refcheck: builtins.bool = True) -> None: ... + @overload + def resize(self, new_shape: L[0, -1] | tuple[L[0, -1]] | tuple[()], /, *, refcheck: builtins.bool = True) -> None: ... + + # + def byteswap(self, /, inplace: L[False] = False) -> Self: ... + + # + @overload + def astype( + self, + /, + dtype: _DTypeLike[_ScalarT], + order: _OrderKACF = "K", + casting: _CastingKind = "unsafe", + subok: builtins.bool = True, + copy: builtins.bool | _CopyMode = True, + ) -> _ScalarT: ... + @overload + def astype( + self, + /, + dtype: DTypeLike | None, + order: _OrderKACF = "K", + casting: _CastingKind = "unsafe", + subok: builtins.bool = True, + copy: builtins.bool | _CopyMode = True, + ) -> Incomplete: ... + + # NOTE: `view` will perform a 0D->scalar cast, + # thus the array `type` is irrelevant to the output type + @overload + def view(self, type: type[ndarray] = ...) -> Self: ... + @overload + def view(self, /, dtype: _DTypeLike[_ScalarT], type: type[ndarray] = ...) -> _ScalarT: ... + @overload + def view(self, /, dtype: DTypeLike, type: type[ndarray] = ...) -> Incomplete: ... + + @overload + def getfield(self, /, dtype: _DTypeLike[_ScalarT], offset: SupportsIndex = 0) -> _ScalarT: ... + @overload + def getfield(self, /, dtype: DTypeLike, offset: SupportsIndex = 0) -> Incomplete: ... + + @overload + def take( + self, + indices: _IntLike_co, + /, + axis: SupportsIndex | None = None, + out: None = None, + mode: _ModeKind = "raise", + ) -> Self: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None = None, + out: None = None, + mode: _ModeKind = "raise", + ) -> NDArray[Self]: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None = None, + *, + out: _ArrayT, + mode: _ModeKind = "raise", + ) -> _ArrayT: ... + @overload + def take( + self, + indices: _ArrayLikeInt_co, + /, + axis: SupportsIndex | None, + out: _ArrayT, + mode: _ModeKind = "raise", + ) -> _ArrayT: ... + + def repeat(self, repeats: _ArrayLikeInt_co, /, axis: SupportsIndex | None = None) -> ndarray[tuple[int], dtype[Self]]: ... + def flatten(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], dtype[Self]]: ... + def ravel(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], dtype[Self]]: ... + + @overload # (() | []) + def reshape( + self, + shape: tuple[()] | list[Never], + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> Self: ... + @overload # ((1, *(1, ...))@_ShapeT) + def reshape( + self, + shape: _1NShapeT, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[_1NShapeT, dtype[Self]]: ... + @overload # (Sequence[index, ...]) # not recommended + def reshape( + self, + shape: Sequence[SupportsIndex], + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> Self | ndarray[tuple[L[1], ...], dtype[Self]]: ... + @overload # _(index) + def reshape( + self, + size1: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1]], dtype[Self]]: ... + @overload # _(index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1], L[1]], dtype[Self]]: ... + @overload # _(index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1], L[1], L[1]], dtype[Self]]: ... + @overload # _(index, index, index, index) + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + size4: SupportsIndex, + /, + *, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1], L[1], L[1], L[1]], dtype[Self]]: ... + @overload # _(index, index, index, index, index, *index) # ndim >= 5 + def reshape( + self, + size1: SupportsIndex, + size2: SupportsIndex, + size3: SupportsIndex, + size4: SupportsIndex, + size5: SupportsIndex, + /, + *sizes6_: SupportsIndex, + order: _OrderACF = "C", + copy: builtins.bool | None = None, + ) -> ndarray[tuple[L[1], L[1], L[1], L[1], L[1], *tuple[L[1], ...]], dtype[Self]]: ... + + def squeeze(self, axis: L[0] | tuple[()] | None = ...) -> Self: ... + def transpose(self, axes: tuple[()] | None = ..., /) -> Self: ... + + @overload + def all( + self, + /, + axis: L[0, -1] | tuple[()] | None = None, + out: None = None, + keepdims: SupportsIndex = False, + *, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True + ) -> np.bool: ... + @overload + def all( + self, + /, + axis: L[0, -1] | tuple[()] | None, + out: ndarray[tuple[()], dtype[_ScalarT]], + keepdims: SupportsIndex = False, + *, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True, + ) -> _ScalarT: ... + @overload + def all( + self, + /, + axis: L[0, -1] | tuple[()] | None = None, + *, + out: ndarray[tuple[()], dtype[_ScalarT]], + keepdims: SupportsIndex = False, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True, + ) -> _ScalarT: ... + + @overload + def any( + self, + /, + axis: L[0, -1] | tuple[()] | None = None, + out: None = None, + keepdims: SupportsIndex = False, + *, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True + ) -> np.bool: ... + @overload + def any( + self, + /, + axis: L[0, -1] | tuple[()] | None, + out: ndarray[tuple[()], dtype[_ScalarT]], + keepdims: SupportsIndex = False, + *, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True, + ) -> _ScalarT: ... + @overload + def any( + self, + /, + axis: L[0, -1] | tuple[()] | None = None, + *, + out: ndarray[tuple[()], dtype[_ScalarT]], + keepdims: SupportsIndex = False, + where: builtins.bool | np.bool | ndarray[tuple[()], dtype[np.bool]] = True, + ) -> _ScalarT: ... + + # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype` + @property + def dtype(self) -> _dtype[Self]: ... + +class number(generic[_NumberItemT_co], Generic[_NBit, _NumberItemT_co]): + @abstractmethod # `SupportsIndex | str | bytes` equivs `_ConvertibleToInt & _ConvertibleToFloat` + def __new__(cls, value: SupportsIndex | str | bytes = 0, /) -> Self: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + def __neg__(self) -> Self: ... + def __pos__(self) -> Self: ... + def __abs__(self) -> Self: ... + + def __add__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __radd__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __sub__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __rsub__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __mul__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __rmul__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __pow__(self, other: _NumberLike_co, mod: None = None, /) -> Incomplete: ... + def __rpow__(self, other: _NumberLike_co, mod: None = None, /) -> Incomplete: ... + def __truediv__(self, other: _NumberLike_co, /) -> Incomplete: ... + def __rtruediv__(self, other: _NumberLike_co, /) -> Incomplete: ... + + @overload + def __lt__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __lt__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsGT], /) -> NDArray[bool_]: ... + @overload + def __lt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __le__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __le__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsGE], /) -> NDArray[bool_]: ... + @overload + def __le__(self, other: _SupportsGE, /) -> bool_: ... + + @overload + def __gt__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __gt__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsLT], /) -> NDArray[bool_]: ... + @overload + def __gt__(self, other: _SupportsLT, /) -> bool_: ... + + @overload + def __ge__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __ge__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsLE], /) -> NDArray[bool_]: ... + @overload + def __ge__(self, other: _SupportsLE, /) -> bool_: ... + +class bool(generic[_BoolItemT_co], Generic[_BoolItemT_co]): + @property + def itemsize(self) -> L[1]: ... + @property + def nbytes(self) -> L[1]: ... + @property + def real(self) -> Self: ... + @property + def imag(self) -> np.bool[L[False]]: ... + + @overload # mypy bug workaround: https://github.com/numpy/numpy/issues/29245 + def __new__(cls, value: Never, /) -> np.bool[builtins.bool]: ... + @overload + def __new__(cls, value: _Falsy = ..., /) -> np.bool[L[False]]: ... + @overload + def __new__(cls, value: _Truthy, /) -> np.bool[L[True]]: ... + @overload + def __new__(cls, value: object, /) -> np.bool[builtins.bool]: ... + + def __class_getitem__(cls, type_arg: type | object, /) -> GenericAlias: ... + + def __bool__(self, /) -> _BoolItemT_co: ... + + @overload + def __int__(self: np.bool[L[False]], /) -> L[0]: ... + @overload + def __int__(self: np.bool[L[True]], /) -> L[1]: ... + @overload + def __int__(self, /) -> L[0, 1]: ... + + def __abs__(self) -> Self: ... + + @overload + def __invert__(self: np.bool[L[False]], /) -> np.bool[L[True]]: ... + @overload + def __invert__(self: np.bool[L[True]], /) -> np.bool[L[False]]: ... + @overload + def __invert__(self, /) -> np.bool: ... + + @overload + def __add__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __add__(self, other: builtins.bool | bool_, /) -> bool_: ... + @overload + def __add__(self, other: int, /) -> int_: ... + @overload + def __add__(self, other: float, /) -> float64: ... + @overload + def __add__(self, other: complex, /) -> complex128: ... + + @overload + def __radd__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __radd__(self, other: builtins.bool, /) -> bool_: ... + @overload + def __radd__(self, other: int, /) -> int_: ... + @overload + def __radd__(self, other: float, /) -> float64: ... + @overload + def __radd__(self, other: complex, /) -> complex128: ... + + @overload + def __sub__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __sub__(self, other: int, /) -> int_: ... + @overload + def __sub__(self, other: float, /) -> float64: ... + @overload + def __sub__(self, other: complex, /) -> complex128: ... + + @overload + def __rsub__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __rsub__(self, other: int, /) -> int_: ... + @overload + def __rsub__(self, other: float, /) -> float64: ... + @overload + def __rsub__(self, other: complex, /) -> complex128: ... + + @overload + def __mul__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __mul__(self, other: builtins.bool | bool_, /) -> bool_: ... + @overload + def __mul__(self, other: int, /) -> int_: ... + @overload + def __mul__(self, other: float, /) -> float64: ... + @overload + def __mul__(self, other: complex, /) -> complex128: ... + + @overload + def __rmul__(self, other: _NumberT, /) -> _NumberT: ... + @overload + def __rmul__(self, other: builtins.bool, /) -> bool_: ... + @overload + def __rmul__(self, other: int, /) -> int_: ... + @overload + def __rmul__(self, other: float, /) -> float64: ... + @overload + def __rmul__(self, other: complex, /) -> complex128: ... + + @overload + def __pow__(self, other: _NumberT, mod: None = None, /) -> _NumberT: ... + @overload + def __pow__(self, other: builtins.bool | bool_, mod: None = None, /) -> int8: ... + @overload + def __pow__(self, other: int, mod: None = None, /) -> int_: ... + @overload + def __pow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> complex128: ... + + @overload + def __rpow__(self, other: _NumberT, mod: None = None, /) -> _NumberT: ... + @overload + def __rpow__(self, other: builtins.bool, mod: None = None, /) -> int8: ... + @overload + def __rpow__(self, other: int, mod: None = None, /) -> int_: ... + @overload + def __rpow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complex128: ... + + @overload + def __truediv__(self, other: _InexactT, /) -> _InexactT: ... + @overload + def __truediv__(self, other: float | integer | bool_, /) -> float64: ... + @overload + def __truediv__(self, other: complex, /) -> complex128: ... + + @overload + def __rtruediv__(self, other: _InexactT, /) -> _InexactT: ... + @overload + def __rtruediv__(self, other: float | integer, /) -> float64: ... + @overload + def __rtruediv__(self, other: complex, /) -> complex128: ... + + @overload + def __floordiv__(self, other: _RealNumberT, /) -> _RealNumberT: ... + @overload + def __floordiv__(self, other: builtins.bool | bool_, /) -> int8: ... + @overload + def __floordiv__(self, other: int, /) -> int_: ... + @overload + def __floordiv__(self, other: float, /) -> float64: ... + + @overload + def __rfloordiv__(self, other: _RealNumberT, /) -> _RealNumberT: ... + @overload + def __rfloordiv__(self, other: builtins.bool, /) -> int8: ... + @overload + def __rfloordiv__(self, other: int, /) -> int_: ... + @overload + def __rfloordiv__(self, other: float, /) -> float64: ... + + # keep in sync with __floordiv__ + @overload + def __mod__(self, other: _RealNumberT, /) -> _RealNumberT: ... + @overload + def __mod__(self, other: builtins.bool | bool_, /) -> int8: ... + @overload + def __mod__(self, other: int, /) -> int_: ... + @overload + def __mod__(self, other: float, /) -> float64: ... + + # keep in sync with __rfloordiv__ + @overload + def __rmod__(self, other: _RealNumberT, /) -> _RealNumberT: ... + @overload + def __rmod__(self, other: builtins.bool, /) -> int8: ... + @overload + def __rmod__(self, other: int, /) -> int_: ... + @overload + def __rmod__(self, other: float, /) -> float64: ... + + # keep in sync with __mod__ + @overload + def __divmod__(self, other: _RealNumberT, /) -> _2Tuple[_RealNumberT]: ... + @overload + def __divmod__(self, other: builtins.bool | bool_, /) -> _2Tuple[int8]: ... + @overload + def __divmod__(self, other: int, /) -> _2Tuple[int_]: ... + @overload + def __divmod__(self, other: float, /) -> _2Tuple[float64]: ... + + # keep in sync with __rmod__ + @overload + def __rdivmod__(self, other: _RealNumberT, /) -> _2Tuple[_RealNumberT]: ... + @overload + def __rdivmod__(self, other: builtins.bool, /) -> _2Tuple[int8]: ... + @overload + def __rdivmod__(self, other: int, /) -> _2Tuple[int_]: ... + @overload + def __rdivmod__(self, other: float, /) -> _2Tuple[float64]: ... + + @overload + def __lshift__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __lshift__(self, other: builtins.bool | bool_, /) -> int8: ... + @overload + def __lshift__(self, other: int, /) -> int_: ... + + @overload + def __rlshift__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __rlshift__(self, other: builtins.bool, /) -> int8: ... + @overload + def __rlshift__(self, other: int, /) -> int_: ... + + # keep in sync with __lshift__ + @overload + def __rshift__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __rshift__(self, other: builtins.bool | bool_, /) -> int8: ... + @overload + def __rshift__(self, other: int, /) -> int_: ... + + # keep in sync with __rlshift__ + @overload + def __rrshift__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __rrshift__(self, other: builtins.bool, /) -> int8: ... + @overload + def __rrshift__(self, other: int, /) -> int_: ... + + @overload + def __and__(self: np.bool[L[False]], other: builtins.bool | np.bool, /) -> np.bool[L[False]]: ... + @overload + def __and__(self, other: L[False] | np.bool[L[False]], /) -> np.bool[L[False]]: ... + @overload + def __and__(self, other: L[True] | np.bool[L[True]], /) -> Self: ... + @overload + def __and__(self, other: builtins.bool | np.bool, /) -> np.bool: ... + @overload + def __and__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __and__(self, other: int, /) -> np.bool | intp: ... + __rand__ = __and__ + + @overload + def __xor__(self: np.bool[L[False]], other: _BoolItemT | np.bool[_BoolItemT], /) -> np.bool[_BoolItemT]: ... + @overload + def __xor__(self: np.bool[L[True]], other: L[True] | np.bool[L[True]], /) -> np.bool[L[False]]: ... + @overload + def __xor__(self, other: L[False] | np.bool[L[False]], /) -> Self: ... + @overload + def __xor__(self, other: builtins.bool | np.bool, /) -> np.bool: ... + @overload + def __xor__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __xor__(self, other: int, /) -> np.bool | intp: ... + __rxor__ = __xor__ + + @overload + def __or__(self: np.bool[L[True]], other: builtins.bool | np.bool, /) -> np.bool[L[True]]: ... + @overload + def __or__(self, other: L[False] | np.bool[L[False]], /) -> Self: ... + @overload + def __or__(self, other: L[True] | np.bool[L[True]], /) -> np.bool[L[True]]: ... + @overload + def __or__(self, other: builtins.bool | np.bool, /) -> np.bool: ... + @overload + def __or__(self, other: _IntegerT, /) -> _IntegerT: ... + @overload + def __or__(self, other: int, /) -> np.bool | intp: ... + __ror__ = __or__ + + @overload + def __lt__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __lt__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsGT], /) -> NDArray[bool_]: ... + @overload + def __lt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __le__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __le__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsGE], /) -> NDArray[bool_]: ... + @overload + def __le__(self, other: _SupportsGE, /) -> bool_: ... + + @overload + def __gt__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __gt__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsLT], /) -> NDArray[bool_]: ... + @overload + def __gt__(self, other: _SupportsLT, /) -> bool_: ... + + @overload + def __ge__(self, other: _NumberLike_co, /) -> bool_: ... + @overload + def __ge__(self, other: _ArrayLikeNumber_co | _NestedSequence[_SupportsLE], /) -> NDArray[bool_]: ... + @overload + def __ge__(self, other: _SupportsLE, /) -> bool_: ... + +# NOTE: This should _not_ be `Final` or a `TypeAlias` +bool_ = bool + +# NOTE: The `object_` constructor returns the passed object, so instances with type +# `object_` cannot exists (at runtime). +# NOTE: Because mypy has some long-standing bugs related to `__new__`, `object_` can't +# be made generic. +@final +class object_(_RealMixin, generic): + @overload + def __new__(cls, value: None = None, /) -> None: ... # type: ignore[misc] + @overload + def __new__(cls, value: _AnyStr, /) -> _AnyStr: ... # type: ignore[misc] + @overload + def __new__(cls, value: ndarray[_ShapeT, Any], /) -> ndarray[_ShapeT, dtype[Self]]: ... # type: ignore[misc] + @overload + def __new__(cls, value: SupportsLenAndGetItem[object], /) -> NDArray[Self]: ... # type: ignore[misc] + @overload + def __new__(cls, value: _T, /) -> _T: ... # type: ignore[misc] + @overload # catch-all + def __new__(cls, value: Any = ..., /) -> object | NDArray[Self]: ... # type: ignore[misc] + + def __hash__(self, /) -> int: ... + def __abs__(self, /) -> object_: ... # this affects NDArray[object_].__abs__ + def __call__(self, /, *args: object, **kwargs: object) -> Any: ... + + if sys.version_info >= (3, 12): + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + +class integer(_IntegralMixin, _RoundMixin, number[_NBit, int]): + @abstractmethod + def __new__(cls, value: _ConvertibleToInt = 0, /) -> Self: ... + + # NOTE: `bit_count` and `__index__` are technically defined in the concrete subtypes + def bit_count(self, /) -> int: ... + def __index__(self, /) -> int: ... + def __invert__(self, /) -> Self: ... + + @override # type: ignore[override] + @overload + def __truediv__(self, other: float | integer, /) -> float64: ... + @overload + def __truediv__(self, other: complex, /) -> complex128: ... + + @override # type: ignore[override] + @overload + def __rtruediv__(self, other: float | integer, /) -> float64: ... + @overload + def __rtruediv__(self, other: complex, /) -> complex128: ... + + def __floordiv__(self, value: _IntLike_co, /) -> integer: ... + def __rfloordiv__(self, value: _IntLike_co, /) -> integer: ... + def __mod__(self, value: _IntLike_co, /) -> integer: ... + def __rmod__(self, value: _IntLike_co, /) -> integer: ... + def __divmod__(self, value: _IntLike_co, /) -> _2Tuple[integer]: ... + def __rdivmod__(self, value: _IntLike_co, /) -> _2Tuple[integer]: ... + + # Ensure that objects annotated as `integer` support bit-wise operations + def __lshift__(self, other: _IntLike_co, /) -> integer: ... + def __rlshift__(self, other: _IntLike_co, /) -> integer: ... + def __rshift__(self, other: _IntLike_co, /) -> integer: ... + def __rrshift__(self, other: _IntLike_co, /) -> integer: ... + def __and__(self, other: _IntLike_co, /) -> integer: ... + def __rand__(self, other: _IntLike_co, /) -> integer: ... + def __or__(self, other: _IntLike_co, /) -> integer: ... + def __ror__(self, other: _IntLike_co, /) -> integer: ... + def __xor__(self, other: _IntLike_co, /) -> integer: ... + def __rxor__(self, other: _IntLike_co, /) -> integer: ... + +class signedinteger(integer[_NBit]): + def __new__(cls, value: _ConvertibleToInt = 0, /) -> Self: ... + + # arithmetic ops + + @override # type: ignore[override] + @overload + def __add__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __add__(self, other: float, /) -> float64: ... + @overload + def __add__(self, other: complex, /) -> complex128: ... + @overload + def __add__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __add__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __radd__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __radd__(self, other: float, /) -> float64: ... + @overload + def __radd__(self, other: complex, /) -> complex128: ... + @overload + def __radd__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __radd__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __sub__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __sub__(self, other: float, /) -> float64: ... + @overload + def __sub__(self, other: complex, /) -> complex128: ... + @overload + def __sub__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __sub__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rsub__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rsub__(self, other: float, /) -> float64: ... + @overload + def __rsub__(self, other: complex, /) -> complex128: ... + @overload + def __rsub__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __rsub__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __mul__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __mul__(self, other: float, /) -> float64: ... + @overload + def __mul__(self, other: complex, /) -> complex128: ... + @overload + def __mul__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __mul__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rmul__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rmul__(self, other: float, /) -> float64: ... + @overload + def __rmul__(self, other: complex, /) -> complex128: ... + @overload + def __rmul__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __rmul__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __pow__(self, other: int | int8 | bool_ | Self, mod: None = None, /) -> Self: ... + @overload + def __pow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> complex128: ... + @overload + def __pow__(self, other: signedinteger, mod: None = None, /) -> signedinteger: ... + @overload + def __pow__(self, other: integer, mod: None = None, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rpow__(self, other: int | int8 | bool_, mod: None = None, /) -> Self: ... + @overload + def __rpow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complex128: ... + @overload + def __rpow__(self, other: signedinteger, mod: None = None, /) -> signedinteger: ... + @overload + def __rpow__(self, other: integer, mod: None = None, /) -> Incomplete: ... + + # modular division ops + + @override # type: ignore[override] + @overload + def __floordiv__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __floordiv__(self, other: float, /) -> float64: ... + @overload + def __floordiv__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __floordiv__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rfloordiv__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rfloordiv__(self, other: float, /) -> float64: ... + @overload + def __rfloordiv__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __rfloordiv__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __mod__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __mod__(self, other: float, /) -> float64: ... + @overload + def __mod__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __mod__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rmod__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rmod__(self, other: float, /) -> float64: ... + @overload + def __rmod__(self, other: signedinteger, /) -> signedinteger: ... + @overload + def __rmod__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __divmod__(self, other: int | int8 | bool_ | Self, /) -> _2Tuple[Self]: ... + @overload + def __divmod__(self, other: float, /) -> _2Tuple[float64]: ... + @overload + def __divmod__(self, other: signedinteger, /) -> _2Tuple[signedinteger]: ... + @overload + def __divmod__(self, other: integer, /) -> _2Tuple[Incomplete]: ... + + @override # type: ignore[override] + @overload + def __rdivmod__(self, other: int | int8 | bool_, /) -> _2Tuple[Self]: ... + @overload + def __rdivmod__(self, other: float, /) -> _2Tuple[float64]: ... + @overload + def __rdivmod__(self, other: signedinteger, /) -> _2Tuple[signedinteger]: ... + @overload + def __rdivmod__(self, other: integer, /) -> _2Tuple[Incomplete]: ... + + # bitwise ops + + @override # type: ignore[override] + @overload + def __lshift__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __lshift__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rlshift__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rlshift__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rshift__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __rshift__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rrshift__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rrshift__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __and__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __and__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rand__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rand__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __xor__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __xor__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rxor__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rxor__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __or__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __or__(self, other: integer, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __ror__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __ror__(self, other: integer, /) -> signedinteger: ... + +int8 = signedinteger[_8Bit] +int16 = signedinteger[_16Bit] +int32 = signedinteger[_32Bit] +int64 = signedinteger[_64Bit] + +byte = signedinteger[_NBitByte] +short = signedinteger[_NBitShort] +intc = signedinteger[_NBitIntC] +intp = signedinteger[_NBitIntP] +int_ = intp +long = signedinteger[_NBitLong] +longlong = signedinteger[_NBitLongLong] + +class unsignedinteger(integer[_NBit1]): + def __new__(cls, value: _ConvertibleToInt = 0, /) -> Self: ... + + # arithmetic ops + + @override # type: ignore[override] + @overload + def __add__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __add__(self, other: float, /) -> float64: ... + @overload + def __add__(self, other: complex, /) -> complex128: ... + @overload + def __add__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __add__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __radd__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __radd__(self, other: float, /) -> float64: ... + @overload + def __radd__(self, other: complex, /) -> complex128: ... + @overload + def __radd__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __radd__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __sub__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __sub__(self, other: float, /) -> float64: ... + @overload + def __sub__(self, other: complex, /) -> complex128: ... + @overload + def __sub__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __sub__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rsub__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __rsub__(self, other: float, /) -> float64: ... + @overload + def __rsub__(self, other: complex, /) -> complex128: ... + @overload + def __rsub__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rsub__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __mul__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __mul__(self, other: float, /) -> float64: ... + @overload + def __mul__(self, other: complex, /) -> complex128: ... + @overload + def __mul__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __mul__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rmul__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __rmul__(self, other: float, /) -> float64: ... + @overload + def __rmul__(self, other: complex, /) -> complex128: ... + @overload + def __rmul__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rmul__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __pow__(self, other: int | uint8 | bool_ | Self, mod: None = None, /) -> Self: ... + @overload + def __pow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> complex128: ... + @overload + def __pow__(self, other: unsignedinteger, mod: None = None, /) -> unsignedinteger: ... + @overload + def __pow__(self, other: integer, mod: None = None, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rpow__(self, other: int | uint8 | bool_, mod: None = None, /) -> Self: ... + @overload + def __rpow__(self, other: float, mod: None = None, /) -> float64: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complex128: ... + @overload + def __rpow__(self, other: unsignedinteger, mod: None = None, /) -> unsignedinteger: ... + @overload + def __rpow__(self, other: integer, mod: None = None, /) -> Incomplete: ... + + # modular division ops + + @override # type: ignore[override] + @overload + def __floordiv__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __floordiv__(self, other: float, /) -> float64: ... + @overload + def __floordiv__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __floordiv__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rfloordiv__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __rfloordiv__(self, other: float, /) -> float64: ... + @overload + def __rfloordiv__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rfloordiv__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __mod__(self, other: int | uint8 | bool_ | Self, /) -> Self: ... + @overload + def __mod__(self, other: float, /) -> float64: ... + @overload + def __mod__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __mod__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __rmod__(self, other: int | uint8 | bool_, /) -> Self: ... + @overload + def __rmod__(self, other: float, /) -> float64: ... + @overload + def __rmod__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rmod__(self, other: integer, /) -> Incomplete: ... + + @override # type: ignore[override] + @overload + def __divmod__(self, other: int | uint8 | bool_ | Self, /) -> _2Tuple[Self]: ... + @overload + def __divmod__(self, other: float, /) -> _2Tuple[float64]: ... + @overload + def __divmod__(self, other: unsignedinteger, /) -> _2Tuple[unsignedinteger]: ... + @overload + def __divmod__(self, other: integer, /) -> _2Tuple[Incomplete]: ... + + @override # type: ignore[override] + @overload + def __rdivmod__(self, other: int | uint8 | bool_, /) -> _2Tuple[Self]: ... + @overload + def __rdivmod__(self, other: float, /) -> _2Tuple[float64]: ... + @overload + def __rdivmod__(self, other: unsignedinteger, /) -> _2Tuple[unsignedinteger]: ... + @overload + def __rdivmod__(self, other: integer, /) -> _2Tuple[Incomplete]: ... + + # bitwise ops + + @override # type: ignore[override] + @overload + def __lshift__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __lshift__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __lshift__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rlshift__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rlshift__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rlshift__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rshift__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __rshift__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rshift__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rrshift__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rrshift__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rrshift__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __and__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __and__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __and__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rand__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rand__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rand__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __xor__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __xor__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __xor__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __rxor__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __rxor__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __rxor__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __or__(self, other: int | int8 | bool_ | Self, /) -> Self: ... + @overload + def __or__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __or__(self, other: signedinteger, /) -> signedinteger: ... + + @override # type: ignore[override] + @overload + def __ror__(self, other: int | int8 | bool_, /) -> Self: ... + @overload + def __ror__(self, other: unsignedinteger, /) -> unsignedinteger: ... + @overload + def __ror__(self, other: signedinteger, /) -> signedinteger: ... + +uint8: TypeAlias = unsignedinteger[_8Bit] +uint16: TypeAlias = unsignedinteger[_16Bit] +uint32: TypeAlias = unsignedinteger[_32Bit] +uint64: TypeAlias = unsignedinteger[_64Bit] + +ubyte: TypeAlias = unsignedinteger[_NBitByte] +ushort: TypeAlias = unsignedinteger[_NBitShort] +uintc: TypeAlias = unsignedinteger[_NBitIntC] +uintp: TypeAlias = unsignedinteger[_NBitIntP] +uint: TypeAlias = uintp +ulong: TypeAlias = unsignedinteger[_NBitLong] +ulonglong: TypeAlias = unsignedinteger[_NBitLongLong] + +class inexact(number[_NBit, _InexactItemT_co], Generic[_NBit, _InexactItemT_co]): + @abstractmethod + def __new__(cls, value: _ConvertibleToFloat | None = 0, /) -> Self: ... + +class floating(_RealMixin, _RoundMixin, inexact[_NBit1, float]): + def __new__(cls, value: _ConvertibleToFloat | None = 0, /) -> Self: ... + + # arithmetic ops + + @override # type: ignore[override] + @overload + def __add__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __add__(self, other: integer | floating, /) -> floating: ... + @overload + def __add__(self, other: float, /) -> Self: ... + @overload + def __add__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __radd__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __radd__(self, other: integer | floating, /) -> floating: ... + @overload + def __radd__(self, other: float, /) -> Self: ... + @overload + def __radd__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __sub__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __sub__(self, other: integer | floating, /) -> floating: ... + @overload + def __sub__(self, other: float, /) -> Self: ... + @overload + def __sub__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __rsub__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rsub__(self, other: integer | floating, /) -> floating: ... + @overload + def __rsub__(self, other: float, /) -> Self: ... + @overload + def __rsub__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __mul__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __mul__(self, other: integer | floating, /) -> floating: ... + @overload + def __mul__(self, other: float, /) -> Self: ... + @overload + def __mul__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __rmul__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rmul__(self, other: integer | floating, /) -> floating: ... + @overload + def __rmul__(self, other: float, /) -> Self: ... + @overload + def __rmul__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __pow__(self, other: int | float16 | uint8 | int8 | bool_ | Self, mod: None = None, /) -> Self: ... + @overload + def __pow__(self, other: integer | floating, mod: None = None, /) -> floating: ... + @overload + def __pow__(self, other: float, mod: None = None, /) -> Self: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __rpow__(self, other: int | float16 | uint8 | int8 | bool_, mod: None = None, /) -> Self: ... + @overload + def __rpow__(self, other: integer | floating, mod: None = None, /) -> floating: ... + @overload + def __rpow__(self, other: float, mod: None = None, /) -> Self: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __truediv__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __truediv__(self, other: integer | floating, /) -> floating: ... + @overload + def __truediv__(self, other: float, /) -> Self: ... + @overload + def __truediv__(self, other: complex, /) -> complexfloating: ... + + @override # type: ignore[override] + @overload + def __rtruediv__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rtruediv__(self, other: integer | floating, /) -> floating: ... + @overload + def __rtruediv__(self, other: float, /) -> Self: ... + @overload + def __rtruediv__(self, other: complex, /) -> complexfloating: ... + + # modular division ops + + @overload + def __floordiv__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __floordiv__(self, other: integer | floating, /) -> floating: ... + @overload + def __floordiv__(self, other: float, /) -> Self: ... + + @overload + def __rfloordiv__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rfloordiv__(self, other: integer | floating, /) -> floating: ... + @overload + def __rfloordiv__(self, other: float, /) -> Self: ... + + @overload + def __mod__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> Self: ... + @overload + def __mod__(self, other: integer | floating, /) -> floating: ... + @overload + def __mod__(self, other: float, /) -> Self: ... + + @overload + def __rmod__(self, other: int | float16 | uint8 | int8 | bool_, /) -> Self: ... + @overload + def __rmod__(self, other: integer | floating, /) -> floating: ... + @overload + def __rmod__(self, other: float, /) -> Self: ... + + @overload + def __divmod__(self, other: int | float16 | uint8 | int8 | bool_ | Self, /) -> _2Tuple[Self]: ... + @overload + def __divmod__(self, other: integer | floating, /) -> _2Tuple[floating]: ... + @overload + def __divmod__(self, other: float, /) -> _2Tuple[Self]: ... + + @overload + def __rdivmod__(self, other: int | float16 | uint8 | int8 | bool_, /) -> _2Tuple[Self]: ... + @overload + def __rdivmod__(self, other: integer | floating, /) -> _2Tuple[floating]: ... + @overload + def __rdivmod__(self, other: float, /) -> _2Tuple[Self]: ... + + # NOTE: `is_integer` and `as_integer_ratio` are technically defined in the concrete subtypes + def is_integer(self, /) -> builtins.bool: ... + def as_integer_ratio(self, /) -> tuple[int, int]: ... + +float16: TypeAlias = floating[_16Bit] +float32: TypeAlias = floating[_32Bit] + +# either a C `double`, `float`, or `longdouble` +class float64(floating[_64Bit], float): # type: ignore[misc] + @property + def itemsize(self) -> L[8]: ... + @property + def nbytes(self) -> L[8]: ... + + # overrides for `floating` and `builtins.float` compatibility (`_RealMixin` doesn't work) + @property + def real(self) -> Self: ... + @property + def imag(self) -> Self: ... + def conjugate(self) -> Self: ... + def __getnewargs__(self, /) -> tuple[float]: ... + + @classmethod + def __getformat__(cls, typestr: L["double", "float"], /) -> str: ... # undocumented + + # float64-specific operator overrides + # NOTE: Mypy reports [misc] errors about "unsafely overlapping signatures" for the + # reflected methods. But since they are identical to the non-reflected versions, + # these errors appear to be false positives. + + @overload # type: ignore[override] + def __add__(self, other: _Float64_co, /) -> float64: ... + @overload + def __add__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __add__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __add__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __radd__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __radd__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... # type: ignore[misc] + @overload + def __radd__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __radd__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __sub__(self, other: _Float64_co, /) -> float64: ... + @overload + def __sub__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __sub__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __sub__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __rsub__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __rsub__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... # type: ignore[misc] + @overload + def __rsub__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rsub__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __mul__(self, other: _Float64_co, /) -> float64: ... + @overload + def __mul__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __mul__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __mul__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __rmul__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __rmul__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... # type: ignore[misc] + @overload + def __rmul__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rmul__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __truediv__(self, other: _Float64_co, /) -> float64: ... + @overload + def __truediv__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __truediv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __truediv__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __rtruediv__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __rtruediv__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... # type: ignore[misc] + @overload + def __rtruediv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rtruediv__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __floordiv__(self, other: _Float64_co, /) -> float64: ... + @overload + def __floordiv__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __floordiv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __floordiv__(self, other: complex, /) -> float64 | complex128: ... + + @overload + def __rfloordiv__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + @overload + def __rfloordiv__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ... + @overload + def __rfloordiv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rfloordiv__(self, other: complex, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __pow__(self, other: _Float64_co, mod: None = None, /) -> float64: ... + @overload + def __pow__(self, other: complexfloating[_64Bit, _64Bit], mod: None = None, /) -> complex128: ... + @overload + def __pow__( + self, other: complexfloating[_NBit1, _NBit2], mod: None = None, / + ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __pow__(self, other: complex, mod: None = None, /) -> float64 | complex128: ... + + @overload # type: ignore[override] + def __rpow__(self, other: _Float64_co, mod: None = None, /) -> float64: ... # type: ignore[misc] + @overload + def __rpow__(self, other: complexfloating[_64Bit, _64Bit], mod: None = None, /) -> complex128: ... # type: ignore[misc] + @overload + def __rpow__( + self, other: complexfloating[_NBit1, _NBit2], mod: None = None, / + ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> float64 | complex128: ... + + def __mod__(self, other: _Float64_co, /) -> float64: ... + def __rmod__(self, other: _Float64_co, /) -> float64: ... # type: ignore[misc] + + def __divmod__(self, other: _Float64_co, /) -> _2Tuple[float64]: ... + def __rdivmod__(self, other: _Float64_co, /) -> _2Tuple[float64]: ... # type: ignore[misc] + +half: TypeAlias = float16 +single: TypeAlias = float32 +double: TypeAlias = float64 +longdouble: TypeAlias = floating[_NBitLongDouble] + +# The main reason for `complexfloating` having two typevars is cosmetic. +# It is used to clarify why `complex128`s precision is `_64Bit`, the latter +# describing the two 64 bit floats representing its real and imaginary component + +class complexfloating(inexact[_NBit1, complex], Generic[_NBit1, _NBit2]): + @overload + def __new__( + cls, + real: complex | SupportsComplex | SupportsFloat | SupportsIndex = 0, + imag: complex | SupportsFloat | SupportsIndex = 0, + /, + ) -> Self: ... + @overload + def __new__(cls, real: _ConvertibleToComplex | None = 0, /) -> Self: ... + + @property + def real(self) -> floating[_NBit1]: ... + @property + def imag(self) -> floating[_NBit2]: ... + + # NOTE: `__complex__` is technically defined in the concrete subtypes + def __complex__(self, /) -> complex: ... + def __abs__(self, /) -> floating[_NBit1 | _NBit2]: ... # type: ignore[override] + + @overload # type: ignore[override] + def __add__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __add__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __add__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __radd__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __radd__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __radd__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __sub__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __sub__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __sub__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __rsub__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __rsub__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __rsub__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __mul__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __mul__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __mul__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __rmul__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __rmul__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __rmul__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __truediv__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __truediv__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __truediv__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __rtruediv__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __rtruediv__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __rtruediv__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __pow__(self, other: _Complex64_co, mod: None = None, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __pow__( + self, other: complex | float64 | complex128, mod: None = None, / + ) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __pow__( + self, other: number[_NBit], mod: None = None, / + ) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + + @overload # type: ignore[override] + def __rpow__(self, other: _Complex64_co, mod: None = None, /) -> complexfloating[_NBit1, _NBit2]: ... + @overload + def __rpow__(self, other: complex, mod: None = None, /) -> complexfloating[_NBit1, _NBit2] | complex128: ... + @overload + def __rpow__( + self, other: number[_NBit], mod: None = None, / + ) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ... + +complex64: TypeAlias = complexfloating[_32Bit] + +class complex128(complexfloating[_64Bit, _64Bit], complex): + @property + def itemsize(self) -> L[16]: ... + @property + def nbytes(self) -> L[16]: ... + + # overrides for `floating` and `builtins.float` compatibility + @property + def real(self) -> float64: ... + @property + def imag(self) -> float64: ... + def conjugate(self) -> Self: ... + def __abs__(self) -> float64: ... # type: ignore[override] + def __getnewargs__(self, /) -> tuple[float, float]: ... + + # complex128-specific operator overrides + @overload # type: ignore[override] + def __add__(self, other: _Complex128_co, /) -> complex128: ... + @overload + def __add__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __radd__(self, other: _Complex128_co, /) -> complex128: ... # type: ignore[override] + + @overload # type: ignore[override] + def __sub__(self, other: _Complex128_co, /) -> complex128: ... + @overload + def __sub__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __rsub__(self, other: _Complex128_co, /) -> complex128: ... # type: ignore[override] + + @overload # type: ignore[override] + def __mul__(self, other: _Complex128_co, /) -> complex128: ... + @overload + def __mul__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __rmul__(self, other: _Complex128_co, /) -> complex128: ... # type: ignore[override] + + @overload # type: ignore[override] + def __truediv__(self, other: _Complex128_co, /) -> complex128: ... + @overload + def __truediv__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __rtruediv__(self, other: _Complex128_co, /) -> complex128: ... # type: ignore[override] + + @overload # type: ignore[override] + def __pow__(self, other: _Complex128_co, mod: None = None, /) -> complex128: ... + @overload + def __pow__( + self, other: complexfloating[_NBit1, _NBit2], mod: None = None, / + ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ... + def __rpow__(self, other: _Complex128_co, mod: None = None, /) -> complex128: ... # type: ignore[override] + +csingle: TypeAlias = complex64 +cdouble: TypeAlias = complex128 +clongdouble: TypeAlias = complexfloating[_NBitLongDouble] + +class timedelta64(_IntegralMixin, generic[_TD64ItemT_co], Generic[_TD64ItemT_co]): + @property + def itemsize(self) -> L[8]: ... + @property + def nbytes(self) -> L[8]: ... + + @overload + def __new__(cls, value: _TD64ItemT_co | timedelta64[_TD64ItemT_co], /) -> Self: ... + @overload + def __new__(cls, /) -> timedelta64[L[0]]: ... + @overload + def __new__(cls, value: _NaTValue | None, format: _TimeUnitSpec, /) -> timedelta64[None]: ... + @overload + def __new__(cls, value: L[0], format: _TimeUnitSpec[_IntTD64Unit] = ..., /) -> timedelta64[L[0]]: ... + @overload + def __new__(cls, value: _IntLike_co, format: _TimeUnitSpec[_IntTD64Unit] = ..., /) -> timedelta64[int]: ... + @overload + def __new__(cls, value: dt.timedelta, format: _TimeUnitSpec[_IntTimeUnit], /) -> timedelta64[int]: ... + @overload + def __new__( + cls, + value: dt.timedelta | _IntLike_co, + format: _TimeUnitSpec[_NativeTD64Unit] = ..., + /, + ) -> timedelta64[dt.timedelta]: ... + @overload + def __new__(cls, value: _ConvertibleToTD64, format: _TimeUnitSpec = ..., /) -> Self: ... + + # inherited at runtime from `signedinteger` + def __class_getitem__(cls, type_arg: type | object, /) -> GenericAlias: ... + + # NOTE: Only a limited number of units support conversion + # to builtin scalar types: `Y`, `M`, `ns`, `ps`, `fs`, `as` + def __int__(self: timedelta64[int], /) -> int: ... + def __float__(self: timedelta64[int], /) -> float: ... + + def __neg__(self, /) -> Self: ... + def __pos__(self, /) -> Self: ... + def __abs__(self, /) -> Self: ... + + @overload + def __add__(self: timedelta64[None], x: _TD64Like_co, /) -> timedelta64[None]: ... + @overload + def __add__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> timedelta64[int]: ... + @overload + def __add__(self: timedelta64[int], x: timedelta64, /) -> timedelta64[int | None]: ... + @overload + def __add__(self: timedelta64[dt.timedelta], x: _AnyDateOrTime, /) -> _AnyDateOrTime: ... + @overload + def __add__(self: timedelta64[_AnyTD64Item], x: timedelta64[_AnyTD64Item] | _IntLike_co, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __add__(self, x: timedelta64[None], /) -> timedelta64[None]: ... # type: ignore[overload-cannot-match] + __radd__ = __add__ + + @overload + def __mul__(self: timedelta64[_AnyTD64Item], x: int | np.integer | np.bool, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __mul__(self: timedelta64[_AnyTD64Item], x: float | np.floating, /) -> timedelta64[_AnyTD64Item | None]: ... + @overload + def __mul__(self, x: float | np.floating | np.integer | np.bool, /) -> timedelta64: ... + __rmul__ = __mul__ + + @overload + def __mod__(self, x: timedelta64[L[0] | None], /) -> timedelta64[None]: ... + @overload + def __mod__(self: timedelta64[None], x: timedelta64, /) -> timedelta64[None]: ... + @overload + def __mod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> timedelta64[int | None]: ... + @overload + def __mod__(self: timedelta64[dt.timedelta], x: timedelta64[_AnyTD64Item], /) -> timedelta64[_AnyTD64Item | None]: ... + @overload + def __mod__(self: timedelta64[dt.timedelta], x: dt.timedelta, /) -> dt.timedelta: ... + @overload + def __mod__(self, x: timedelta64[int], /) -> timedelta64[int | None]: ... + @overload + def __mod__(self, x: timedelta64, /) -> timedelta64: ... + + # NOTE: The L[0] makes __mod__ non-commutative, which the first two overloads + # reflect. However, mypy does not seem to like this, so we ignore the errors. + @overload + def __rmod__(self, x: timedelta64[None], /) -> timedelta64[None]: ... # type: ignore[misc] + @overload + def __rmod__(self: timedelta64[L[0] | None], x: timedelta64, /) -> timedelta64[None]: ... + @overload + def __rmod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> timedelta64[int | None]: ... # type: ignore[misc] + @overload + def __rmod__(self: timedelta64[dt.timedelta], x: timedelta64[_AnyTD64Item], /) -> timedelta64[_AnyTD64Item | None]: ... # type: ignore[misc] + @overload + def __rmod__(self: timedelta64[dt.timedelta], x: dt.timedelta, /) -> dt.timedelta: ... + @overload + def __rmod__(self, x: timedelta64[int], /) -> timedelta64[int | None]: ... # type: ignore[misc] + @overload + def __rmod__(self, x: timedelta64, /) -> timedelta64: ... # type: ignore[misc] + + # keep in sync with __mod__ + @overload + def __divmod__(self, x: timedelta64[L[0] | None], /) -> tuple[int64, timedelta64[None]]: ... + @overload + def __divmod__(self: timedelta64[None], x: timedelta64, /) -> tuple[int64, timedelta64[None]]: ... + @overload + def __divmod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> tuple[int64, timedelta64[int | None]]: ... + @overload + def __divmod__( + self: timedelta64[dt.timedelta], x: timedelta64[_AnyTD64Item], / + ) -> tuple[int64, timedelta64[_AnyTD64Item | None]]: ... + @overload + def __divmod__(self: timedelta64[dt.timedelta], x: dt.timedelta, /) -> tuple[int, dt.timedelta]: ... + @overload + def __divmod__(self, x: timedelta64[int], /) -> tuple[int64, timedelta64[int | None]]: ... + @overload + def __divmod__(self, x: timedelta64, /) -> tuple[int64, timedelta64]: ... + + # keep in sync with __rmod__ + @overload + def __rdivmod__(self, x: timedelta64[None], /) -> tuple[int64, timedelta64[None]]: ... # type: ignore[misc] + @overload + def __rdivmod__(self: timedelta64[L[0] | None], x: timedelta64, /) -> tuple[int64, timedelta64[None]]: ... # type: ignore[misc] + @overload + def __rdivmod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> tuple[int64, timedelta64[int | None]]: ... # type: ignore[misc] + @overload + def __rdivmod__( # type: ignore[misc] + self: timedelta64[dt.timedelta], x: timedelta64[_AnyTD64Item], / + ) -> tuple[int64, timedelta64[_AnyTD64Item | None]]: ... + @overload + def __rdivmod__(self: timedelta64[dt.timedelta], x: dt.timedelta, /) -> tuple[int, dt.timedelta]: ... + @overload + def __rdivmod__(self, x: timedelta64[int], /) -> tuple[int64, timedelta64[int | None]]: ... # type: ignore[misc] + @overload + def __rdivmod__(self, x: timedelta64, /) -> tuple[int64, timedelta64]: ... # type: ignore[misc] + + @overload + def __sub__(self: timedelta64[None], b: _TD64Like_co, /) -> timedelta64[None]: ... + @overload + def __sub__(self: timedelta64[int], b: timedelta64[int | dt.timedelta], /) -> timedelta64[int]: ... + @overload + def __sub__(self: timedelta64[int], b: timedelta64, /) -> timedelta64[int | None]: ... + @overload + def __sub__(self: timedelta64[dt.timedelta], b: dt.timedelta, /) -> dt.timedelta: ... + @overload + def __sub__(self: timedelta64[_AnyTD64Item], b: timedelta64[_AnyTD64Item] | _IntLike_co, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __sub__(self, b: timedelta64[None], /) -> timedelta64[None]: ... # type: ignore[overload-cannot-match] + + # NOTE: subtraction is not commutative, so __rsub__ differs from __sub__. + # This confuses mypy, so we ignore the [misc] errors it reports. + @overload + def __rsub__(self: timedelta64[None], a: _TD64Like_co, /) -> timedelta64[None]: ... + @overload + def __rsub__(self: timedelta64[dt.timedelta], a: _AnyDateOrTime, /) -> _AnyDateOrTime: ... + @overload + def __rsub__(self: timedelta64[dt.timedelta], a: timedelta64[_AnyTD64Item], /) -> timedelta64[_AnyTD64Item]: ... # type: ignore[misc] + @overload + def __rsub__(self: timedelta64[_AnyTD64Item], a: timedelta64[_AnyTD64Item] | _IntLike_co, /) -> timedelta64[_AnyTD64Item]: ... # type: ignore[misc] + @overload + def __rsub__(self, a: timedelta64[None], /) -> timedelta64[None]: ... # type: ignore[overload-cannot-match] + @overload + def __rsub__(self, a: datetime64[None], /) -> datetime64[None]: ... # type: ignore[misc] + + @overload + def __truediv__(self: timedelta64[dt.timedelta], b: dt.timedelta, /) -> float: ... + @overload + def __truediv__(self, b: timedelta64, /) -> float64: ... + @overload + def __truediv__(self: timedelta64[_AnyTD64Item], b: int | integer, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __truediv__(self: timedelta64[_AnyTD64Item], b: float | floating, /) -> timedelta64[_AnyTD64Item | None]: ... + @overload + def __truediv__(self, b: float | floating | integer, /) -> timedelta64: ... + + @overload + def __rtruediv__(self: timedelta64[dt.timedelta], a: dt.timedelta, /) -> float: ... + @overload + def __rtruediv__(self, a: timedelta64, /) -> float64: ... + + @overload + def __floordiv__(self: timedelta64[dt.timedelta], b: dt.timedelta, /) -> int: ... + @overload + def __floordiv__(self, b: timedelta64, /) -> int64: ... + @overload + def __floordiv__(self: timedelta64[_AnyTD64Item], b: int | integer, /) -> timedelta64[_AnyTD64Item]: ... + @overload + def __floordiv__(self: timedelta64[_AnyTD64Item], b: float | floating, /) -> timedelta64[_AnyTD64Item | None]: ... + + @overload + def __rfloordiv__(self: timedelta64[dt.timedelta], a: dt.timedelta, /) -> int: ... + @overload + def __rfloordiv__(self, a: timedelta64, /) -> int64: ... + + # comparison ops + + @overload + def __lt__(self, other: _TD64Like_co, /) -> bool_: ... + @overload + def __lt__(self, other: _ArrayLikeTD64_co | _NestedSequence[_SupportsGT], /) -> NDArray[bool_]: ... + @overload + def __lt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __le__(self, other: _TD64Like_co, /) -> bool_: ... + @overload + def __le__(self, other: _ArrayLikeTD64_co | _NestedSequence[_SupportsGE], /) -> NDArray[bool_]: ... + @overload + def __le__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __gt__(self, other: _TD64Like_co, /) -> bool_: ... + @overload + def __gt__(self, other: _ArrayLikeTD64_co | _NestedSequence[_SupportsLT], /) -> NDArray[bool_]: ... + @overload + def __gt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __ge__(self, other: _TD64Like_co, /) -> bool_: ... + @overload + def __ge__(self, other: _ArrayLikeTD64_co | _NestedSequence[_SupportsLE], /) -> NDArray[bool_]: ... + @overload + def __ge__(self, other: _SupportsGT, /) -> bool_: ... + +class datetime64(_RealMixin, generic[_DT64ItemT_co], Generic[_DT64ItemT_co]): + @property + def itemsize(self) -> L[8]: ... + @property + def nbytes(self) -> L[8]: ... + + @overload + def __new__(cls, value: datetime64[_DT64ItemT_co], /) -> Self: ... + @overload + def __new__(cls, value: _AnyDT64Arg, /) -> datetime64[_AnyDT64Arg]: ... + @overload + def __new__(cls, value: _NaTValue | None = ..., format: _TimeUnitSpec = ..., /) -> datetime64[None]: ... + @overload + def __new__(cls, value: _DT64Now, format: _TimeUnitSpec[_NativeTimeUnit] = ..., /) -> datetime64[dt.datetime]: ... + @overload + def __new__(cls, value: _DT64Date, format: _TimeUnitSpec[_DateUnit] = ..., /) -> datetime64[dt.date]: ... + @overload + def __new__(cls, value: int | bytes | str | dt.date, format: _TimeUnitSpec[_IntTimeUnit], /) -> datetime64[int]: ... + @overload + def __new__( + cls, value: int | bytes | str | dt.date, format: _TimeUnitSpec[_NativeTimeUnit], / + ) -> datetime64[dt.datetime]: ... + @overload + def __new__(cls, value: int | bytes | str | dt.date, format: _TimeUnitSpec[_DateUnit], /) -> datetime64[dt.date]: ... + @overload + def __new__(cls, value: bytes | str | dt.date | None, format: _TimeUnitSpec = ..., /) -> Self: ... + + def __class_getitem__(cls, type_arg: type | object, /) -> GenericAlias: ... + + @overload + def __add__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ... + @overload + def __add__(self: datetime64[None], x: _TD64Like_co, /) -> datetime64[None]: ... + @overload + def __add__(self: datetime64[int], x: timedelta64[int | dt.timedelta], /) -> datetime64[int]: ... + @overload + def __add__(self: datetime64[dt.datetime], x: timedelta64[dt.timedelta], /) -> datetime64[dt.datetime]: ... + @overload + def __add__(self: datetime64[dt.date], x: timedelta64[dt.timedelta], /) -> datetime64[dt.date]: ... + @overload + def __add__(self: datetime64[dt.date], x: timedelta64[int], /) -> datetime64[int]: ... + @overload + def __add__(self, x: datetime64[None], /) -> datetime64[None]: ... + @overload + def __add__(self, x: _TD64Like_co, /) -> datetime64: ... + __radd__ = __add__ + + @overload + def __sub__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ... + @overload + def __sub__(self: datetime64[_AnyDate], x: _AnyDate, /) -> dt.timedelta: ... + @overload + def __sub__(self: datetime64[None], x: timedelta64, /) -> datetime64[None]: ... + @overload + def __sub__(self: datetime64[None], x: datetime64, /) -> timedelta64[None]: ... + @overload + def __sub__(self: datetime64[int], x: timedelta64, /) -> datetime64[int]: ... + @overload + def __sub__(self: datetime64[int], x: datetime64, /) -> timedelta64[int]: ... + @overload + def __sub__(self: datetime64[dt.datetime], x: timedelta64[int], /) -> datetime64[int]: ... + @overload + def __sub__(self: datetime64[dt.datetime], x: timedelta64[dt.timedelta], /) -> datetime64[dt.datetime]: ... + @overload + def __sub__(self: datetime64[dt.datetime], x: datetime64[int], /) -> timedelta64[int]: ... + @overload + def __sub__(self: datetime64[dt.date], x: timedelta64[int], /) -> datetime64[dt.date | int]: ... + @overload + def __sub__(self: datetime64[dt.date], x: timedelta64[dt.timedelta], /) -> datetime64[dt.date]: ... + @overload + def __sub__(self: datetime64[dt.date], x: datetime64[dt.date], /) -> timedelta64[dt.timedelta]: ... + @overload + def __sub__(self, x: timedelta64[None], /) -> datetime64[None]: ... + @overload + def __sub__(self, x: datetime64[None], /) -> timedelta64[None]: ... + @overload + def __sub__(self, x: _TD64Like_co, /) -> datetime64: ... + @overload + def __sub__(self, x: datetime64, /) -> timedelta64: ... + + # NOTE: mypy gets confused by the non-commutativity of subtraction here + @overload + def __rsub__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ... + @overload + def __rsub__(self: datetime64[_AnyDate], x: _AnyDate, /) -> dt.timedelta: ... + @overload + def __rsub__(self: datetime64[None], x: datetime64, /) -> timedelta64[None]: ... + @overload + def __rsub__(self: datetime64[int], x: datetime64, /) -> timedelta64[int]: ... + @overload + def __rsub__(self: datetime64[dt.datetime], x: datetime64[int], /) -> timedelta64[int]: ... # type: ignore[misc] + @overload + def __rsub__(self: datetime64[dt.datetime], x: datetime64[dt.date], /) -> timedelta64[dt.timedelta]: ... # type: ignore[misc] + @overload + def __rsub__(self, x: datetime64[None], /) -> timedelta64[None]: ... # type: ignore[misc] + @overload + def __rsub__(self, x: datetime64, /) -> timedelta64: ... # type: ignore[misc] + + @overload + def __lt__(self, other: datetime64, /) -> bool_: ... + @overload + def __lt__(self, other: _ArrayLikeDT64_co | _NestedSequence[_SupportsGT], /) -> NDArray[bool_]: ... + @overload + def __lt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __le__(self, other: datetime64, /) -> bool_: ... + @overload + def __le__(self, other: _ArrayLikeDT64_co | _NestedSequence[_SupportsGE], /) -> NDArray[bool_]: ... + @overload + def __le__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __gt__(self, other: datetime64, /) -> bool_: ... + @overload + def __gt__(self, other: _ArrayLikeDT64_co | _NestedSequence[_SupportsLT], /) -> NDArray[bool_]: ... + @overload + def __gt__(self, other: _SupportsGT, /) -> bool_: ... + + @overload + def __ge__(self, other: datetime64, /) -> bool_: ... + @overload + def __ge__(self, other: _ArrayLikeDT64_co | _NestedSequence[_SupportsLE], /) -> NDArray[bool_]: ... + @overload + def __ge__(self, other: _SupportsGT, /) -> bool_: ... + +@final # cannot be subclassed at runtime +class flexible(_RealMixin, generic[_FlexibleItemT_co], Generic[_FlexibleItemT_co]): ... # type: ignore[misc] + +class void(flexible[bytes | tuple[Any, ...]]): # type: ignore[misc] + @overload + def __new__(cls, length_or_data: _IntLike_co | bytes, /, dtype: None = None) -> Self: ... + @overload + def __new__(cls, length_or_data: object, /, dtype: _DTypeLikeVoid) -> Self: ... + + @overload + def __getitem__(self, key: str | SupportsIndex, /) -> Any: ... + @overload + def __getitem__(self, key: list[str], /) -> void: ... + def __setitem__(self, key: str | list[str] | SupportsIndex, value: ArrayLike, /) -> None: ... + + def setfield(self, val: ArrayLike, dtype: DTypeLike, offset: int = ...) -> None: ... + +class character(flexible[_CharacterItemT_co], Generic[_CharacterItemT_co]): # type: ignore[misc] + @abstractmethod + def __new__(cls, value: object = ..., /) -> Self: ... + +# NOTE: Most `np.bytes_` / `np.str_` methods return their builtin `bytes` / `str` counterpart + +class bytes_(character[bytes], bytes): # type: ignore[misc] + @overload + def __new__(cls, value: object = b"", /) -> Self: ... + @overload + def __new__(cls, value: str, /, encoding: str, errors: str = "strict") -> Self: ... + + # + @override + def __hash__(self, /) -> int: ... + + # + def __bytes__(self, /) -> bytes: ... + +class str_(character[str], str): # type: ignore[misc] + @overload + def __new__(cls, value: object = "", /) -> Self: ... + @overload + def __new__(cls, value: bytes, /, encoding: str, errors: str = "strict") -> Self: ... + + # + @override + def __hash__(self, /) -> int: ... + +# See `numpy._typing._ufunc` for more concrete nin-/nout-specific stubs +@final +class ufunc: + __signature__: Final[inspect.Signature] + + @property + def __name__(self) -> LiteralString: ... + @property + def __qualname__(self) -> LiteralString: ... # pyright: ignore[reportIncompatibleVariableOverride] + @property + def __doc__(self) -> str: ... # type: ignore[override] + @property + def nin(self) -> int: ... + @property + def nout(self) -> int: ... + @property + def nargs(self) -> int: ... + @property + def ntypes(self) -> int: ... + @property + def types(self) -> list[LiteralString]: ... + # Broad return type because it has to encompass things like + # + # >>> np.logical_and.identity is True + # True + # >>> np.add.identity is 0 + # True + # >>> np.sin.identity is None + # True + # + # and any user-defined ufuncs. + @property + def identity(self) -> Any: ... + # This is None for ufuncs and a string for gufuncs. + @property + def signature(self) -> LiteralString | None: ... + + def __call__(self, /, *args: Any, **kwargs: Any) -> Any: ... + + # The next four methods will always exist, but they will just + # raise a ValueError ufuncs with that don't accept two input + # arguments and return one output argument. Because of that we + # can't type them very precisely. + def accumulate( + self, + array: ArrayLike, + /, + axis: SupportsIndex = 0, + dtype: DTypeLike | None = None, + out: ndarray | EllipsisType | None = None, + ) -> NDArray[Incomplete]: ... + def reduce( + self, + array: ArrayLike, + /, + axis: _ShapeLike | None = 0, + dtype: DTypeLike | None = None, + out: ndarray | EllipsisType | None = None, + **kwargs: Incomplete, + ) -> Incomplete: ... + def reduceat( + self, + array: ArrayLike, + /, + indices: _ArrayLikeInt_co, + axis: SupportsIndex = 0, + dtype: DTypeLike | None = None, + out: ndarray | EllipsisType | None = None, + ) -> NDArray[Incomplete]: ... + def outer(self, A: ArrayLike, B: ArrayLike, /, **kwargs: Incomplete) -> NDArray[Incomplete]: ... + + # Similarly `at` won't be defined for ufuncs that return multiple + # outputs, so we can't type it very precisely. + def at(self, a: ndarray, indices: _ArrayLikeInt_co, b: ArrayLike | None = None, /) -> None: ... + + # + def resolve_dtypes( + self, + /, + dtypes: tuple[dtype | type | None, ...], + *, + signature: tuple[dtype | None, ...] | None = None, + casting: _CastingKind | None = None, + reduction: builtins.bool = False, + ) -> tuple[dtype, ...]: ... + +# Parameters: `__name__`, `ntypes` and `identity` +absolute: _UFunc_Nin1_Nout1[L["absolute"], L[20], None] +add: _UFunc_Nin2_Nout1[L["add"], L[22], L[0]] +arccos: _UFunc_Nin1_Nout1[L["arccos"], L[8], None] +arccosh: _UFunc_Nin1_Nout1[L["arccosh"], L[8], None] +arcsin: _UFunc_Nin1_Nout1[L["arcsin"], L[8], None] +arcsinh: _UFunc_Nin1_Nout1[L["arcsinh"], L[8], None] +arctan2: _UFunc_Nin2_Nout1[L["arctan2"], L[5], None] +arctan: _UFunc_Nin1_Nout1[L["arctan"], L[8], None] +arctanh: _UFunc_Nin1_Nout1[L["arctanh"], L[8], None] +bitwise_and: _UFunc_Nin2_Nout1[L["bitwise_and"], L[12], L[-1]] +bitwise_count: _UFunc_Nin1_Nout1[L["bitwise_count"], L[11], None] +bitwise_or: _UFunc_Nin2_Nout1[L["bitwise_or"], L[12], L[0]] +bitwise_xor: _UFunc_Nin2_Nout1[L["bitwise_xor"], L[12], L[0]] +cbrt: _UFunc_Nin1_Nout1[L["cbrt"], L[5], None] +ceil: _UFunc_Nin1_Nout1[L["ceil"], L[7], None] +conjugate: _UFunc_Nin1_Nout1[L["conjugate"], L[18], None] +copysign: _UFunc_Nin2_Nout1[L["copysign"], L[4], None] +cos: _UFunc_Nin1_Nout1[L["cos"], L[9], None] +cosh: _UFunc_Nin1_Nout1[L["cosh"], L[8], None] +deg2rad: _UFunc_Nin1_Nout1[L["deg2rad"], L[5], None] +degrees: _UFunc_Nin1_Nout1[L["degrees"], L[5], None] +divide: _UFunc_Nin2_Nout1[L["divide"], L[11], None] +divmod: _UFunc_Nin2_Nout2[L["divmod"], L[15], None] +equal: _UFunc_Nin2_Nout1[L["equal"], L[23], None] +exp2: _UFunc_Nin1_Nout1[L["exp2"], L[8], None] +exp: _UFunc_Nin1_Nout1[L["exp"], L[10], None] +expm1: _UFunc_Nin1_Nout1[L["expm1"], L[8], None] +fabs: _UFunc_Nin1_Nout1[L["fabs"], L[5], None] +float_power: _UFunc_Nin2_Nout1[L["float_power"], L[4], None] +floor: _UFunc_Nin1_Nout1[L["floor"], L[7], None] +floor_divide: _UFunc_Nin2_Nout1[L["floor_divide"], L[21], None] +fmax: _UFunc_Nin2_Nout1[L["fmax"], L[21], None] +fmin: _UFunc_Nin2_Nout1[L["fmin"], L[21], None] +fmod: _UFunc_Nin2_Nout1[L["fmod"], L[15], None] +frexp: _UFunc_Nin1_Nout2[L["frexp"], L[4], None] +gcd: _UFunc_Nin2_Nout1[L["gcd"], L[11], L[0]] +greater: _UFunc_Nin2_Nout1[L["greater"], L[23], None] +greater_equal: _UFunc_Nin2_Nout1[L["greater_equal"], L[23], None] +heaviside: _UFunc_Nin2_Nout1[L["heaviside"], L[4], None] +hypot: _UFunc_Nin2_Nout1[L["hypot"], L[5], L[0]] +invert: _UFunc_Nin1_Nout1[L["invert"], L[12], None] +isfinite: _UFunc_Nin1_Nout1[L["isfinite"], L[20], None] +isinf: _UFunc_Nin1_Nout1[L["isinf"], L[20], None] +isnan: _UFunc_Nin1_Nout1[L["isnan"], L[20], None] +isnat: _UFunc_Nin1_Nout1[L["isnat"], L[2], None] +lcm: _UFunc_Nin2_Nout1[L["lcm"], L[11], None] +ldexp: _UFunc_Nin2_Nout1[L["ldexp"], L[8], None] +left_shift: _UFunc_Nin2_Nout1[L["left_shift"], L[11], None] +less: _UFunc_Nin2_Nout1[L["less"], L[23], None] +less_equal: _UFunc_Nin2_Nout1[L["less_equal"], L[23], None] +log10: _UFunc_Nin1_Nout1[L["log10"], L[8], None] +log1p: _UFunc_Nin1_Nout1[L["log1p"], L[8], None] +log2: _UFunc_Nin1_Nout1[L["log2"], L[8], None] +log: _UFunc_Nin1_Nout1[L["log"], L[10], None] +logaddexp2: _UFunc_Nin2_Nout1[L["logaddexp2"], L[4], float] +logaddexp: _UFunc_Nin2_Nout1[L["logaddexp"], L[4], float] +logical_and: _UFunc_Nin2_Nout1[L["logical_and"], L[20], L[True]] +logical_not: _UFunc_Nin1_Nout1[L["logical_not"], L[20], None] +logical_or: _UFunc_Nin2_Nout1[L["logical_or"], L[20], L[False]] +logical_xor: _UFunc_Nin2_Nout1[L["logical_xor"], L[19], L[False]] +matmul: _GUFunc_Nin2_Nout1[L["matmul"], L[19], None, L["(n?,k),(k,m?)->(n?,m?)"]] +matvec: _GUFunc_Nin2_Nout1[L["matvec"], L[19], None, L["(m,n),(n)->(m)"]] +maximum: _UFunc_Nin2_Nout1[L["maximum"], L[21], None] +minimum: _UFunc_Nin2_Nout1[L["minimum"], L[21], None] +modf: _UFunc_Nin1_Nout2[L["modf"], L[4], None] +multiply: _UFunc_Nin2_Nout1[L["multiply"], L[23], L[1]] +negative: _UFunc_Nin1_Nout1[L["negative"], L[19], None] +nextafter: _UFunc_Nin2_Nout1[L["nextafter"], L[4], None] +not_equal: _UFunc_Nin2_Nout1[L["not_equal"], L[23], None] +positive: _UFunc_Nin1_Nout1[L["positive"], L[19], None] +power: _UFunc_Nin2_Nout1[L["power"], L[18], None] +rad2deg: _UFunc_Nin1_Nout1[L["rad2deg"], L[5], None] +radians: _UFunc_Nin1_Nout1[L["radians"], L[5], None] +reciprocal: _UFunc_Nin1_Nout1[L["reciprocal"], L[18], None] +remainder: _UFunc_Nin2_Nout1[L["remainder"], L[16], None] +right_shift: _UFunc_Nin2_Nout1[L["right_shift"], L[11], None] +rint: _UFunc_Nin1_Nout1[L["rint"], L[10], None] +sign: _UFunc_Nin1_Nout1[L["sign"], L[19], None] +signbit: _UFunc_Nin1_Nout1[L["signbit"], L[4], None] +sin: _UFunc_Nin1_Nout1[L["sin"], L[9], None] +sinh: _UFunc_Nin1_Nout1[L["sinh"], L[8], None] +spacing: _UFunc_Nin1_Nout1[L["spacing"], L[4], None] +sqrt: _UFunc_Nin1_Nout1[L["sqrt"], L[10], None] +square: _UFunc_Nin1_Nout1[L["square"], L[18], None] +subtract: _UFunc_Nin2_Nout1[L["subtract"], L[21], None] +tan: _UFunc_Nin1_Nout1[L["tan"], L[8], None] +tanh: _UFunc_Nin1_Nout1[L["tanh"], L[8], None] +trunc: _UFunc_Nin1_Nout1[L["trunc"], L[7], None] +vecdot: _GUFunc_Nin2_Nout1[L["vecdot"], L[19], None, L["(n),(n)->()"]] +vecmat: _GUFunc_Nin2_Nout1[L["vecmat"], L[19], None, L["(n),(n,m)->(m)"]] + +abs = absolute +acos = arccos +acosh = arccosh +asin = arcsin +asinh = arcsinh +atan = arctan +atanh = arctanh +atan2 = arctan2 +concat = concatenate +bitwise_left_shift = left_shift +bitwise_not = invert +bitwise_invert = invert +bitwise_right_shift = right_shift +conj = conjugate +mod = remainder +permute_dims = transpose +pow = power +true_divide = divide + +# TODO: The type of each `__next__` and `iters` return-type depends +# on the length and dtype of `args`; we can't describe this behavior yet +# as we lack variadics (PEP 646). +@final +class broadcast: + def __new__(cls, *args: ArrayLike) -> broadcast: ... + @property + def index(self) -> int: ... + @property + def iters(self) -> tuple[flatiter[Any], ...]: ... + @property + def nd(self) -> int: ... + @property + def ndim(self) -> int: ... + @property + def numiter(self) -> int: ... + @property + def shape(self) -> _AnyShape: ... + @property + def size(self) -> int: ... + def __next__(self) -> tuple[Any, ...]: ... + def __iter__(self) -> Self: ... + def reset(self) -> None: ... + +@final +class busdaycalendar: + def __init__( + self, + /, + weekmask: str | Sequence[int | bool_ | integer] | _SupportsArray[dtype[bool_ | integer]] = "1111100", + holidays: Sequence[dt.date | datetime64] | _SupportsArray[dtype[datetime64]] | None = None, + ) -> None: ... + @property + def weekmask(self) -> ndarray[tuple[int], dtype[bool_]]: ... + @property + def holidays(self) -> ndarray[tuple[int], dtype[datetime64[dt.date]]]: ... + +@final +class nditer: + @overload + def __init__( + self, + /, + op: ArrayLike, + flags: Sequence[_NDIterFlagsKind] | None = None, + op_flags: Sequence[_NDIterFlagsOp] | None = None, + op_dtypes: DTypeLike | None = None, + order: _OrderKACF = "K", + casting: _CastingKind = "safe", + op_axes: Sequence[SupportsIndex] | None = None, + itershape: _ShapeLike | None = None, + buffersize: SupportsIndex = 0, + ) -> None: ... + @overload + def __init__( + self, + /, + op: Sequence[ArrayLike | None], + flags: Sequence[_NDIterFlagsKind] | None = None, + op_flags: Sequence[Sequence[_NDIterFlagsOp]] | None = None, + op_dtypes: Sequence[DTypeLike | None] | None = None, + order: _OrderKACF = "K", + casting: _CastingKind = "safe", + op_axes: Sequence[Sequence[SupportsIndex]] | None = None, + itershape: _ShapeLike | None = None, + buffersize: SupportsIndex = 0, + ) -> None: ... + + def __enter__(self) -> nditer: ... + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: ... + def __iter__(self) -> nditer: ... + def __next__(self) -> tuple[NDArray[Any], ...]: ... + def __len__(self) -> int: ... + def __copy__(self) -> nditer: ... + @overload + def __getitem__(self, index: SupportsIndex) -> NDArray[Any]: ... + @overload + def __getitem__(self, index: slice) -> tuple[NDArray[Any], ...]: ... + def __setitem__(self, index: slice | SupportsIndex, value: ArrayLike) -> None: ... + def close(self) -> None: ... + def copy(self) -> nditer: ... + def debug_print(self) -> None: ... + def enable_external_loop(self) -> None: ... + def iternext(self) -> builtins.bool: ... + def remove_axis(self, i: SupportsIndex, /) -> None: ... + def remove_multi_index(self) -> None: ... + def reset(self) -> None: ... + @property + def dtypes(self) -> tuple[dtype, ...]: ... + @property + def finished(self) -> builtins.bool: ... + @property + def has_delayed_bufalloc(self) -> builtins.bool: ... + @property + def has_index(self) -> builtins.bool: ... + @property + def has_multi_index(self) -> builtins.bool: ... + @property + def index(self) -> int: ... + @property + def iterationneedsapi(self) -> builtins.bool: ... + @property + def iterindex(self) -> int: ... + @property + def iterrange(self) -> tuple[int, ...]: ... + @property + def itersize(self) -> int: ... + @property + def itviews(self) -> tuple[NDArray[Any], ...]: ... + @property + def multi_index(self) -> tuple[int, ...]: ... + @property + def ndim(self) -> int: ... + @property + def nop(self) -> int: ... + @property + def operands(self) -> tuple[NDArray[Any], ...]: ... + @property + def shape(self) -> tuple[int, ...]: ... + @property + def value(self) -> tuple[NDArray[Any], ...]: ... + +class memmap(ndarray[_ShapeT_co, _DTypeT_co]): + __array_priority__: ClassVar[float] + filename: str | None + offset: int + mode: str + @overload + def __new__( + subtype, + filename: StrOrBytesPath | _SupportsFileMethodsRW, + dtype: type[uint8] = ..., + mode: _MemMapModeKind = "r+", + offset: int = 0, + shape: int | tuple[int, ...] | None = None, + order: _OrderKACF = "C", + ) -> memmap[Any, dtype[uint8]]: ... + @overload + def __new__( + subtype, + filename: StrOrBytesPath | _SupportsFileMethodsRW, + dtype: _DTypeLike[_ScalarT], + mode: _MemMapModeKind = "r+", + offset: int = 0, + shape: int | tuple[int, ...] | None = None, + order: _OrderKACF = "C", + ) -> memmap[Any, dtype[_ScalarT]]: ... + @overload + def __new__( + subtype, + filename: StrOrBytesPath | _SupportsFileMethodsRW, + dtype: DTypeLike, + mode: _MemMapModeKind = "r+", + offset: int = 0, + shape: int | tuple[int, ...] | None = None, + order: _OrderKACF = "C", + ) -> memmap[Any, dtype]: ... + def __array_finalize__(self, obj: object) -> None: ... + def __array_wrap__( + self, + array: memmap[_ShapeT_co, _DTypeT_co], # type: ignore[override] + context: tuple[ufunc, tuple[Any, ...], int] | None = None, + return_scalar: builtins.bool = False, + ) -> Any: ... + def flush(self) -> None: ... + +class poly1d: + @property + def variable(self) -> LiteralString: ... + @property + def order(self) -> int: ... + @property + def o(self) -> int: ... + @property + def roots(self) -> NDArray[Any]: ... + @property + def r(self) -> NDArray[Any]: ... + + @property + def coeffs(self) -> NDArray[Any]: ... + @coeffs.setter + def coeffs(self, value: NDArray[Any]) -> None: ... + + @property + def c(self) -> NDArray[Any]: ... + @c.setter + def c(self, value: NDArray[Any]) -> None: ... + + @property + def coef(self) -> NDArray[Any]: ... + @coef.setter + def coef(self, value: NDArray[Any]) -> None: ... + + @property + def coefficients(self) -> NDArray[Any]: ... + @coefficients.setter + def coefficients(self, value: NDArray[Any]) -> None: ... + + __hash__: ClassVar[None] # type: ignore[assignment] # pyright: ignore[reportIncompatibleMethodOverride] + + @overload + def __array__(self, /, t: None = None, copy: builtins.bool | None = None) -> ndarray[tuple[int], dtype]: ... + @overload + def __array__(self, /, t: _DTypeT, copy: builtins.bool | None = None) -> ndarray[tuple[int], _DTypeT]: ... + + @overload + def __call__(self, val: _ScalarLike_co) -> Any: ... + @overload + def __call__(self, val: poly1d) -> poly1d: ... + @overload + def __call__(self, val: ArrayLike) -> NDArray[Any]: ... + + def __init__( + self, + c_or_r: ArrayLike, + r: builtins.bool = False, + variable: str | None = None, + ) -> None: ... + def __len__(self) -> int: ... + def __neg__(self) -> poly1d: ... + def __pos__(self) -> poly1d: ... + def __mul__(self, other: ArrayLike, /) -> poly1d: ... + def __rmul__(self, other: ArrayLike, /) -> poly1d: ... + def __add__(self, other: ArrayLike, /) -> poly1d: ... + def __radd__(self, other: ArrayLike, /) -> poly1d: ... + def __pow__(self, val: _FloatLike_co, /) -> poly1d: ... # Integral floats are accepted + def __sub__(self, other: ArrayLike, /) -> poly1d: ... + def __rsub__(self, other: ArrayLike, /) -> poly1d: ... + def __truediv__(self, other: ArrayLike, /) -> poly1d: ... + def __rtruediv__(self, other: ArrayLike, /) -> poly1d: ... + def __getitem__(self, val: int, /) -> Any: ... + def __setitem__(self, key: int, val: Any, /) -> None: ... + def __iter__(self) -> Iterator[Any]: ... + def deriv(self, m: SupportsInt | SupportsIndex = 1) -> poly1d: ... + def integ( + self, + m: SupportsInt | SupportsIndex = 1, + k: _ArrayLikeComplex_co | _ArrayLikeObject_co | None = 0, + ) -> poly1d: ... + +def from_dlpack( + x: _SupportsDLPack[None], + /, + *, + device: L["cpu"] | None = None, + copy: builtins.bool | None = None, +) -> NDArray[number | np.bool]: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_array_api_info.py b/data/miniconda3/lib/python3.13/site-packages/numpy/_array_api_info.py new file mode 100644 index 0000000000000000000000000000000000000000..41adb835433db946472db6d2814ebe1e45af2cc7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_array_api_info.py @@ -0,0 +1,346 @@ +""" +Array API Inspection namespace + +This is the namespace for inspection functions as defined by the array API +standard. See +https://data-apis.org/array-api/latest/API_specification/inspection.html for +more details. + +""" +from numpy._core import ( + bool, + complex64, + complex128, + dtype, + float32, + float64, + int8, + int16, + int32, + int64, + intp, + uint8, + uint16, + uint32, + uint64, +) +from numpy._utils import set_module + + +@set_module('numpy') +class __array_namespace_info__: + """ + Get the array API inspection namespace for NumPy. + + The array API inspection namespace defines the following functions: + + - capabilities() + - default_device() + - default_dtypes() + - dtypes() + - devices() + + See + https://data-apis.org/array-api/latest/API_specification/inspection.html + for more details. + + Returns + ------- + info : ModuleType + The array API inspection namespace for NumPy. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': numpy.float64, + 'complex floating': numpy.complex128, + 'integral': numpy.int64, + 'indexing': numpy.int64} + + """ + + def capabilities(self): + """ + Return a dictionary of array API library capabilities. + + The resulting dictionary has the following keys: + + - **"boolean indexing"**: boolean indicating whether an array library + supports boolean indexing. Always ``True`` for NumPy. + + - **"data-dependent shapes"**: boolean indicating whether an array + library supports data-dependent output shapes. Always ``True`` for + NumPy. + + See + https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html + for more details. + + See Also + -------- + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + capabilities : dict + A dictionary of array API library capabilities. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.capabilities() + {'boolean indexing': True, + 'data-dependent shapes': True, + 'max dimensions': 64} + + """ + return { + "boolean indexing": True, + "data-dependent shapes": True, + "max dimensions": 64, + } + + def default_device(self): + """ + The default device used for new NumPy arrays. + + For NumPy, this always returns ``'cpu'``. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Returns + ------- + device : str + The default device used for new NumPy arrays. + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_device() + 'cpu' + + """ + return "cpu" + + def default_dtypes(self, *, device=None): + """ + The default data types used for new NumPy arrays. + + For NumPy, this always returns the following dictionary: + + - **"real floating"**: ``numpy.float64`` + - **"complex floating"**: ``numpy.complex128`` + - **"integral"**: ``numpy.intp`` + - **"indexing"**: ``numpy.intp`` + + Parameters + ---------- + device : str, optional + The device to get the default data types for. For NumPy, only + ``'cpu'`` is allowed. + + Returns + ------- + dtypes : dict + A dictionary describing the default data types used for new NumPy + arrays. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.default_dtypes() + {'real floating': numpy.float64, + 'complex floating': numpy.complex128, + 'integral': numpy.int64, + 'indexing': numpy.int64} + + """ + if device not in ["cpu", None]: + raise ValueError( + 'Device not understood. Only "cpu" is allowed, but received:' + f' {device}' + ) + return { + "real floating": dtype(float64), + "complex floating": dtype(complex128), + "integral": dtype(intp), + "indexing": dtype(intp), + } + + def dtypes(self, *, device=None, kind=None): + """ + The array API data types supported by NumPy. + + Note that this function only returns data types that are defined by + the array API. + + Parameters + ---------- + device : str, optional + The device to get the data types for. For NumPy, only ``'cpu'`` is + allowed. + kind : str or tuple of str, optional + The kind of data types to return. If ``None``, all data types are + returned. If a string, only data types of that kind are returned. + If a tuple, a dictionary containing the union of the given kinds + is returned. The following kinds are supported: + + - ``'bool'``: boolean data types (i.e., ``bool``). + - ``'signed integer'``: signed integer data types (i.e., ``int8``, + ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (i.e., + ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed + integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types + (i.e., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (i.e., + ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', + 'real floating', 'complex floating')``. + + Returns + ------- + dtypes : dict + A dictionary mapping the names of data types to the corresponding + NumPy data types. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.devices + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.dtypes(kind='signed integer') + {'int8': numpy.int8, + 'int16': numpy.int16, + 'int32': numpy.int32, + 'int64': numpy.int64} + + """ + if device not in ["cpu", None]: + raise ValueError( + 'Device not understood. Only "cpu" is allowed, but received:' + f' {device}' + ) + if kind is None: + return { + "bool": dtype(bool), + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "bool": + return {"bool": bool} + if kind == "signed integer": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + } + if kind == "unsigned integer": + return { + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "integral": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + } + if kind == "real floating": + return { + "float32": dtype(float32), + "float64": dtype(float64), + } + if kind == "complex floating": + return { + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if kind == "numeric": + return { + "int8": dtype(int8), + "int16": dtype(int16), + "int32": dtype(int32), + "int64": dtype(int64), + "uint8": dtype(uint8), + "uint16": dtype(uint16), + "uint32": dtype(uint32), + "uint64": dtype(uint64), + "float32": dtype(float32), + "float64": dtype(float64), + "complex64": dtype(complex64), + "complex128": dtype(complex128), + } + if isinstance(kind, tuple): + res = {} + for k in kind: + res.update(self.dtypes(kind=k)) + return res + raise ValueError(f"unsupported kind: {kind!r}") + + def devices(self): + """ + The devices supported by NumPy. + + For NumPy, this always returns ``['cpu']``. + + Returns + ------- + devices : list of str + The devices supported by NumPy. + + See Also + -------- + __array_namespace_info__.capabilities, + __array_namespace_info__.default_device, + __array_namespace_info__.default_dtypes, + __array_namespace_info__.dtypes + + Examples + -------- + >>> info = np.__array_namespace_info__() + >>> info.devices() + ['cpu'] + + """ + return ["cpu"] diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_array_api_info.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/_array_api_info.pyi new file mode 100644 index 0000000000000000000000000000000000000000..396125143e922a0d4c7a6c84b5ab61b6cf7b5319 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_array_api_info.pyi @@ -0,0 +1,206 @@ +from typing import ( + Literal, + Never, + TypeAlias, + TypedDict, + TypeVar, + final, + overload, + type_check_only, +) + +import numpy as np + +_Device: TypeAlias = Literal["cpu"] +_DeviceLike: TypeAlias = _Device | None + +_Capabilities = TypedDict( + "_Capabilities", + { + "boolean indexing": Literal[True], + "data-dependent shapes": Literal[True], + }, +) + +_DefaultDTypes = TypedDict( + "_DefaultDTypes", + { + "real floating": np.dtype[np.float64], + "complex floating": np.dtype[np.complex128], + "integral": np.dtype[np.intp], + "indexing": np.dtype[np.intp], + }, +) + +_KindBool: TypeAlias = Literal["bool"] +_KindInt: TypeAlias = Literal["signed integer"] +_KindUInt: TypeAlias = Literal["unsigned integer"] +_KindInteger: TypeAlias = Literal["integral"] +_KindFloat: TypeAlias = Literal["real floating"] +_KindComplex: TypeAlias = Literal["complex floating"] +_KindNumber: TypeAlias = Literal["numeric"] +_Kind: TypeAlias = ( + _KindBool + | _KindInt + | _KindUInt + | _KindInteger + | _KindFloat + | _KindComplex + | _KindNumber +) + +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_Permute1: TypeAlias = _T1 | tuple[_T1] +_Permute2: TypeAlias = tuple[_T1, _T2] | tuple[_T2, _T1] +_Permute3: TypeAlias = ( + tuple[_T1, _T2, _T3] | tuple[_T1, _T3, _T2] + | tuple[_T2, _T1, _T3] | tuple[_T2, _T3, _T1] + | tuple[_T3, _T1, _T2] | tuple[_T3, _T2, _T1] +) + +@type_check_only +class _DTypesBool(TypedDict): + bool: np.dtype[np.bool] + +@type_check_only +class _DTypesInt(TypedDict): + int8: np.dtype[np.int8] + int16: np.dtype[np.int16] + int32: np.dtype[np.int32] + int64: np.dtype[np.int64] + +@type_check_only +class _DTypesUInt(TypedDict): + uint8: np.dtype[np.uint8] + uint16: np.dtype[np.uint16] + uint32: np.dtype[np.uint32] + uint64: np.dtype[np.uint64] + +@type_check_only +class _DTypesInteger(_DTypesInt, _DTypesUInt): ... + +@type_check_only +class _DTypesFloat(TypedDict): + float32: np.dtype[np.float32] + float64: np.dtype[np.float64] + +@type_check_only +class _DTypesComplex(TypedDict): + complex64: np.dtype[np.complex64] + complex128: np.dtype[np.complex128] + +@type_check_only +class _DTypesNumber(_DTypesInteger, _DTypesFloat, _DTypesComplex): ... + +@type_check_only +class _DTypes(_DTypesBool, _DTypesNumber): ... + +@type_check_only +class _DTypesUnion(TypedDict, total=False): + bool: np.dtype[np.bool] + int8: np.dtype[np.int8] + int16: np.dtype[np.int16] + int32: np.dtype[np.int32] + int64: np.dtype[np.int64] + uint8: np.dtype[np.uint8] + uint16: np.dtype[np.uint16] + uint32: np.dtype[np.uint32] + uint64: np.dtype[np.uint64] + float32: np.dtype[np.float32] + float64: np.dtype[np.float64] + complex64: np.dtype[np.complex64] + complex128: np.dtype[np.complex128] + +_EmptyDict: TypeAlias = dict[Never, Never] + +@final +class __array_namespace_info__: + __module__: Literal["numpy"] = "numpy" + + def capabilities(self) -> _Capabilities: ... + def default_device(self) -> _Device: ... + def default_dtypes( + self, + *, + device: _DeviceLike = None, + ) -> _DefaultDTypes: ... + def devices(self) -> list[_Device]: ... + + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: None = None, + ) -> _DTypes: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindBool], + ) -> _DTypesBool: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindInt], + ) -> _DTypesInt: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindUInt], + ) -> _DTypesUInt: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindFloat], + ) -> _DTypesFloat: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: _Permute1[_KindComplex], + ) -> _DTypesComplex: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: ( + _Permute1[_KindInteger] + | _Permute2[_KindInt, _KindUInt] + ), + ) -> _DTypesInteger: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: ( + _Permute1[_KindNumber] + | _Permute3[_KindInteger, _KindFloat, _KindComplex] + ), + ) -> _DTypesNumber: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: tuple[()], + ) -> _EmptyDict: ... + @overload + def dtypes( + self, + *, + device: _DeviceLike = None, + kind: tuple[_Kind, ...], + ) -> _DTypesUnion: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_configtool.py b/data/miniconda3/lib/python3.13/site-packages/numpy/_configtool.py new file mode 100644 index 0000000000000000000000000000000000000000..db7831c339518ba3a2a939eaa0006eded43ad129 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_configtool.py @@ -0,0 +1,39 @@ +import argparse +import sys +from pathlib import Path + +from .lib._utils_impl import get_include +from .version import __version__ + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--version", + action="version", + version=__version__, + help="Print the version and exit.", + ) + parser.add_argument( + "--cflags", + action="store_true", + help="Compile flag needed when using the NumPy headers.", + ) + parser.add_argument( + "--pkgconfigdir", + action="store_true", + help=("Print the pkgconfig directory in which `numpy.pc` is stored " + "(useful for setting $PKG_CONFIG_PATH)."), + ) + args = parser.parse_args() + if not sys.argv[1:]: + parser.print_help() + if args.cflags: + print("-I" + get_include()) + if args.pkgconfigdir: + _path = Path(get_include()) / '..' / 'lib' / 'pkgconfig' + print(_path.resolve()) + + +if __name__ == "__main__": + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_configtool.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/_configtool.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7e7363e797f3f5a33f66efd0349814c562e349e6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_configtool.pyi @@ -0,0 +1 @@ +def main() -> None: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_distributor_init.py b/data/miniconda3/lib/python3.13/site-packages/numpy/_distributor_init.py new file mode 100644 index 0000000000000000000000000000000000000000..f608036a2405528c0ddc4874b25b223dbe22c385 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_distributor_init.py @@ -0,0 +1,15 @@ +""" Distributor init file + +Distributors: you can add custom code here to support particular distributions +of numpy. + +For example, this is a good place to put any BLAS/LAPACK initialization code. + +The numpy standard source distribution will not put code in this file, so you +can safely replace this file with your own version. +""" + +try: + from . import _distributor_init_local # noqa: F401 +except ImportError: + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_distributor_init.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/_distributor_init.pyi new file mode 100644 index 0000000000000000000000000000000000000000..94456aba2bcfaf1166eeb81199dff4515c8b9474 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_distributor_init.pyi @@ -0,0 +1 @@ +# intentionally left blank diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_expired_attrs_2_0.py b/data/miniconda3/lib/python3.13/site-packages/numpy/_expired_attrs_2_0.py new file mode 100644 index 0000000000000000000000000000000000000000..2eebf95bc558c609bd665ab120746420a5ccb432 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_expired_attrs_2_0.py @@ -0,0 +1,78 @@ +""" +Dict of expired attributes that are discontinued since 2.0 release. +Each item is associated with a migration note. +""" + +__expired_attributes__ = { + "geterrobj": "Use the np.errstate context manager instead.", + "seterrobj": "Use the np.errstate context manager instead.", + "cast": "Use `np.asarray(arr, dtype=dtype)` instead.", + "source": "Use `inspect.getsource` instead.", + "lookfor": "Search NumPy's documentation directly.", + "who": "Use an IDE variable explorer or `locals()` instead.", + "fastCopyAndTranspose": "Use `arr.T.copy()` instead.", + "set_numeric_ops": + "For the general case, use `PyUFunc_ReplaceLoopBySignature`. " + "For ndarray subclasses, define the ``__array_ufunc__`` method " + "and override the relevant ufunc.", + "NINF": "Use `-np.inf` instead.", + "PINF": "Use `np.inf` instead.", + "NZERO": "Use `-0.0` instead.", + "PZERO": "Use `0.0` instead.", + "add_newdoc": + "It's still available as `np.lib.add_newdoc`.", + "add_docstring": + "It's still available as `np.lib.add_docstring`.", + "add_newdoc_ufunc": + "It's an internal function and doesn't have a replacement.", + "safe_eval": "Use `ast.literal_eval` instead.", + "float_": "Use `np.float64` instead.", + "complex_": "Use `np.complex128` instead.", + "longfloat": "Use `np.longdouble` instead.", + "singlecomplex": "Use `np.complex64` instead.", + "cfloat": "Use `np.complex128` instead.", + "longcomplex": "Use `np.clongdouble` instead.", + "clongfloat": "Use `np.clongdouble` instead.", + "string_": "Use `np.bytes_` instead.", + "unicode_": "Use `np.str_` instead.", + "Inf": "Use `np.inf` instead.", + "Infinity": "Use `np.inf` instead.", + "NaN": "Use `np.nan` instead.", + "infty": "Use `np.inf` instead.", + "issctype": "Use `issubclass(rep, np.generic)` instead.", + "maximum_sctype": + "Use a specific dtype instead. You should avoid relying " + "on any implicit mechanism and select the largest dtype of " + "a kind explicitly in the code.", + "obj2sctype": "Use `np.dtype(obj).type` instead.", + "sctype2char": "Use `np.dtype(obj).char` instead.", + "sctypes": "Access dtypes explicitly instead.", + "issubsctype": "Use `np.issubdtype` instead.", + "set_string_function": + "Use `np.set_printoptions` instead with a formatter for " + "custom printing of NumPy objects.", + "asfarray": "Use `np.asarray` with a proper dtype instead.", + "issubclass_": "Use `issubclass` builtin instead.", + "tracemalloc_domain": "It's now available from `np.lib`.", + "mat": "Use `np.asmatrix` instead.", + "recfromcsv": "Use `np.genfromtxt` with comma delimiter instead.", + "recfromtxt": "Use `np.genfromtxt` instead.", + "deprecate": "Emit `DeprecationWarning` with `warnings.warn` directly, " + "or use `typing.deprecated`.", + "deprecate_with_doc": "Emit `DeprecationWarning` with `warnings.warn` " + "directly, or use `typing.deprecated`.", + "find_common_type": + "Use `numpy.promote_types` or `numpy.result_type` instead. " + "To achieve semantics for the `scalar_types` argument, use " + "`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.", + "round_": "Use `np.round` instead.", + "get_array_wrap": "", + "DataSource": "It's still available as `np.lib.npyio.DataSource`.", + "nbytes": "Use `np.dtype().itemsize` instead.", + "byte_bounds": "Now it's available under `np.lib.array_utils.byte_bounds`", + "compare_chararrays": + "It's still available as `np.char.compare_chararrays`.", + "format_parser": "It's still available as `np.rec.format_parser`.", + "alltrue": "Use `np.all` instead.", + "sometrue": "Use `np.any` instead.", +} diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_expired_attrs_2_0.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/_expired_attrs_2_0.pyi new file mode 100644 index 0000000000000000000000000000000000000000..de6c2d10f9b0264238094e3ce9f8affafe5ca7a8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_expired_attrs_2_0.pyi @@ -0,0 +1,61 @@ +from typing import Final, TypedDict, final, type_check_only + +@final +@type_check_only +class _ExpiredAttributesType(TypedDict): + geterrobj: str + seterrobj: str + cast: str + source: str + lookfor: str + who: str + fastCopyAndTranspose: str + set_numeric_ops: str + NINF: str + PINF: str + NZERO: str + PZERO: str + add_newdoc: str + add_docstring: str + add_newdoc_ufunc: str + safe_eval: str + float_: str + complex_: str + longfloat: str + singlecomplex: str + cfloat: str + longcomplex: str + clongfloat: str + string_: str + unicode_: str + Inf: str + Infinity: str + NaN: str + infty: str + issctype: str + maximum_sctype: str + obj2sctype: str + sctype2char: str + sctypes: str + issubsctype: str + set_string_function: str + asfarray: str + issubclass_: str + tracemalloc_domain: str + mat: str + recfromcsv: str + recfromtxt: str + deprecate: str + deprecate_with_doc: str + find_common_type: str + round_: str + get_array_wrap: str + DataSource: str + nbytes: str + byte_bounds: str + compare_chararrays: str + format_parser: str + alltrue: str + sometrue: str + +__expired_attributes__: Final[_ExpiredAttributesType] = ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_globals.py b/data/miniconda3/lib/python3.13/site-packages/numpy/_globals.py new file mode 100644 index 0000000000000000000000000000000000000000..ada8d5c41af0c0ff939a28b6d690e2e392deedb9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_globals.py @@ -0,0 +1,121 @@ +""" +Module defining global singleton classes. + +This module raises a RuntimeError if an attempt to reload it is made. In that +way the identities of the classes defined here are fixed and will remain so +even if numpy itself is reloaded. In particular, a function like the following +will still work correctly after numpy is reloaded:: + + def foo(arg=np._NoValue): + if arg is np._NoValue: + ... + +That was not the case when the singleton classes were defined in the numpy +``__init__.py`` file. See gh-7844 for a discussion of the reload problem that +motivated this module. + +""" +import enum + +from ._utils import set_module as _set_module + +__all__ = ['_NoValue', '_CopyMode'] + + +# Disallow reloading this module so as to preserve the identities of the +# classes defined here. +if '_is_loaded' in globals(): + raise RuntimeError('Reloading numpy._globals is not allowed') +_is_loaded = True + + +class _NoValueType: + """Special keyword value. + + The instance of this class may be used as the default value assigned to a + keyword if no other obvious default (e.g., `None`) is suitable, + + Common reasons for using this keyword are: + + - A new keyword is added to a function, and that function forwards its + inputs to another function or method which can be defined outside of + NumPy. For example, ``np.std(x)`` calls ``x.std``, so when a ``keepdims`` + keyword was added that could only be forwarded if the user explicitly + specified ``keepdims``; downstream array libraries may not have added + the same keyword, so adding ``x.std(..., keepdims=keepdims)`` + unconditionally could have broken previously working code. + - A keyword is being deprecated, and a deprecation warning must only be + emitted when the keyword is used. + + """ + __instance = None + + def __new__(cls): + # ensure that only one instance exists + if not cls.__instance: + cls.__instance = super().__new__(cls) + return cls.__instance + + def __repr__(self): + return "" + + +_NoValue = _NoValueType() + + +@_set_module("numpy") +class _CopyMode(enum.Enum): + """ + An enumeration for the copy modes supported + by numpy.copy() and numpy.array(). The following three modes are supported, + + - ALWAYS: This means that a deep copy of the input + array will always be taken. + - IF_NEEDED: This means that a deep copy of the input + array will be taken only if necessary. + - NEVER: This means that the deep copy will never be taken. + If a copy cannot be avoided then a `ValueError` will be + raised. + + Note that the buffer-protocol could in theory do copies. NumPy currently + assumes an object exporting the buffer protocol will never do this. + """ + + ALWAYS = True + NEVER = False + IF_NEEDED = 2 + + def __bool__(self): + # For backwards compatibility + if self == _CopyMode.ALWAYS: + return True + + if self == _CopyMode.NEVER: + return False + + raise ValueError(f"{self} is neither True nor False.") + + +class _SignatureDescriptor: + # A descriptor to store on the ufunc __dict__ that avoids definig a + # signature for the ufunc class/type but allows the instance to have one. + # This is needed because inspect.signature() chokes on normal properties + # (as of 3.14 at least). + # We could also set __signature__ on the instance but this allows deferred + # computation of the signature. + def __get__(self, obj, objtype=None): + # Delay import, not a critical path but need to avoid circular import. + from numpy._core._internal import _ufunc_inspect_signature_builder + + if obj is None: + # could also return None, which is accepted as "not set" by + # inspect.signature(). + raise AttributeError( + "type object 'numpy.ufunc' has no attribute '__signature__'") + + # Store on the instance, after this the descriptor won't be used. + obj.__signature__ = _ufunc_inspect_signature_builder(obj) + return obj.__signature__ + + +_signature_descriptor = _SignatureDescriptor() diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_globals.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/_globals.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b2231a9636b0863be24555734d66df6da3464ac4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_globals.pyi @@ -0,0 +1,17 @@ +__all__ = ["_CopyMode", "_NoValue"] + +import enum +from typing import Final, final + +@final +class _CopyMode(enum.Enum): + ALWAYS = True + NEVER = False + IF_NEEDED = 2 + + def __bool__(self, /) -> bool: ... + +@final +class _NoValueType: ... + +_NoValue: Final[_NoValueType] = ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_pytesttester.py b/data/miniconda3/lib/python3.13/site-packages/numpy/_pytesttester.py new file mode 100644 index 0000000000000000000000000000000000000000..77342e44aea0251c513dd0ed7a8fb67b074e298f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_pytesttester.py @@ -0,0 +1,201 @@ +""" +Pytest test running. + +This module implements the ``test()`` function for NumPy modules. The usual +boiler plate for doing that is to put the following in the module +``__init__.py`` file:: + + from numpy._pytesttester import PytestTester + test = PytestTester(__name__) + del PytestTester + + +Warnings filtering and other runtime settings should be dealt with in the +``pytest.ini`` file in the numpy repo root. The behavior of the test depends on +whether or not that file is found as follows: + +* ``pytest.ini`` is present (develop mode) + All warnings except those explicitly filtered out are raised as error. +* ``pytest.ini`` is absent (release mode) + DeprecationWarnings and PendingDeprecationWarnings are ignored, other + warnings are passed through. + +In practice, tests run from the numpy repo are run in development mode with +``spin``, through the standard ``spin test`` invocation or from an inplace +build with ``pytest numpy``. + +This module is imported by every numpy subpackage, so lies at the top level to +simplify circular import issues. For the same reason, it contains no numpy +imports at module scope, instead importing numpy within function calls. +""" +import os +import sys + +__all__ = ['PytestTester'] + + +def _show_numpy_info(): + import numpy as np + + print(f"NumPy version {np.__version__}") + info = np.lib._utils_impl._opt_info() + print("NumPy CPU features: ", (info or 'nothing enabled')) + + +class PytestTester: + """ + Pytest test runner. + + A test function is typically added to a package's __init__.py like so:: + + from numpy._pytesttester import PytestTester + test = PytestTester(__name__).test + del PytestTester + + Calling this test function finds and runs all tests associated with the + module and all its sub-modules. + + Attributes + ---------- + module_name : str + Full path to the package to test. + + Parameters + ---------- + module_name : module name + The name of the module to test. + + Notes + ----- + Unlike the previous ``nose``-based implementation, this class is not + publicly exposed as it performs some ``numpy``-specific warning + suppression. + + """ + def __init__(self, module_name): + self.module_name = module_name + self.__module__ = module_name + + def __call__(self, label='fast', verbose=1, extra_argv=None, + doctests=False, coverage=False, durations=-1, tests=None): + """ + Run tests for module using pytest. + + Parameters + ---------- + label : {'fast', 'full'}, optional + Identifies the tests to run. When set to 'fast', tests decorated + with `pytest.mark.slow` are skipped, when 'full', the slow marker + is ignored. + verbose : int, optional + Verbosity value for test outputs, in the range 1-3. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytests. + doctests : bool, optional + .. note:: Not supported + coverage : bool, optional + If True, report coverage of NumPy code. Default is False. + Requires installation of (pip) pytest-cov. + durations : int, optional + If < 0, do nothing, If 0, report time of all tests, if > 0, + report the time of the slowest `timer` tests. Default is -1. + tests : test or list of tests + Tests to be executed with pytest '--pyargs' + + Returns + ------- + result : bool + Return True on success, false otherwise. + + Notes + ----- + Each NumPy module exposes `test` in its namespace to run all tests for + it. For example, to run all tests for numpy.lib: + + >>> np.lib.test() #doctest: +SKIP + + Examples + -------- + >>> result = np.lib.test() #doctest: +SKIP + ... + 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds + >>> result + True + + """ + import warnings + + import pytest + + module = sys.modules[self.module_name] + module_path = os.path.abspath(module.__path__[0]) + + # setup the pytest arguments + pytest_args = ["-l"] + + # offset verbosity. The "-q" cancels a "-v". + pytest_args += ["-q"] + + if sys.version_info < (3, 12): + with warnings.catch_warnings(): + warnings.simplefilter("always") + # Filter out distutils cpu warnings (could be localized to + # distutils tests). ASV has problems with top level import, + # so fetch module for suppression here. + from numpy.distutils import cpuinfo # noqa: F401 + + # Filter out annoying import messages. Want these in both develop and + # release mode. + pytest_args += [ + "-W ignore:Not importing directory", + "-W ignore:numpy.dtype size changed", + "-W ignore:numpy.ufunc size changed", + "-W ignore::UserWarning:cpuinfo", + ] + + # When testing matrices, ignore their PendingDeprecationWarnings + pytest_args += [ + "-W ignore:the matrix subclass is not", + "-W ignore:Importing from numpy.matlib is", + ] + + if doctests: + pytest_args += ["--doctest-modules"] + + if extra_argv: + pytest_args += list(extra_argv) + + if verbose > 1: + pytest_args += ["-" + "v" * (verbose - 1)] + + if coverage: + pytest_args += ["--cov=" + module_path] + + if label == "fast": + # not importing at the top level to avoid circular import of module + from numpy.testing import IS_PYPY + if IS_PYPY: + pytest_args += ["-m", "not slow and not slow_pypy"] + else: + pytest_args += ["-m", "not slow"] + + elif label != "full": + pytest_args += ["-m", label] + + if durations >= 0: + pytest_args += [f"--durations={durations}"] + + if tests is None: + tests = [self.module_name] + + pytest_args += ["--pyargs"] + list(tests) + + # run tests. + _show_numpy_info() + + try: + code = pytest.main(pytest_args) + except SystemExit as exc: + code = exc.code + + return code == 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/_pytesttester.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/_pytesttester.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bd71239314b409102656a2a2826867f737876227 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/_pytesttester.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable +from typing import Literal as L + +__all__ = ["PytestTester"] + +class PytestTester: + module_name: str + def __init__(self, module_name: str) -> None: ... + def __call__( + self, + label: L["fast", "full"] = "fast", + verbose: int = 1, + extra_argv: Iterable[str] | None = None, + doctests: L[False] = False, + coverage: bool = False, + durations: int = -1, + tests: Iterable[str] | None = None, + ) -> bool: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/conftest.py b/data/miniconda3/lib/python3.13/site-packages/numpy/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..c3c96ef3bc39f27f069feb269eb65c9bea55f7a0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/conftest.py @@ -0,0 +1,248 @@ +""" +Pytest configuration and fixtures for the Numpy test suite. +""" +import os +import sys +import tempfile +import warnings +from contextlib import contextmanager +from pathlib import Path + +import hypothesis +import pytest + +import numpy +from numpy._core._multiarray_tests import get_fpu_mode +from numpy.testing._private.utils import NOGIL_BUILD + +try: + from scipy_doctest.conftest import dt_config + HAVE_SCPDT = True +except ModuleNotFoundError: + HAVE_SCPDT = False + +try: + import pytest_run_parallel # noqa: F401 + PARALLEL_RUN_AVALIABLE = True +except ModuleNotFoundError: + PARALLEL_RUN_AVALIABLE = False + +_old_fpu_mode = None +_collect_results = {} + +# Use a known and persistent tmpdir for hypothesis' caches, which +# can be automatically cleared by the OS or user. +hypothesis.configuration.set_hypothesis_home_dir( + os.path.join(tempfile.gettempdir(), ".hypothesis") +) + +# We register two custom profiles for Numpy - for details see +# https://hypothesis.readthedocs.io/en/latest/settings.html +# The first is designed for our own CI runs; the latter also +# forces determinism and is designed for use via np.test() +hypothesis.settings.register_profile( + name="numpy-profile", deadline=None, print_blob=True, +) +hypothesis.settings.register_profile( + name="np.test() profile", + deadline=None, print_blob=True, database=None, derandomize=True, + suppress_health_check=list(hypothesis.HealthCheck), +) +# Note that the default profile is chosen based on the presence +# of pytest.ini, but can be overridden by passing the +# --hypothesis-profile=NAME argument to pytest. +_pytest_ini = os.path.join(os.path.dirname(__file__), "..", "pytest.ini") +hypothesis.settings.load_profile( + "numpy-profile" if os.path.isfile(_pytest_ini) else "np.test() profile" +) + +# The experimentalAPI is used in _umath_tests +os.environ["NUMPY_EXPERIMENTAL_DTYPE_API"] = "1" + +def pytest_configure(config): + config.addinivalue_line("markers", + "valgrind_error: Tests that are known to error under valgrind.") + config.addinivalue_line("markers", + "leaks_references: Tests that are known to leak references.") + config.addinivalue_line("markers", + "slow: Tests that are very slow.") + config.addinivalue_line("markers", + "slow_pypy: Tests that are very slow on pypy.") + if not PARALLEL_RUN_AVALIABLE: + config.addinivalue_line("markers", + "parallel_threads(n): run the given test function in parallel " + "using `n` threads.", + ) + config.addinivalue_line("markers", + "iterations(n): run the given test function `n` times in each thread", + ) + config.addinivalue_line("markers", + "thread_unsafe: mark the test function as single-threaded", + ) + + +def pytest_addoption(parser): + parser.addoption("--available-memory", action="store", default=None, + help=("Set amount of memory available for running the " + "test suite. This can result to tests requiring " + "especially large amounts of memory to be skipped. " + "Equivalent to setting environment variable " + "NPY_AVAILABLE_MEM. Default: determined" + "automatically.")) + + +gil_enabled_at_start = True +if NOGIL_BUILD: + gil_enabled_at_start = sys._is_gil_enabled() + + +def pytest_sessionstart(session): + available_mem = session.config.getoption('available_memory') + if available_mem is not None: + os.environ['NPY_AVAILABLE_MEM'] = available_mem + + +def pytest_terminal_summary(terminalreporter, exitstatus, config): + if NOGIL_BUILD and not gil_enabled_at_start and sys._is_gil_enabled(): + tr = terminalreporter + tr.ensure_newline() + tr.section("GIL re-enabled", sep="=", red=True, bold=True) + tr.line("The GIL was re-enabled at runtime during the tests.") + tr.line("This can happen with no test failures if the RuntimeWarning") + tr.line("raised by Python when this happens is filtered by a test.") + tr.line("") + tr.line("Please ensure all new C modules declare support for running") + tr.line("without the GIL. Any new tests that intentionally imports ") + tr.line("code that re-enables the GIL should do so in a subprocess.") + pytest.exit("GIL re-enabled during tests", returncode=1) + +# FIXME when yield tests are gone. +@pytest.hookimpl(tryfirst=True) +def pytest_itemcollected(item): + """ + Check FPU precision mode was not changed during test collection. + + The clumsy way we do it here is mainly necessary because numpy + still uses yield tests, which can execute code at test collection + time. + """ + global _old_fpu_mode + + mode = get_fpu_mode() + + if _old_fpu_mode is None: + _old_fpu_mode = mode + elif mode != _old_fpu_mode: + _collect_results[item] = (_old_fpu_mode, mode) + _old_fpu_mode = mode + + # mark f2py tests as thread unsafe + if Path(item.fspath).parent == Path(__file__).parent / 'f2py' / 'tests': + item.add_marker(pytest.mark.thread_unsafe( + reason="f2py tests are thread-unsafe")) + + +@pytest.fixture(scope="function", autouse=True) +def check_fpu_mode(request): + """ + Check FPU precision mode was not changed during the test. + """ + old_mode = get_fpu_mode() + yield + new_mode = get_fpu_mode() + + if old_mode != new_mode: + raise AssertionError(f"FPU precision mode changed from {old_mode:#x} to " + f"{new_mode:#x} during the test") + + collect_result = _collect_results.get(request.node) + if collect_result is not None: + old_mode, new_mode = collect_result + raise AssertionError(f"FPU precision mode changed from {old_mode:#x} to " + f"{new_mode:#x} when collecting the test") + + +@pytest.fixture(autouse=True) +def add_np(doctest_namespace): + doctest_namespace['np'] = numpy + + +if HAVE_SCPDT: + + @contextmanager + def warnings_errors_and_rng(test=None): + """Filter out the wall of DeprecationWarnings. + """ + msgs = ["The numpy.linalg.linalg", + "The numpy.fft.helper", + "dep_util", + "pkg_resources", + "numpy.core.umath", + "msvccompiler", + "Deprecated call", + "numpy.core", + "Importing from numpy.matlib", + "This function is deprecated.", # random_integers + "Data type alias 'a'", # numpy.rec.fromfile + "Arrays of 2-dimensional vectors", # matlib.cross + "NumPy warning suppression and assertion utilities are deprecated." + ] + msg = "|".join(msgs) + + msgs_r = [ + "invalid value encountered", + "divide by zero encountered" + ] + msg_r = "|".join(msgs_r) + + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', category=DeprecationWarning, message=msg + ) + warnings.filterwarnings( + 'ignore', category=RuntimeWarning, message=msg_r + ) + yield + + # find and check doctests under this context manager + dt_config.user_context_mgr = warnings_errors_and_rng + + # numpy specific tweaks from refguide-check + dt_config.rndm_markers.add('#uninitialized') + dt_config.rndm_markers.add('# uninitialized') + + # make the checker pick on mismatched dtypes + dt_config.strict_check = True + + import doctest + dt_config.optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS + + # recognize the StringDType repr + dt_config.check_namespace['StringDType'] = numpy.dtypes.StringDType + + # temporary skips + dt_config.skiplist = { + 'numpy.savez', # unclosed file + 'numpy.matlib.savez', + 'numpy.__array_namespace_info__', + 'numpy.matlib.__array_namespace_info__', + } + + # xfail problematic tutorials + dt_config.pytest_extra_xfail = { + 'how-to-verify-bug.rst': '', + 'c-info.ufunc-tutorial.rst': '', + 'basics.interoperability.rst': 'needs pandas', + 'basics.dispatch.rst': 'errors out in /testing/overrides.py', + 'basics.subclassing.rst': '.. testcode:: admonitions not understood', + 'misc.rst': 'manipulates warnings', + } + + # ignores are for things fail doctest collection (optionals etc) + dt_config.pytest_extra_ignore = [ + 'numpy/distutils', + 'numpy/_core/cversions.py', + 'numpy/_pyinstaller', + 'numpy/random/_examples', + 'numpy/f2py/_backends/_distutils.py', + ] diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/dtypes.py b/data/miniconda3/lib/python3.13/site-packages/numpy/dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..550a29e18f292e65600108804636b833c75d1be4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/dtypes.py @@ -0,0 +1,41 @@ +""" +This module is home to specific dtypes related functionality and their classes. +For more general information about dtypes, also see `numpy.dtype` and +:ref:`arrays.dtypes`. + +Similar to the builtin ``types`` module, this submodule defines types (classes) +that are not widely used directly. + +.. versionadded:: NumPy 1.25 + + The dtypes module is new in NumPy 1.25. Previously DType classes were + only accessible indirectly. + + +DType classes +------------- + +The following are the classes of the corresponding NumPy dtype instances and +NumPy scalar types. The classes can be used in ``isinstance`` checks and can +also be instantiated or used directly. Direct use of these classes is not +typical, since their scalar counterparts (e.g. ``np.float64``) or strings +like ``"float64"`` can be used. +""" + +# See doc/source/reference/routines.dtypes.rst for module-level docs + +__all__ = [] + + +def _add_dtype_helper(DType, alias): + # Function to add DTypes a bit more conveniently without channeling them + # through `numpy._core._multiarray_umath` namespace or similar. + from numpy import dtypes + + setattr(dtypes, DType.__name__, DType) + __all__.append(DType.__name__) + + if alias: + alias = alias.removeprefix("numpy.dtypes.") + setattr(dtypes, alias, DType) + __all__.append(alias) diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/dtypes.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/dtypes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3e34113edd4f4d87847e01ebe5a90a002a4aab00 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/dtypes.pyi @@ -0,0 +1,630 @@ +# ruff: noqa: ANN401 +from typing import ( + Any, + Generic, + Literal as L, + LiteralString, + Never, + NoReturn, + Self, + TypeAlias, + final, + overload, + type_check_only, +) +from typing_extensions import TypeVar + +import numpy as np + +__all__ = [ # noqa: RUF022 + "BoolDType", + "Int8DType", + "ByteDType", + "UInt8DType", + "UByteDType", + "Int16DType", + "ShortDType", + "UInt16DType", + "UShortDType", + "Int32DType", + "IntDType", + "UInt32DType", + "UIntDType", + "Int64DType", + "LongDType", + "UInt64DType", + "ULongDType", + "LongLongDType", + "ULongLongDType", + "Float16DType", + "Float32DType", + "Float64DType", + "LongDoubleDType", + "Complex64DType", + "Complex128DType", + "CLongDoubleDType", + "ObjectDType", + "BytesDType", + "StrDType", + "VoidDType", + "DateTime64DType", + "TimeDelta64DType", + "StringDType", +] + +# Helper base classes (typing-only) + +_ScalarT_co = TypeVar("_ScalarT_co", bound=np.generic, covariant=True) + +@type_check_only +class _SimpleDType(np.dtype[_ScalarT_co], Generic[_ScalarT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + names: None # pyright: ignore[reportIncompatibleVariableOverride] + def __new__(cls, /) -> Self: ... + def __getitem__(self, key: Any, /) -> NoReturn: ... + @property + def base(self) -> np.dtype[_ScalarT_co]: ... + @property + def fields(self) -> None: ... + @property + def isalignedstruct(self) -> L[False]: ... + @property + def isnative(self) -> L[True]: ... + @property + def ndim(self) -> L[0]: ... + @property + def shape(self) -> tuple[()]: ... + @property + def subdtype(self) -> None: ... + +@type_check_only +class _LiteralDType(_SimpleDType[_ScalarT_co], Generic[_ScalarT_co]): # type: ignore[misc] + @property + def flags(self) -> L[0]: ... + @property + def hasobject(self) -> L[False]: ... + +# Helper mixins (typing-only): + +_KindT_co = TypeVar("_KindT_co", bound=LiteralString, covariant=True) +_CharT_co = TypeVar("_CharT_co", bound=LiteralString, covariant=True) +_NumT_co = TypeVar("_NumT_co", bound=int, covariant=True) + +@type_check_only +class _TypeCodes(Generic[_KindT_co, _CharT_co, _NumT_co]): + @final + @property + def kind(self) -> _KindT_co: ... + @final + @property + def char(self) -> _CharT_co: ... + @final + @property + def num(self) -> _NumT_co: ... + +@type_check_only +class _NoOrder: + @final + @property + def byteorder(self) -> L["|"]: ... + +@type_check_only +class _NativeOrder: + @final + @property + def byteorder(self) -> L["="]: ... + +_DataSize_co = TypeVar("_DataSize_co", bound=int, covariant=True) +_ItemSize_co = TypeVar("_ItemSize_co", bound=int, covariant=True, default=int) + +@type_check_only +class _NBit(Generic[_DataSize_co, _ItemSize_co]): + @final + @property + def alignment(self) -> _DataSize_co: ... + @final + @property + def itemsize(self) -> _ItemSize_co: ... + +@type_check_only +class _8Bit(_NoOrder, _NBit[L[1], L[1]]): ... + +# Boolean: + +@final +class BoolDType( # type: ignore[misc] + _TypeCodes[L["b"], L["?"], L[0]], + _8Bit, + _LiteralDType[np.bool], +): + @property + def name(self) -> L["bool"]: ... + @property + def str(self) -> L["|b1"]: ... + +# Sized integers: + +@final +class Int8DType( # type: ignore[misc] + _TypeCodes[L["i"], L["b"], L[1]], + _8Bit, + _LiteralDType[np.int8], +): + @property + def name(self) -> L["int8"]: ... + @property + def str(self) -> L["|i1"]: ... + +@final +class UInt8DType( # type: ignore[misc] + _TypeCodes[L["u"], L["B"], L[2]], + _8Bit, + _LiteralDType[np.uint8], +): + @property + def name(self) -> L["uint8"]: ... + @property + def str(self) -> L["|u1"]: ... + +@final +class Int16DType( # type: ignore[misc] + _TypeCodes[L["i"], L["h"], L[3]], + _NativeOrder, + _NBit[L[2], L[2]], + _LiteralDType[np.int16], +): + @property + def name(self) -> L["int16"]: ... + @property + def str(self) -> L["i2"]: ... + +@final +class UInt16DType( # type: ignore[misc] + _TypeCodes[L["u"], L["H"], L[4]], + _NativeOrder, + _NBit[L[2], L[2]], + _LiteralDType[np.uint16], +): + @property + def name(self) -> L["uint16"]: ... + @property + def str(self) -> L["u2"]: ... + +@final +class Int32DType( # type: ignore[misc] + _TypeCodes[L["i"], L["i", "l"], L[5, 7]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.int32], +): + @property + def name(self) -> L["int32"]: ... + @property + def str(self) -> L["i4"]: ... + +@final +class UInt32DType( # type: ignore[misc] + _TypeCodes[L["u"], L["I", "L"], L[6, 8]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.uint32], +): + @property + def name(self) -> L["uint32"]: ... + @property + def str(self) -> L["u4"]: ... + +@final +class Int64DType( # type: ignore[misc] + _TypeCodes[L["i"], L["l", "q"], L[7, 9]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.int64], +): + @property + def name(self) -> L["int64"]: ... + @property + def str(self) -> L["i8"]: ... + +@final +class UInt64DType( # type: ignore[misc] + _TypeCodes[L["u"], L["L", "Q"], L[8, 10]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.uint64], +): + @property + def name(self) -> L["uint64"]: ... + @property + def str(self) -> L["u8"]: ... + +# Standard C-named version/alias: +# NOTE: Don't make these `Final`: it will break stubtest +ByteDType = Int8DType +UByteDType = UInt8DType +ShortDType = Int16DType +UShortDType = UInt16DType + +@final +class IntDType( # type: ignore[misc] + _TypeCodes[L["i"], L["i"], L[5]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.intc], +): + @property + def name(self) -> L["int32"]: ... + @property + def str(self) -> L["i4"]: ... + +@final +class UIntDType( # type: ignore[misc] + _TypeCodes[L["u"], L["I"], L[6]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.uintc], +): + @property + def name(self) -> L["uint32"]: ... + @property + def str(self) -> L["u4"]: ... + +@final +class LongDType( # type: ignore[misc] + _TypeCodes[L["i"], L["l"], L[7]], + _NativeOrder, + _NBit[L[4, 8], L[4, 8]], + _LiteralDType[np.long], +): + @property + def name(self) -> L["int32", "int64"]: ... + @property + def str(self) -> L["i4", "i8"]: ... + +@final +class ULongDType( # type: ignore[misc] + _TypeCodes[L["u"], L["L"], L[8]], + _NativeOrder, + _NBit[L[4, 8], L[4, 8]], + _LiteralDType[np.ulong], +): + @property + def name(self) -> L["uint32", "uint64"]: ... + @property + def str(self) -> L["u4", "u8"]: ... + +@final +class LongLongDType( # type: ignore[misc] + _TypeCodes[L["i"], L["q"], L[9]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.longlong], +): + @property + def name(self) -> L["int64"]: ... + @property + def str(self) -> L["i8"]: ... + +@final +class ULongLongDType( # type: ignore[misc] + _TypeCodes[L["u"], L["Q"], L[10]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.ulonglong], +): + @property + def name(self) -> L["uint64"]: ... + @property + def str(self) -> L["u8"]: ... + +# Floats: + +@final +class Float16DType( # type: ignore[misc] + _TypeCodes[L["f"], L["e"], L[23]], + _NativeOrder, + _NBit[L[2], L[2]], + _LiteralDType[np.float16], +): + @property + def name(self) -> L["float16"]: ... + @property + def str(self) -> L["f2"]: ... + +@final +class Float32DType( # type: ignore[misc] + _TypeCodes[L["f"], L["f"], L[11]], + _NativeOrder, + _NBit[L[4], L[4]], + _LiteralDType[np.float32], +): + @property + def name(self) -> L["float32"]: ... + @property + def str(self) -> L["f4"]: ... + +@final +class Float64DType( # type: ignore[misc] + _TypeCodes[L["f"], L["d"], L[12]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.float64], +): + @property + def name(self) -> L["float64"]: ... + @property + def str(self) -> L["f8"]: ... + +@final +class LongDoubleDType( # type: ignore[misc] + _TypeCodes[L["f"], L["g"], L[13]], + _NativeOrder, + _NBit[L[8, 12, 16], L[8, 12, 16]], + _LiteralDType[np.longdouble], +): + @property + def name(self) -> L["float64", "float96", "float128"]: ... + @property + def str(self) -> L["f8", "f12", "f16"]: ... + +# Complex: + +@final +class Complex64DType( # type: ignore[misc] + _TypeCodes[L["c"], L["F"], L[14]], + _NativeOrder, + _NBit[L[4], L[8]], + _LiteralDType[np.complex64], +): + @property + def name(self) -> L["complex64"]: ... + @property + def str(self) -> L["c8"]: ... + +@final +class Complex128DType( # type: ignore[misc] + _TypeCodes[L["c"], L["D"], L[15]], + _NativeOrder, + _NBit[L[8], L[16]], + _LiteralDType[np.complex128], +): + @property + def name(self) -> L["complex128"]: ... + @property + def str(self) -> L["c16"]: ... + +@final +class CLongDoubleDType( # type: ignore[misc] + _TypeCodes[L["c"], L["G"], L[16]], + _NativeOrder, + _NBit[L[8, 12, 16], L[16, 24, 32]], + _LiteralDType[np.clongdouble], +): + @property + def name(self) -> L["complex128", "complex192", "complex256"]: ... + @property + def str(self) -> L["c16", "c24", "c32"]: ... + +# Python objects: + +@final +class ObjectDType( # type: ignore[misc] + _TypeCodes[L["O"], L["O"], L[17]], + _NoOrder, + _NBit[L[8], L[8]], + _SimpleDType[np.object_], +): + @property + def hasobject(self) -> L[True]: ... + @property + def name(self) -> L["object"]: ... + @property + def str(self) -> L["|O"]: ... + +# Flexible: + +@final +class BytesDType( # type: ignore[misc] + _TypeCodes[L["S"], L["S"], L[18]], + _NoOrder, + _NBit[L[1], _ItemSize_co], + _SimpleDType[np.bytes_], + Generic[_ItemSize_co], +): + def __new__(cls, size: _ItemSize_co, /) -> BytesDType[_ItemSize_co]: ... + @property + def hasobject(self) -> L[False]: ... + @property + def name(self) -> LiteralString: ... + @property + def str(self) -> LiteralString: ... + +@final +class StrDType( # type: ignore[misc] + _TypeCodes[L["U"], L["U"], L[19]], + _NativeOrder, + _NBit[L[4], _ItemSize_co], + _SimpleDType[np.str_], + Generic[_ItemSize_co], +): + def __new__(cls, size: _ItemSize_co, /) -> StrDType[_ItemSize_co]: ... + @property + def hasobject(self) -> L[False]: ... + @property + def name(self) -> LiteralString: ... + @property + def str(self) -> LiteralString: ... + +@final +class VoidDType( # type: ignore[misc] + _TypeCodes[L["V"], L["V"], L[20]], + _NoOrder, + _NBit[L[1], _ItemSize_co], + np.dtype[np.void], # pyright: ignore[reportGeneralTypeIssues] + Generic[_ItemSize_co], +): + # NOTE: `VoidDType(...)` raises a `TypeError` at the moment + def __new__(cls, length: _ItemSize_co, /) -> NoReturn: ... + @property + def base(self) -> Self: ... + @property + def isalignedstruct(self) -> L[False]: ... + @property + def isnative(self) -> L[True]: ... + @property + def ndim(self) -> L[0]: ... + @property + def shape(self) -> tuple[()]: ... + @property + def subdtype(self) -> None: ... + @property + def name(self) -> LiteralString: ... + @property + def str(self) -> LiteralString: ... + +# Other: + +_DateUnit: TypeAlias = L["Y", "M", "W", "D"] +_TimeUnit: TypeAlias = L["h", "m", "s", "ms", "us", "ns", "ps", "fs", "as"] +_DateTimeUnit: TypeAlias = _DateUnit | _TimeUnit + +@final +class DateTime64DType( # type: ignore[misc] + _TypeCodes[L["M"], L["M"], L[21]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.datetime64], +): + # NOTE: `DateTime64DType(...)` raises a `TypeError` at the moment + # TODO: Once implemented, don't forget the`unit: L["μs"]` overload. + def __new__(cls, unit: _DateTimeUnit, /) -> NoReturn: ... + @property + def name(self) -> L[ + "datetime64", + "datetime64[Y]", + "datetime64[M]", + "datetime64[W]", + "datetime64[D]", + "datetime64[h]", + "datetime64[m]", + "datetime64[s]", + "datetime64[ms]", + "datetime64[us]", + "datetime64[ns]", + "datetime64[ps]", + "datetime64[fs]", + "datetime64[as]", + ]: ... + @property + def str(self) -> L[ + "M8", + "M8[Y]", + "M8[M]", + "M8[W]", + "M8[D]", + "M8[h]", + "M8[m]", + "M8[s]", + "M8[ms]", + "M8[us]", + "M8[ns]", + "M8[ps]", + "M8[fs]", + "M8[as]", + ]: ... + +@final +class TimeDelta64DType( # type: ignore[misc] + _TypeCodes[L["m"], L["m"], L[22]], + _NativeOrder, + _NBit[L[8], L[8]], + _LiteralDType[np.timedelta64], +): + # NOTE: `TimeDelta64DType(...)` raises a `TypeError` at the moment + # TODO: Once implemented, don't forget to overload on `unit: L["μs"]`. + def __new__(cls, unit: _DateTimeUnit, /) -> NoReturn: ... + @property + def name(self) -> L[ + "timedelta64", + "timedelta64[Y]", + "timedelta64[M]", + "timedelta64[W]", + "timedelta64[D]", + "timedelta64[h]", + "timedelta64[m]", + "timedelta64[s]", + "timedelta64[ms]", + "timedelta64[us]", + "timedelta64[ns]", + "timedelta64[ps]", + "timedelta64[fs]", + "timedelta64[as]", + ]: ... + @property + def str(self) -> L[ + "m8", + "m8[Y]", + "m8[M]", + "m8[W]", + "m8[D]", + "m8[h]", + "m8[m]", + "m8[s]", + "m8[ms]", + "m8[us]", + "m8[ns]", + "m8[ps]", + "m8[fs]", + "m8[as]", + ]: ... + +_NaObjectT_co = TypeVar("_NaObjectT_co", default=Never, covariant=True) + +@final +class StringDType( # type: ignore[misc] + _TypeCodes[L["T"], L["T"], L[2056]], + _NativeOrder, + _NBit[L[8], L[16]], + # TODO(jorenham): change once we have a string scalar type: + # https://github.com/numpy/numpy/issues/28165 + np.dtype[str], # type: ignore[type-var] # pyright: ignore[reportGeneralTypeIssues, reportInvalidTypeArguments] + Generic[_NaObjectT_co], +): + @property + def na_object(self) -> _NaObjectT_co: ... + @property + def coerce(self) -> L[True]: ... + + # + @overload + def __new__(cls, /, *, coerce: bool = True) -> Self: ... + @overload + def __new__(cls, /, *, na_object: _NaObjectT_co, coerce: bool = True) -> Self: ... + + # + def __getitem__(self, key: Never, /) -> NoReturn: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + @property + def fields(self) -> None: ... + @property + def base(self) -> Self: ... + @property + def ndim(self) -> L[0]: ... + @property + def shape(self) -> tuple[()]: ... + + # + @property + def name(self) -> L["StringDType64", "StringDType128"]: ... + @property + def subdtype(self) -> None: ... + @property + def type(self) -> type[str]: ... + @property + def str(self) -> L["|T8", "|T16"]: ... + + # + @property + def hasobject(self) -> L[True]: ... + @property + def isalignedstruct(self) -> L[False]: ... + @property + def isnative(self) -> L[True]: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/numpy/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..cf70b4a4ce3bd752fc9dc10d32de8646217d9ef1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/exceptions.py @@ -0,0 +1,246 @@ +""" +Exceptions and Warnings +======================= + +General exceptions used by NumPy. Note that some exceptions may be module +specific, such as linear algebra errors. + +.. versionadded:: NumPy 1.25 + + The exceptions module is new in NumPy 1.25. + +.. currentmodule:: numpy.exceptions + +Warnings +-------- +.. autosummary:: + :toctree: generated/ + + ComplexWarning Given when converting complex to real. + VisibleDeprecationWarning Same as a DeprecationWarning, but more visible. + RankWarning Issued when the design matrix is rank deficient. + +Exceptions +---------- +.. autosummary:: + :toctree: generated/ + + AxisError Given when an axis was invalid. + DTypePromotionError Given when no common dtype could be found. + TooHardError Error specific to `numpy.shares_memory`. + +""" + + +__all__ = [ + "ComplexWarning", "VisibleDeprecationWarning", "ModuleDeprecationWarning", + "TooHardError", "AxisError", "DTypePromotionError"] + + +# Disallow reloading this module so as to preserve the identities of the +# classes defined here. +if '_is_loaded' in globals(): + raise RuntimeError('Reloading numpy._globals is not allowed') +_is_loaded = True + + +class ComplexWarning(RuntimeWarning): + """ + The warning raised when casting a complex dtype to a real dtype. + + As implemented, casting a complex number to a real discards its imaginary + part, but this behavior may not be what the user actually wants. + + """ + pass + + +class ModuleDeprecationWarning(DeprecationWarning): + """Module deprecation warning. + + .. warning:: + + This warning should not be used, since nose testing is not relevant + anymore. + + The nose tester turns ordinary Deprecation warnings into test failures. + That makes it hard to deprecate whole modules, because they get + imported by default. So this is a special Deprecation warning that the + nose tester will let pass without making tests fail. + + """ + pass + + +class VisibleDeprecationWarning(UserWarning): + """Visible deprecation warning. + + By default, python will not show deprecation warnings, so this class + can be used when a very visible warning is helpful, for example because + the usage is most likely a user bug. + + """ + pass + + +class RankWarning(RuntimeWarning): + """Matrix rank warning. + + Issued by polynomial functions when the design matrix is rank deficient. + + """ + pass + + +# Exception used in shares_memory() +class TooHardError(RuntimeError): + """``max_work`` was exceeded. + + This is raised whenever the maximum number of candidate solutions + to consider specified by the ``max_work`` parameter is exceeded. + Assigning a finite number to ``max_work`` may have caused the operation + to fail. + + """ + pass + + +class AxisError(ValueError, IndexError): + """Axis supplied was invalid. + + This is raised whenever an ``axis`` parameter is specified that is larger + than the number of array dimensions. + For compatibility with code written against older numpy versions, which + raised a mixture of :exc:`ValueError` and :exc:`IndexError` for this + situation, this exception subclasses both to ensure that + ``except ValueError`` and ``except IndexError`` statements continue + to catch ``AxisError``. + + Parameters + ---------- + axis : int or str + The out of bounds axis or a custom exception message. + If an axis is provided, then `ndim` should be specified as well. + ndim : int, optional + The number of array dimensions. + msg_prefix : str, optional + A prefix for the exception message. + + Attributes + ---------- + axis : int, optional + The out of bounds axis or ``None`` if a custom exception + message was provided. This should be the axis as passed by + the user, before any normalization to resolve negative indices. + + .. versionadded:: 1.22 + ndim : int, optional + The number of array dimensions or ``None`` if a custom exception + message was provided. + + .. versionadded:: 1.22 + + + Examples + -------- + >>> import numpy as np + >>> array_1d = np.arange(10) + >>> np.cumsum(array_1d, axis=1) + Traceback (most recent call last): + ... + numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1 + + Negative axes are preserved: + + >>> np.cumsum(array_1d, axis=-2) + Traceback (most recent call last): + ... + numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1 + + The class constructor generally takes the axis and arrays' + dimensionality as arguments: + + >>> print(np.exceptions.AxisError(2, 1, msg_prefix='error')) + error: axis 2 is out of bounds for array of dimension 1 + + Alternatively, a custom exception message can be passed: + + >>> print(np.exceptions.AxisError('Custom error message')) + Custom error message + + """ + + __slots__ = ("_msg", "axis", "ndim") + + def __init__(self, axis, ndim=None, msg_prefix=None): + if ndim is msg_prefix is None: + # single-argument form: directly set the error message + self._msg = axis + self.axis = None + self.ndim = None + else: + self._msg = msg_prefix + self.axis = axis + self.ndim = ndim + + def __str__(self): + axis = self.axis + ndim = self.ndim + + if axis is ndim is None: + return self._msg + else: + msg = f"axis {axis} is out of bounds for array of dimension {ndim}" + if self._msg is not None: + msg = f"{self._msg}: {msg}" + return msg + + +class DTypePromotionError(TypeError): + """Multiple DTypes could not be converted to a common one. + + This exception derives from ``TypeError`` and is raised whenever dtypes + cannot be converted to a single common one. This can be because they + are of a different category/class or incompatible instances of the same + one (see Examples). + + Notes + ----- + Many functions will use promotion to find the correct result and + implementation. For these functions the error will typically be chained + with a more specific error indicating that no implementation was found + for the input dtypes. + + Typically promotion should be considered "invalid" between the dtypes of + two arrays when `arr1 == arr2` can safely return all ``False`` because the + dtypes are fundamentally different. + + Examples + -------- + Datetimes and complex numbers are incompatible classes and cannot be + promoted: + + >>> import numpy as np + >>> np.result_type(np.dtype("M8[s]"), np.complex128) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + DTypePromotionError: The DType could not + be promoted by . This means that no common + DType exists for the given inputs. For example they cannot be stored in a + single array unless the dtype is `object`. The full list of DTypes is: + (, ) + + For example for structured dtypes, the structure can mismatch and the + same ``DTypePromotionError`` is given when two structured dtypes with + a mismatch in their number of fields is given: + + >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)]) + >>> dtype2 = np.dtype([("field1", np.float64)]) + >>> np.promote_types(dtype1, dtype2) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + DTypePromotionError: field names `('field1', 'field2')` and `('field1',)` + mismatch. + + """ # noqa: E501 + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/exceptions.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4cc4eff5d321324e0a8e8d522f7e7f95ecc6279f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/exceptions.pyi @@ -0,0 +1,27 @@ +from typing import overload + +__all__ = [ + "ComplexWarning", + "VisibleDeprecationWarning", + "ModuleDeprecationWarning", + "TooHardError", + "AxisError", + "DTypePromotionError", +] + +class ComplexWarning(RuntimeWarning): ... +class ModuleDeprecationWarning(DeprecationWarning): ... +class VisibleDeprecationWarning(UserWarning): ... +class RankWarning(RuntimeWarning): ... +class TooHardError(RuntimeError): ... +class DTypePromotionError(TypeError): ... + +class AxisError(ValueError, IndexError): + __slots__ = "_msg", "axis", "ndim" + + axis: int | None + ndim: int | None + @overload + def __init__(self, axis: str, ndim: None = None, msg_prefix: None = None) -> None: ... + @overload + def __init__(self, axis: int, ndim: int, msg_prefix: str | None = None) -> None: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/matlib.py b/data/miniconda3/lib/python3.13/site-packages/numpy/matlib.py new file mode 100644 index 0000000000000000000000000000000000000000..f27d503cdbca80c745b14b8854afecc56125df9a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/matlib.py @@ -0,0 +1,380 @@ +import warnings + +# 2018-05-29, PendingDeprecationWarning added to matrix.__new__ +# 2020-01-23, numpy 1.19.0 PendingDeprecatonWarning +warnings.warn("Importing from numpy.matlib is deprecated since 1.19.0. " + "The matrix subclass is not the recommended way to represent " + "matrices or deal with linear algebra (see " + "https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). " + "Please adjust your code to use regular ndarray. ", + PendingDeprecationWarning, stacklevel=2) + +import numpy as np + +# Matlib.py contains all functions in the numpy namespace with a few +# replacements. See doc/source/reference/routines.matlib.rst for details. +# Need * as we're copying the numpy namespace. +from numpy import * # noqa: F403 +from numpy.matrixlib.defmatrix import asmatrix, matrix + +__version__ = np.__version__ + +__all__ = ['rand', 'randn', 'repmat'] +__all__ += np.__all__ + +def empty(shape, dtype=None, order='C'): + """Return a new matrix of given shape and type, without initializing entries. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty matrix. + dtype : data-type, optional + Desired output data-type. + order : {'C', 'F'}, optional + Whether to store multi-dimensional data in row-major + (C-style) or column-major (Fortran-style) order in + memory. + + See Also + -------- + numpy.empty : Equivalent array function. + matlib.zeros : Return a matrix of zeros. + matlib.ones : Return a matrix of ones. + + Notes + ----- + Unlike other matrix creation functions (e.g. `matlib.zeros`, + `matlib.ones`), `matlib.empty` does not initialize the values of the + matrix, and may therefore be marginally faster. However, the values + stored in the newly allocated matrix are arbitrary. For reproducible + behavior, be sure to set each element of the matrix before reading. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.empty((2, 2)) # filled with random data + matrix([[ 6.76425276e-320, 9.79033856e-307], # random + [ 7.39337286e-309, 3.22135945e-309]]) + >>> np.matlib.empty((2, 2), dtype=int) + matrix([[ 6600475, 0], # random + [ 6586976, 22740995]]) + + """ + return ndarray.__new__(matrix, shape, dtype, order=order) + +def ones(shape, dtype=None, order='C'): + """ + Matrix of ones. + + Return a matrix of given shape and type, filled with ones. + + Parameters + ---------- + shape : {sequence of ints, int} + Shape of the matrix + dtype : data-type, optional + The desired data-type for the matrix, default is np.float64. + order : {'C', 'F'}, optional + Whether to store matrix in C- or Fortran-contiguous order, + default is 'C'. + + Returns + ------- + out : matrix + Matrix of ones of given shape, dtype, and order. + + See Also + -------- + ones : Array of ones. + matlib.zeros : Zero matrix. + + Notes + ----- + If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, + `out` becomes a single row matrix of shape ``(1,N)``. + + Examples + -------- + >>> np.matlib.ones((2,3)) + matrix([[1., 1., 1.], + [1., 1., 1.]]) + + >>> np.matlib.ones(2) + matrix([[1., 1.]]) + + """ + a = ndarray.__new__(matrix, shape, dtype, order=order) + a.fill(1) + return a + +def zeros(shape, dtype=None, order='C'): + """ + Return a matrix of given shape and type, filled with zeros. + + Parameters + ---------- + shape : int or sequence of ints + Shape of the matrix + dtype : data-type, optional + The desired data-type for the matrix, default is float. + order : {'C', 'F'}, optional + Whether to store the result in C- or Fortran-contiguous order, + default is 'C'. + + Returns + ------- + out : matrix + Zero matrix of given shape, dtype, and order. + + See Also + -------- + numpy.zeros : Equivalent array function. + matlib.ones : Return a matrix of ones. + + Notes + ----- + If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, + `out` becomes a single row matrix of shape ``(1,N)``. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.zeros((2, 3)) + matrix([[0., 0., 0.], + [0., 0., 0.]]) + + >>> np.matlib.zeros(2) + matrix([[0., 0.]]) + + """ + a = ndarray.__new__(matrix, shape, dtype, order=order) + a.fill(0) + return a + +def identity(n, dtype=None): + """ + Returns the square identity matrix of given size. + + Parameters + ---------- + n : int + Size of the returned identity matrix. + dtype : data-type, optional + Data-type of the output. Defaults to ``float``. + + Returns + ------- + out : matrix + `n` x `n` matrix with its main diagonal set to one, + and all other elements zero. + + See Also + -------- + numpy.identity : Equivalent array function. + matlib.eye : More general matrix identity function. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.identity(3, dtype=int) + matrix([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + """ + a = array([1] + n * [0], dtype=dtype) + b = empty((n, n), dtype=dtype) + b.flat = a + return b + +def eye(n, M=None, k=0, dtype=float, order='C'): + """ + Return a matrix with ones on the diagonal and zeros elsewhere. + + Parameters + ---------- + n : int + Number of rows in the output. + M : int, optional + Number of columns in the output, defaults to `n`. + k : int, optional + Index of the diagonal: 0 refers to the main diagonal, + a positive value refers to an upper diagonal, + and a negative value to a lower diagonal. + dtype : dtype, optional + Data-type of the returned matrix. + order : {'C', 'F'}, optional + Whether the output should be stored in row-major (C-style) or + column-major (Fortran-style) order in memory. + + Returns + ------- + I : matrix + A `n` x `M` matrix where all elements are equal to zero, + except for the `k`-th diagonal, whose values are equal to one. + + See Also + -------- + numpy.eye : Equivalent array function. + identity : Square identity matrix. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.eye(3, k=1, dtype=float) + matrix([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) + + """ + return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order)) + +def rand(*args): + """ + Return a matrix of random values with given shape. + + Create a matrix of the given shape and propagate it with + random samples from a uniform distribution over ``[0, 1)``. + + Parameters + ---------- + \\*args : Arguments + Shape of the output. + If given as N integers, each integer specifies the size of one + dimension. + If given as a tuple, this tuple gives the complete shape. + + Returns + ------- + out : ndarray + The matrix of random values with shape given by `\\*args`. + + See Also + -------- + randn, numpy.random.RandomState.rand + + Examples + -------- + >>> np.random.seed(123) + >>> import numpy.matlib + >>> np.matlib.rand(2, 3) + matrix([[0.69646919, 0.28613933, 0.22685145], + [0.55131477, 0.71946897, 0.42310646]]) + >>> np.matlib.rand((2, 3)) + matrix([[0.9807642 , 0.68482974, 0.4809319 ], + [0.39211752, 0.34317802, 0.72904971]]) + + If the first argument is a tuple, other arguments are ignored: + + >>> np.matlib.rand((2, 3), 4) + matrix([[0.43857224, 0.0596779 , 0.39804426], + [0.73799541, 0.18249173, 0.17545176]]) + + """ + if isinstance(args[0], tuple): + args = args[0] + return asmatrix(np.random.rand(*args)) + +def randn(*args): + """ + Return a random matrix with data from the "standard normal" distribution. + + `randn` generates a matrix filled with random floats sampled from a + univariate "normal" (Gaussian) distribution of mean 0 and variance 1. + + Parameters + ---------- + \\*args : Arguments + Shape of the output. + If given as N integers, each integer specifies the size of one + dimension. If given as a tuple, this tuple gives the complete shape. + + Returns + ------- + Z : matrix of floats + A matrix of floating-point samples drawn from the standard normal + distribution. + + See Also + -------- + rand, numpy.random.RandomState.randn + + Notes + ----- + For random samples from the normal distribution with mean ``mu`` and + standard deviation ``sigma``, use:: + + sigma * np.matlib.randn(...) + mu + + Examples + -------- + >>> np.random.seed(123) + >>> import numpy.matlib + >>> np.matlib.randn(1) + matrix([[-1.0856306]]) + >>> np.matlib.randn(1, 2, 3) + matrix([[ 0.99734545, 0.2829785 , -1.50629471], + [-0.57860025, 1.65143654, -2.42667924]]) + + Two-by-four matrix of samples from the normal distribution with + mean 3 and standard deviation 2.5: + + >>> 2.5 * np.matlib.randn((2, 4)) + 3 + matrix([[1.92771843, 6.16484065, 0.83314899, 1.30278462], + [2.76322758, 6.72847407, 1.40274501, 1.8900451 ]]) + + """ + if isinstance(args[0], tuple): + args = args[0] + return asmatrix(np.random.randn(*args)) + +def repmat(a, m, n): + """ + Repeat a 0-D to 2-D array or matrix MxN times. + + Parameters + ---------- + a : array_like + The array or matrix to be repeated. + m, n : int + The number of times `a` is repeated along the first and second axes. + + Returns + ------- + out : ndarray + The result of repeating `a`. + + Examples + -------- + >>> import numpy.matlib + >>> a0 = np.array(1) + >>> np.matlib.repmat(a0, 2, 3) + array([[1, 1, 1], + [1, 1, 1]]) + + >>> a1 = np.arange(4) + >>> np.matlib.repmat(a1, 2, 2) + array([[0, 1, 2, 3, 0, 1, 2, 3], + [0, 1, 2, 3, 0, 1, 2, 3]]) + + >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3)) + >>> np.matlib.repmat(a2, 2, 3) + matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5, 3, 4, 5], + [0, 1, 2, 0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5, 3, 4, 5]]) + + """ + a = asanyarray(a) + ndim = a.ndim + if ndim == 0: + origrows, origcols = (1, 1) + elif ndim == 1: + origrows, origcols = (1, a.shape[0]) + else: + origrows, origcols = a.shape + rows = origrows * m + cols = origcols * n + c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0) + return c.reshape(rows, cols) diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/matlib.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/matlib.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f73e941729bf8b0e5eb79a28683e326f18cc89f2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/matlib.pyi @@ -0,0 +1,582 @@ +from typing import Any, Literal, TypeAlias, TypeVar, overload + +import numpy as np +import numpy.typing as npt +from numpy import ( # noqa: F401 + False_, + ScalarType, + True_, + __array_namespace_info__, + __version__, + abs, + absolute, + acos, + acosh, + add, + all, + allclose, + amax, + amin, + angle, + any, + append, + apply_along_axis, + apply_over_axes, + arange, + arccos, + arccosh, + arcsin, + arcsinh, + arctan, + arctan2, + arctanh, + argmax, + argmin, + argpartition, + argsort, + argwhere, + around, + array, + array2string, + array_equal, + array_equiv, + array_repr, + array_split, + array_str, + asanyarray, + asarray, + asarray_chkfinite, + ascontiguousarray, + asfortranarray, + asin, + asinh, + asmatrix, + astype, + atan, + atan2, + atanh, + atleast_1d, + atleast_2d, + atleast_3d, + average, + bartlett, + base_repr, + binary_repr, + bincount, + bitwise_and, + bitwise_count, + bitwise_invert, + bitwise_left_shift, + bitwise_not, + bitwise_or, + bitwise_right_shift, + bitwise_xor, + blackman, + block, + bmat, + bool, + bool_, + broadcast, + broadcast_arrays, + broadcast_shapes, + broadcast_to, + busday_count, + busday_offset, + busdaycalendar, + byte, + bytes_, + c_, + can_cast, + cbrt, + cdouble, + ceil, + char, + character, + choose, + clip, + clongdouble, + column_stack, + common_type, + complex64, + complex128, + complex192, + complex256, + complexfloating, + compress, + concat, + concatenate, + conj, + conjugate, + convolve, + copy, + copysign, + copyto, + core, + corrcoef, + correlate, + cos, + cosh, + count_nonzero, + cov, + cross, + csingle, + ctypeslib, + cumprod, + cumsum, + cumulative_prod, + cumulative_sum, + datetime64, + datetime_as_string, + datetime_data, + deg2rad, + degrees, + delete, + diag, + diag_indices, + diag_indices_from, + diagflat, + diagonal, + diff, + digitize, + divide, + divmod, + dot, + double, + dsplit, + dstack, + dtype, + dtypes, + e, + ediff1d, + einsum, + einsum_path, + emath, + empty_like, + equal, + errstate, + euler_gamma, + exceptions, + exp, + exp2, + expand_dims, + expm1, + extract, + f2py, + fabs, + fft, + fill_diagonal, + finfo, + fix, + flatiter, + flatnonzero, + flexible, + flip, + fliplr, + flipud, + float16, + float32, + float64, + float96, + float128, + float_power, + floating, + floor, + floor_divide, + fmax, + fmin, + fmod, + format_float_positional, + format_float_scientific, + frexp, + from_dlpack, + frombuffer, + fromfile, + fromfunction, + fromiter, + frompyfunc, + fromregex, + fromstring, + full, + full_like, + gcd, + generic, + genfromtxt, + geomspace, + get_include, + get_printoptions, + getbufsize, + geterr, + geterrcall, + gradient, + greater, + greater_equal, + half, + hamming, + hanning, + heaviside, + histogram, + histogram2d, + histogram_bin_edges, + histogramdd, + hsplit, + hstack, + hypot, + i0, + iinfo, + imag, + index_exp, + indices, + inexact, + inf, + info, + inner, + insert, + int8, + int16, + int32, + int64, + int_, + intc, + integer, + interp, + intersect1d, + intp, + invert, + is_busday, + isclose, + iscomplex, + iscomplexobj, + isdtype, + isfinite, + isfortran, + isin, + isinf, + isnan, + isnat, + isneginf, + isposinf, + isreal, + isrealobj, + isscalar, + issubdtype, + iterable, + ix_, + kaiser, + kron, + lcm, + ldexp, + left_shift, + less, + less_equal, + lexsort, + lib, + linalg, + linspace, + little_endian, + load, + loadtxt, + log, + log1p, + log2, + log10, + logaddexp, + logaddexp2, + logical_and, + logical_not, + logical_or, + logical_xor, + logspace, + long, + longdouble, + longlong, + ma, + mask_indices, + matmul, + matrix, + matrix_transpose, + matvec, + max, + maximum, + may_share_memory, + mean, + median, + memmap, + meshgrid, + mgrid, + min, + min_scalar_type, + minimum, + mintypecode, + mod, + modf, + moveaxis, + multiply, + nan, + nan_to_num, + nanargmax, + nanargmin, + nancumprod, + nancumsum, + nanmax, + nanmean, + nanmedian, + nanmin, + nanpercentile, + nanprod, + nanquantile, + nanstd, + nansum, + nanvar, + ndarray, + ndenumerate, + ndim, + ndindex, + nditer, + negative, + nested_iters, + newaxis, + nextafter, + nonzero, + not_equal, + number, + object_, + ogrid, + ones_like, + outer, + packbits, + pad, + partition, + percentile, + permute_dims, + pi, + piecewise, + place, + poly, + poly1d, + polyadd, + polyder, + polydiv, + polyfit, + polyint, + polymul, + polynomial, + polysub, + polyval, + positive, + pow, + power, + printoptions, + prod, + promote_types, + ptp, + put, + put_along_axis, + putmask, + quantile, + r_, + rad2deg, + radians, + random, + ravel, + ravel_multi_index, + real, + real_if_close, + rec, + recarray, + reciprocal, + record, + remainder, + repeat, + require, + reshape, + resize, + result_type, + right_shift, + rint, + roll, + rollaxis, + roots, + rot90, + round, + row_stack, + s_, + save, + savetxt, + savez, + savez_compressed, + sctypeDict, + searchsorted, + select, + set_printoptions, + setbufsize, + setdiff1d, + seterr, + seterrcall, + setxor1d, + shape, + shares_memory, + short, + show_config, + show_runtime, + sign, + signbit, + signedinteger, + sin, + sinc, + single, + sinh, + size, + sort, + sort_complex, + spacing, + split, + sqrt, + square, + squeeze, + stack, + std, + str_, + strings, + subtract, + sum, + swapaxes, + take, + take_along_axis, + tan, + tanh, + tensordot, + test, + testing, + tile, + timedelta64, + trace, + transpose, + trapezoid, + tri, + tril, + tril_indices, + tril_indices_from, + trim_zeros, + triu, + triu_indices, + triu_indices_from, + true_divide, + trunc, + typecodes, + typename, + typing, + ubyte, + ufunc, + uint, + uint8, + uint16, + uint32, + uint64, + uintc, + uintp, + ulong, + ulonglong, + union1d, + unique, + unique_all, + unique_counts, + unique_inverse, + unique_values, + unpackbits, + unravel_index, + unsignedinteger, + unstack, + unwrap, + ushort, + vander, + var, + vdot, + vecdot, + vecmat, + vectorize, + void, + vsplit, + vstack, + where, + zeros_like, +) +from numpy._typing import _ArrayLike, _DTypeLike + +__all__ = ["rand", "randn", "repmat"] +__all__ += np.__all__ + +### + +_ScalarT = TypeVar("_ScalarT", bound=np.generic) +_Matrix: TypeAlias = np.matrix[tuple[int, int], np.dtype[_ScalarT]] +_Order: TypeAlias = Literal["C", "F"] + +### + +# +@overload +def empty(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ... +@overload +def empty(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def empty(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ... + +# +@overload +def ones(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ... +@overload +def ones(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def ones(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ... + +# +@overload +def zeros(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ... +@overload +def zeros(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def zeros(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ... + +# +@overload +def identity(n: int, dtype: None = None) -> _Matrix[np.float64]: ... +@overload +def identity(n: int, dtype: _DTypeLike[_ScalarT]) -> _Matrix[_ScalarT]: ... +@overload +def identity(n: int, dtype: npt.DTypeLike | None = None) -> _Matrix[Any]: ... + +# +@overload +def eye( + n: int, + M: int | None = None, + k: int = 0, + dtype: type[np.float64] | None = ..., + order: _Order = "C", +) -> _Matrix[np.float64]: ... +@overload +def eye(n: int, M: int | None, k: int, dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def eye(n: int, M: int | None = None, k: int = 0, *, dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ... +@overload +def eye(n: int, M: int | None = None, k: int = 0, dtype: npt.DTypeLike | None = ..., order: _Order = "C") -> _Matrix[Any]: ... + +# +@overload +def rand(arg: int | tuple[()] | tuple[int] | tuple[int, int], /) -> _Matrix[np.float64]: ... +@overload +def rand(arg: int, /, *args: int) -> _Matrix[np.float64]: ... + +# +@overload +def randn(arg: int | tuple[()] | tuple[int] | tuple[int, int], /) -> _Matrix[np.float64]: ... +@overload +def randn(arg: int, /, *args: int) -> _Matrix[np.float64]: ... + +# +@overload +def repmat(a: _Matrix[_ScalarT], m: int, n: int) -> _Matrix[_ScalarT]: ... +@overload +def repmat(a: _ArrayLike[_ScalarT], m: int, n: int) -> npt.NDArray[_ScalarT]: ... +@overload +def repmat(a: npt.ArrayLike, m: int, n: int) -> npt.NDArray[Any]: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/py.typed b/data/miniconda3/lib/python3.13/site-packages/numpy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/version.py b/data/miniconda3/lib/python3.13/site-packages/numpy/version.py new file mode 100644 index 0000000000000000000000000000000000000000..b901f6bf99d93c6b76fb05cc3236f8d97a8167fd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/version.py @@ -0,0 +1,11 @@ + +""" +Module to expose more detailed version info for the installed `numpy` +""" +version = "2.4.3" +__version__ = version +full_version = version + +git_revision = "8bcb2e72e67c343e55165e6064fe6a9dc011e954" +release = 'dev' not in version and '+' not in version +short_version = version.split("+")[0] diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy/version.pyi b/data/miniconda3/lib/python3.13/site-packages/numpy/version.pyi new file mode 100644 index 0000000000000000000000000000000000000000..073885c017c2a9c34e41431d0d9361de4b59ff90 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy/version.pyi @@ -0,0 +1,9 @@ +from typing import Final, LiteralString + +version: Final[LiteralString] = ... +__version__: Final[LiteralString] = ... +full_version: Final[LiteralString] = ... + +git_revision: Final[LiteralString] = ... +release: Final[bool] = ... +short_version: Final[LiteralString] = ... diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/LICENSE b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d16a112ca134627fb88dbc6ebe911c333d19d3b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Rick van Hattem All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..438e0225ca893faecf0b16e6c4b43cda02bce550 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/METADATA @@ -0,0 +1,532 @@ +Metadata-Version: 2.1 +Name: numpy-stl +Version: 3.2.0 +Summary: Library to make reading, writing and modifying both binary and ascii STL files easy. +Home-page: https://github.com/WoLpH/numpy-stl/ +Author: Rick van Hattem +Author-email: Wolph@Wol.ph +License: BSD +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Natural Language :: English +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >3.9.0 +License-File: LICENSE +Requires-Dist: numpy +Requires-Dist: python-utils>=3.4.5 +Provides-Extra: docs +Requires-Dist: mock; extra == "docs" +Requires-Dist: sphinx; extra == "docs" +Requires-Dist: python-utils; extra == "docs" +Provides-Extra: tests +Requires-Dist: cov-core; extra == "tests" +Requires-Dist: coverage; extra == "tests" +Requires-Dist: docutils; extra == "tests" +Requires-Dist: execnet; extra == "tests" +Requires-Dist: numpy; extra == "tests" +Requires-Dist: cython; extra == "tests" +Requires-Dist: pep8; extra == "tests" +Requires-Dist: py; extra == "tests" +Requires-Dist: pyflakes; extra == "tests" +Requires-Dist: pytest; extra == "tests" +Requires-Dist: pytest-cache; extra == "tests" +Requires-Dist: pytest-cov; extra == "tests" +Requires-Dist: python-utils; extra == "tests" +Requires-Dist: Sphinx; extra == "tests" +Requires-Dist: flake8; extra == "tests" +Requires-Dist: wheel; extra == "tests" + +numpy-stl +============================================================================== + +.. image:: https://github.com/WoLpH/numpy-stl/actions/workflows/main.yml/badge.svg?branch=master + :alt: numpy-stl test status + :target: https://github.com/WoLpH/numpy-stl/actions/workflows/main.yml + +.. image:: https://ci.appveyor.com/api/projects/status/cbv7ak2i59wf3lpj?svg=true + :alt: numpy-stl test status + :target: https://ci.appveyor.com/project/WoLpH/numpy-stl + +.. image:: https://badge.fury.io/py/numpy-stl.svg + :alt: numpy-stl Pypi version + :target: https://pypi.python.org/pypi/numpy-stl + +.. image:: https://coveralls.io/repos/WoLpH/numpy-stl/badge.svg?branch=master + :alt: numpy-stl code coverage + :target: https://coveralls.io/r/WoLpH/numpy-stl?branch=master + +.. image:: https://img.shields.io/pypi/pyversions/numpy-stl.svg + +Simple library to make working with STL files (and 3D objects in general) fast +and easy. + +Due to all operations heavily relying on `numpy` this is one of the fastest +STL editing libraries for Python available. + +Security contact information +------------------------------------------------------------------------------ + +To report a security vulnerability, please use the +`Tidelift security contact `_. +Tidelift will coordinate the fix and disclosure. + +Issues +------ + +If you encounter any issues, make sure you report them `here `_. Be sure to search for existing issues however. Many issues have been covered before. +While this project uses `numpy` as it's main dependency, it is not in any way affiliated to the `numpy` project or the NumFocus organisation. + +Links +----- + + - The source: https://github.com/WoLpH/numpy-stl + - Project page: https://pypi.python.org/pypi/numpy-stl + - Reporting bugs: https://github.com/WoLpH/numpy-stl/issues + - Documentation: http://numpy-stl.readthedocs.org/en/latest/ + - My blog: https://wol.ph/ + +Requirements for installing: +------------------------------------------------------------------------------ + + - `numpy`_ any recent version + - `python-utils`_ version 1.6 or greater + +Installation: +------------------------------------------------------------------------------ + +`pip install numpy-stl` + +Initial usage: +------------------------------------------------------------------------------ + +After installing the package, you should be able to run the following commands +similar to how you can run `pip`. + +.. code-block:: shell + + $ stl2bin your_ascii_stl_file.stl new_binary_stl_file.stl + $ stl2ascii your_binary_stl_file.stl new_ascii_stl_file.stl + $ stl your_ascii_stl_file.stl new_binary_stl_file.stl + +Contributing: +------------------------------------------------------------------------------ + +Contributions are always welcome. Please view the guidelines to get started: +https://github.com/WoLpH/numpy-stl/blob/develop/CONTRIBUTING.rst + +Quickstart +------------------------------------------------------------------------------ + +.. code-block:: python + + import numpy + from stl import mesh + + # Using an existing stl file: + your_mesh = mesh.Mesh.from_file('some_file.stl') + + # Or creating a new mesh (make sure not to overwrite the `mesh` import by + # naming it `mesh`): + VERTICE_COUNT = 100 + data = numpy.zeros(VERTICE_COUNT, dtype=mesh.Mesh.dtype) + your_mesh = mesh.Mesh(data, remove_empty_areas=False) + + # The mesh normals (calculated automatically) + your_mesh.normals + # The mesh vectors + your_mesh.v0, your_mesh.v1, your_mesh.v2 + # Accessing individual points (concatenation of v0, v1 and v2 in triplets) + assert (your_mesh.points[0][0:3] == your_mesh.v0[0]).all() + assert (your_mesh.points[0][3:6] == your_mesh.v1[0]).all() + assert (your_mesh.points[0][6:9] == your_mesh.v2[0]).all() + assert (your_mesh.points[1][0:3] == your_mesh.v0[1]).all() + + your_mesh.save('new_stl_file.stl') + +Plotting using `matplotlib`_ is equally easy: +------------------------------------------------------------------------------ + +.. code-block:: python + + from stl import mesh + from mpl_toolkits import mplot3d + from matplotlib import pyplot + + # Create a new plot + figure = pyplot.figure() + axes = figure.add_subplot(projection='3d') + + # Load the STL files and add the vectors to the plot + your_mesh = mesh.Mesh.from_file('tests/stl_binary/HalfDonut.stl') + axes.add_collection3d(mplot3d.art3d.Poly3DCollection(your_mesh.vectors)) + + # Auto scale to the mesh size + scale = your_mesh.points.flatten() + axes.auto_scale_xyz(scale, scale, scale) + + # Show the plot to the screen + pyplot.show() + +.. _numpy: http://numpy.org/ +.. _matplotlib: http://matplotlib.org/ +.. _python-utils: https://github.com/WoLpH/python-utils + +Experimental support for reading 3MF files +------------------------------------------------------------------------------ + +.. code-block:: python + + import pathlib + import stl + + path = pathlib.Path('tests/3mf/Moon.3mf') + + # Load the 3MF file + for m in stl.Mesh.from_3mf_file(path): + # Do something with the mesh + print('mesh', m) + +Note that this is still experimental and may not work for all 3MF files. +Additionally it only allows reading 3mf files, not writing them. + +Modifying Mesh objects +------------------------------------------------------------------------------ + +.. code-block:: python + + from stl import mesh + import math + import numpy + + # Create 3 faces of a cube + data = numpy.zeros(6, dtype=mesh.Mesh.dtype) + + # Top of the cube + data['vectors'][0] = numpy.array([[0, 1, 1], + [1, 0, 1], + [0, 0, 1]]) + data['vectors'][1] = numpy.array([[1, 0, 1], + [0, 1, 1], + [1, 1, 1]]) + # Front face + data['vectors'][2] = numpy.array([[1, 0, 0], + [1, 0, 1], + [1, 1, 0]]) + data['vectors'][3] = numpy.array([[1, 1, 1], + [1, 0, 1], + [1, 1, 0]]) + # Left face + data['vectors'][4] = numpy.array([[0, 0, 0], + [1, 0, 0], + [1, 0, 1]]) + data['vectors'][5] = numpy.array([[0, 0, 0], + [0, 0, 1], + [1, 0, 1]]) + + # Since the cube faces are from 0 to 1 we can move it to the middle by + # substracting .5 + data['vectors'] -= .5 + + # Generate 4 different meshes so we can rotate them later + meshes = [mesh.Mesh(data.copy()) for _ in range(4)] + + # Rotate 90 degrees over the Y axis + meshes[0].rotate([0.0, 0.5, 0.0], math.radians(90)) + + # Translate 2 points over the X axis + meshes[1].x += 2 + + # Rotate 90 degrees over the X axis + meshes[2].rotate([0.5, 0.0, 0.0], math.radians(90)) + # Translate 2 points over the X and Y points + meshes[2].x += 2 + meshes[2].y += 2 + + # Rotate 90 degrees over the X and Y axis + meshes[3].rotate([0.5, 0.0, 0.0], math.radians(90)) + meshes[3].rotate([0.0, 0.5, 0.0], math.radians(90)) + # Translate 2 points over the Y axis + meshes[3].y += 2 + + + # Optionally render the rotated cube faces + from matplotlib import pyplot + from mpl_toolkits import mplot3d + + # Create a new plot + figure = pyplot.figure() + axes = figure.add_subplot(projection='3d') + + # Render the cube faces + for m in meshes: + axes.add_collection3d(mplot3d.art3d.Poly3DCollection(m.vectors)) + + # Auto scale to the mesh size + scale = numpy.concatenate([m.points for m in meshes]).flatten() + axes.auto_scale_xyz(scale, scale, scale) + + # Show the plot to the screen + pyplot.show() + +Extending Mesh objects +------------------------------------------------------------------------------ + +.. code-block:: python + + from stl import mesh + import math + import numpy + + # Create 3 faces of a cube + data = numpy.zeros(6, dtype=mesh.Mesh.dtype) + + # Top of the cube + data['vectors'][0] = numpy.array([[0, 1, 1], + [1, 0, 1], + [0, 0, 1]]) + data['vectors'][1] = numpy.array([[1, 0, 1], + [0, 1, 1], + [1, 1, 1]]) + # Front face + data['vectors'][2] = numpy.array([[1, 0, 0], + [1, 0, 1], + [1, 1, 0]]) + data['vectors'][3] = numpy.array([[1, 1, 1], + [1, 0, 1], + [1, 1, 0]]) + # Left face + data['vectors'][4] = numpy.array([[0, 0, 0], + [1, 0, 0], + [1, 0, 1]]) + data['vectors'][5] = numpy.array([[0, 0, 0], + [0, 0, 1], + [1, 0, 1]]) + + # Since the cube faces are from 0 to 1 we can move it to the middle by + # substracting .5 + data['vectors'] -= .5 + + cube_back = mesh.Mesh(data.copy()) + cube_front = mesh.Mesh(data.copy()) + + # Rotate 90 degrees over the X axis followed by the Y axis followed by the + # X axis + cube_back.rotate([0.5, 0.0, 0.0], math.radians(90)) + cube_back.rotate([0.0, 0.5, 0.0], math.radians(90)) + cube_back.rotate([0.5, 0.0, 0.0], math.radians(90)) + + cube = mesh.Mesh(numpy.concatenate([ + cube_back.data.copy(), + cube_front.data.copy(), + ])) + + # Optionally render the rotated cube faces + from matplotlib import pyplot + from mpl_toolkits import mplot3d + + # Create a new plot + figure = pyplot.figure() + axes = figure.add_subplot(projection='3d') + + # Render the cube + axes.add_collection3d(mplot3d.art3d.Poly3DCollection(cube.vectors)) + + # Auto scale to the mesh size + scale = cube_back.points.flatten() + axes.auto_scale_xyz(scale, scale, scale) + + # Show the plot to the screen + pyplot.show() + +Creating a single triangle +---------------------------------- + +.. code-block:: python + + import numpy + from stl import mesh + + # A unit triangle + tri_vectors = [[0,0,0],[0,1,0],[0,0,1]] + + # Create the vector data. It’s a numpy structured array with N entries, where N is the number of triangles (here N=1), and each entry is in the format ('normals','vectors','attr') + data = numpy.array([( + 0, # Set 'normals' to zero, and the mesh class will automatically calculate them at initialization + tri_vectors, # 'vectors' + 0 # 'attr' + )], dtype = mesh.Mesh.dtype) # The structure defined by the mesh class (N x ('normals','vectors','attr')) + + # Create the mesh object from the structured array + tri_mesh = mesh.Mesh(data) + + # Optionally make a plot for fun + # Load the plot tools + from matplotlib import pyplot + from mpl_toolkits import mplot3d + + # Create a new plot + figure = pyplot.figure() + axes = figure.add_subplot(projection='3d') + + # Add mesh to plot + axes.add_collection3d(mplot3d.art3d.Poly3DCollection(tri_mesh.vectors)) # Just need the 'vectors' attribute for display + +Creating Mesh objects from a list of vertices and faces +------------------------------------------------------------------------------ + +.. code-block:: python + + import numpy as np + from stl import mesh + + # Define the 8 vertices of the cube + vertices = np.array([\ + [-1, -1, -1], + [+1, -1, -1], + [+1, +1, -1], + [-1, +1, -1], + [-1, -1, +1], + [+1, -1, +1], + [+1, +1, +1], + [-1, +1, +1]]) + # Define the 12 triangles composing the cube + faces = np.array([\ + [0,3,1], + [1,3,2], + [0,4,7], + [0,7,3], + [4,5,6], + [4,6,7], + [5,1,2], + [5,2,6], + [2,3,6], + [3,7,6], + [0,1,5], + [0,5,4]]) + + # Create the mesh + cube = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype)) + for i, f in enumerate(faces): + for j in range(3): + cube.vectors[i][j] = vertices[f[j],:] + + # Write the mesh to file "cube.stl" + cube.save('cube.stl') + + +Evaluating Mesh properties (Volume, Center of gravity, Inertia) +------------------------------------------------------------------------------ + +.. code-block:: python + + import numpy as np + from stl import mesh + + # Using an existing closed stl file: + your_mesh = mesh.Mesh.from_file('some_file.stl') + + volume, cog, inertia = your_mesh.get_mass_properties() + print("Volume = {0}".format(volume)) + print("Position of the center of gravity (COG) = {0}".format(cog)) + print("Inertia matrix at expressed at the COG = {0}".format(inertia[0,:])) + print(" {0}".format(inertia[1,:])) + print(" {0}".format(inertia[2,:])) + +Combining multiple STL files +------------------------------------------------------------------------------ + +.. code-block:: python + + import math + import stl + from stl import mesh + import numpy + + + # find the max dimensions, so we can know the bounding box, getting the height, + # width, length (because these are the step size)... + def find_mins_maxs(obj): + minx = obj.x.min() + maxx = obj.x.max() + miny = obj.y.min() + maxy = obj.y.max() + minz = obj.z.min() + maxz = obj.z.max() + return minx, maxx, miny, maxy, minz, maxz + + + def translate(_solid, step, padding, multiplier, axis): + if 'x' == axis: + items = 0, 3, 6 + elif 'y' == axis: + items = 1, 4, 7 + elif 'z' == axis: + items = 2, 5, 8 + else: + raise RuntimeError('Unknown axis %r, expected x, y or z' % axis) + + # _solid.points.shape == [:, ((x, y, z), (x, y, z), (x, y, z))] + _solid.points[:, items] += (step * multiplier) + (padding * multiplier) + + + def copy_obj(obj, dims, num_rows, num_cols, num_layers): + w, l, h = dims + copies = [] + for layer in range(num_layers): + for row in range(num_rows): + for col in range(num_cols): + # skip the position where original being copied is + if row == 0 and col == 0 and layer == 0: + continue + _copy = mesh.Mesh(obj.data.copy()) + # pad the space between objects by 10% of the dimension being + # translated + if col != 0: + translate(_copy, w, w / 10., col, 'x') + if row != 0: + translate(_copy, l, l / 10., row, 'y') + if layer != 0: + translate(_copy, h, h / 10., layer, 'z') + copies.append(_copy) + return copies + + # Using an existing stl file: + main_body = mesh.Mesh.from_file('ball_and_socket_simplified_-_main_body.stl') + + # rotate along Y + main_body.rotate([0.0, 0.5, 0.0], math.radians(90)) + + minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(main_body) + w1 = maxx - minx + l1 = maxy - miny + h1 = maxz - minz + copies = copy_obj(main_body, (w1, l1, h1), 2, 2, 1) + + # I wanted to add another related STL to the final STL + twist_lock = mesh.Mesh.from_file('ball_and_socket_simplified_-_twist_lock.stl') + minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(twist_lock) + w2 = maxx - minx + l2 = maxy - miny + h2 = maxz - minz + translate(twist_lock, w1, w1 / 10., 3, 'x') + copies2 = copy_obj(twist_lock, (w2, l2, h2), 2, 2, 1) + combined = mesh.Mesh(numpy.concatenate([main_body.data, twist_lock.data] + + [copy.data for copy in copies] + + [copy.data for copy in copies2])) + + combined.save('combined.stl', mode=stl.Mode.ASCII) # save as ASCII + +Known limitations +------------------------------------------------------------------------------ + + - When speedups are enabled the STL name is automatically converted to + lowercase. diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..63f683ebfe5f7222aed52bc2e40b6c1eaf5960b6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/RECORD @@ -0,0 +1,26 @@ +../../../bin/stl,sha256=Vj5FEZ_wkMlCeuNjPxWUqeHeT5GIcA7YtpAAUSIkOgo,204 +../../../bin/stl2ascii,sha256=EjGxN_fji1OxMmiUhmcRSpH3nHRN9Daxs04Lf2blDNQ,212 +../../../bin/stl2bin,sha256=Snj9U7OD3Vk-nWCzmIr4bBwbsFWbgA-xL7Wj06H5p4k,214 +numpy_stl-3.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +numpy_stl-3.2.0.dist-info/LICENSE,sha256=Xv_4h5nRgKdXtNtFKNEpKSLc0MJ2Z8iFRg-fDkX4j4w,1509 +numpy_stl-3.2.0.dist-info/METADATA,sha256=ngG09uw8uVg1fGtzBAm-vmbD26kAeMV9E4-IO22tnn0,18068 +numpy_stl-3.2.0.dist-info/RECORD,, +numpy_stl-3.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +numpy_stl-3.2.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91 +numpy_stl-3.2.0.dist-info/entry_points.txt,sha256=vMxevnKpKFT087Vw3CO9RhMnkKb81QH5J1Pl77rnlOk,97 +numpy_stl-3.2.0.dist-info/top_level.txt,sha256=uhNU6NfJF-H1ykSlU9oT3dAfUibkYXjmXGGxjMCe2ls,4 +stl/__about__.py,sha256=lAh1a45i1QIVWjzDT-UXFuvHGHkiunxBfKtO0hn3Djw,325 +stl/__init__.py,sha256=mRb0-wba1gZzv1p9uRfck8mT057ov1eovyBRGsMXGp0,293 +stl/__pycache__/__about__.cpython-313.pyc,, +stl/__pycache__/__init__.cpython-313.pyc,, +stl/__pycache__/base.cpython-313.pyc,, +stl/__pycache__/main.cpython-313.pyc,, +stl/__pycache__/mesh.cpython-313.pyc,, +stl/__pycache__/stl.cpython-313.pyc,, +stl/__pycache__/utils.cpython-313.pyc,, +stl/base.py,sha256=VakqraI0xOQVylouzQpn1zBS-9ztq9MQsUqec2otz9w,24089 +stl/main.py,sha256=gJEctn9sq2I6uZJZXAoQgJrb1rL5iWjb4zzvCbJIw7g,3551 +stl/mesh.py,sha256=xE6crruKZbZu0-HtAZ_KuZgPvcu9pbGRbb3TEsHhPvo,54 +stl/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +stl/stl.py,sha256=qnlWQk4YHB9xxh_o6iCzPj3iMRBxmWh9qnajGCcEQMc,18702 +stl/utils.py,sha256=3HI_Wgl415ZxNvXkR294_FBLyQ01cUY86RV_3gz94Cc,202 diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae527e7d64811439e61b93aa375defb30e06edfe --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..cda44352cd0a6791b20609c6efc7dbdc79195d3f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/entry_points.txt @@ -0,0 +1,4 @@ +[console_scripts] +stl = stl.main:main +stl2ascii = stl.main:to_ascii +stl2bin = stl.main:to_binary diff --git a/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8125967a3b7c806a010767dd88a088906e00008d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/numpy_stl-3.2.0.dist-info/top_level.txt @@ -0,0 +1 @@ +stl diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/__init__.py b/data/miniconda3/lib/python3.13/site-packages/packaging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d45c22cfd88e2b88976b46d4171a502b602658ec --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/__init__.py @@ -0,0 +1,15 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +__title__ = "packaging" +__summary__ = "Core utilities for Python packages" +__uri__ = "https://github.com/pypa/packaging" + +__version__ = "25.0" + +__author__ = "Donald Stufft and individual contributors" +__email__ = "donald@stufft.io" + +__license__ = "BSD-2-Clause or Apache-2.0" +__copyright__ = f"2014 {__author__}" diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/_elffile.py b/data/miniconda3/lib/python3.13/site-packages/packaging/_elffile.py new file mode 100644 index 0000000000000000000000000000000000000000..7a5afc33b0a2401cf509bb6a8d1143d5230324d9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/_elffile.py @@ -0,0 +1,109 @@ +""" +ELF file parser. + +This provides a class ``ELFFile`` that parses an ELF executable in a similar +interface to ``ZipFile``. Only the read interface is implemented. + +Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca +ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html +""" + +from __future__ import annotations + +import enum +import os +import struct +from typing import IO + + +class ELFInvalid(ValueError): + pass + + +class EIClass(enum.IntEnum): + C32 = 1 + C64 = 2 + + +class EIData(enum.IntEnum): + Lsb = 1 + Msb = 2 + + +class EMachine(enum.IntEnum): + I386 = 3 + S390 = 22 + Arm = 40 + X8664 = 62 + AArc64 = 183 + + +class ELFFile: + """ + Representation of an ELF executable. + """ + + def __init__(self, f: IO[bytes]) -> None: + self._f = f + + try: + ident = self._read("16B") + except struct.error as e: + raise ELFInvalid("unable to parse identification") from e + magic = bytes(ident[:4]) + if magic != b"\x7fELF": + raise ELFInvalid(f"invalid magic: {magic!r}") + + self.capacity = ident[4] # Format for program header (bitness). + self.encoding = ident[5] # Data structure encoding (endianness). + + try: + # e_fmt: Format for program header. + # p_fmt: Format for section header. + # p_idx: Indexes to find p_type, p_offset, and p_filesz. + e_fmt, self._p_fmt, self._p_idx = { + (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. + (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. + }[(self.capacity, self.encoding)] + except KeyError as e: + raise ELFInvalid( + f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})" + ) from e + + try: + ( + _, + self.machine, # Architecture type. + _, + _, + self._e_phoff, # Offset of program header. + _, + self.flags, # Processor-specific flags. + _, + self._e_phentsize, # Size of section. + self._e_phnum, # Number of sections. + ) = self._read(e_fmt) + except struct.error as e: + raise ELFInvalid("unable to parse machine and section information") from e + + def _read(self, fmt: str) -> tuple[int, ...]: + return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) + + @property + def interpreter(self) -> str | None: + """ + The path recorded in the ``PT_INTERP`` section header. + """ + for index in range(self._e_phnum): + self._f.seek(self._e_phoff + self._e_phentsize * index) + try: + data = self._read(self._p_fmt) + except struct.error: + continue + if data[self._p_idx[0]] != 3: # Not PT_INTERP. + continue + self._f.seek(data[self._p_idx[1]]) + return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") + return None diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/_manylinux.py b/data/miniconda3/lib/python3.13/site-packages/packaging/_manylinux.py new file mode 100644 index 0000000000000000000000000000000000000000..95f55762e86f08af76aaa95f5cd147d4517c6d66 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/_manylinux.py @@ -0,0 +1,262 @@ +from __future__ import annotations + +import collections +import contextlib +import functools +import os +import re +import sys +import warnings +from typing import Generator, Iterator, NamedTuple, Sequence + +from ._elffile import EIClass, EIData, ELFFile, EMachine + +EF_ARM_ABIMASK = 0xFF000000 +EF_ARM_ABI_VER5 = 0x05000000 +EF_ARM_ABI_FLOAT_HARD = 0x00000400 + + +# `os.PathLike` not a generic type until Python 3.9, so sticking with `str` +# as the type for `path` until then. +@contextlib.contextmanager +def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]: + try: + with open(path, "rb") as f: + yield ELFFile(f) + except (OSError, TypeError, ValueError): + yield None + + +def _is_linux_armhf(executable: str) -> bool: + # hard-float ABI can be detected from the ELF header of the running + # process + # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.Arm + and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 + and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD + ) + + +def _is_linux_i686(executable: str) -> bool: + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.I386 + ) + + +def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: + if "armv7l" in archs: + return _is_linux_armhf(executable) + if "i686" in archs: + return _is_linux_i686(executable) + allowed_archs = { + "x86_64", + "aarch64", + "ppc64", + "ppc64le", + "s390x", + "loongarch64", + "riscv64", + } + return any(arch in allowed_archs for arch in archs) + + +# If glibc ever changes its major version, we need to know what the last +# minor version was, so we can build the complete list of all versions. +# For now, guess what the highest minor version might be, assume it will +# be 50 for testing. Once this actually happens, update the dictionary +# with the actual value. +_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50) + + +class _GLibCVersion(NamedTuple): + major: int + minor: int + + +def _glibc_version_string_confstr() -> str | None: + """ + Primary implementation of glibc_version_string using os.confstr. + """ + # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely + # to be broken or missing. This strategy is used in the standard library + # platform module. + # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 + try: + # Should be a string like "glibc 2.17". + version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") + assert version_string is not None + _, version = version_string.rsplit() + except (AssertionError, AttributeError, OSError, ValueError): + # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... + return None + return version + + +def _glibc_version_string_ctypes() -> str | None: + """ + Fallback implementation of glibc_version_string using ctypes. + """ + try: + import ctypes + except ImportError: + return None + + # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen + # manpage says, "If filename is NULL, then the returned handle is for the + # main program". This way we can let the linker do the work to figure out + # which libc our process is actually using. + # + # We must also handle the special case where the executable is not a + # dynamically linked executable. This can occur when using musl libc, + # for example. In this situation, dlopen() will error, leading to an + # OSError. Interestingly, at least in the case of musl, there is no + # errno set on the OSError. The single string argument used to construct + # OSError comes from libc itself and is therefore not portable to + # hard code here. In any case, failure to call dlopen() means we + # can proceed, so we bail on our attempt. + try: + process_namespace = ctypes.CDLL(None) + except OSError: + return None + + try: + gnu_get_libc_version = process_namespace.gnu_get_libc_version + except AttributeError: + # Symbol doesn't exist -> therefore, we are not linked to + # glibc. + return None + + # Call gnu_get_libc_version, which returns a string like "2.5" + gnu_get_libc_version.restype = ctypes.c_char_p + version_str: str = gnu_get_libc_version() + # py2 / py3 compatibility: + if not isinstance(version_str, str): + version_str = version_str.decode("ascii") + + return version_str + + +def _glibc_version_string() -> str | None: + """Returns glibc version string, or None if not using glibc.""" + return _glibc_version_string_confstr() or _glibc_version_string_ctypes() + + +def _parse_glibc_version(version_str: str) -> tuple[int, int]: + """Parse glibc version. + + We use a regexp instead of str.split because we want to discard any + random junk that might come after the minor version -- this might happen + in patched/forked versions of glibc (e.g. Linaro's version of glibc + uses version strings like "2.20-2014.11"). See gh-3588. + """ + m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str) + if not m: + warnings.warn( + f"Expected glibc version with 2 components major.minor, got: {version_str}", + RuntimeWarning, + stacklevel=2, + ) + return -1, -1 + return int(m.group("major")), int(m.group("minor")) + + +@functools.lru_cache +def _get_glibc_version() -> tuple[int, int]: + version_str = _glibc_version_string() + if version_str is None: + return (-1, -1) + return _parse_glibc_version(version_str) + + +# From PEP 513, PEP 600 +def _is_compatible(arch: str, version: _GLibCVersion) -> bool: + sys_glibc = _get_glibc_version() + if sys_glibc < version: + return False + # Check for presence of _manylinux module. + try: + import _manylinux + except ImportError: + return True + if hasattr(_manylinux, "manylinux_compatible"): + result = _manylinux.manylinux_compatible(version[0], version[1], arch) + if result is not None: + return bool(result) + return True + if version == _GLibCVersion(2, 5): + if hasattr(_manylinux, "manylinux1_compatible"): + return bool(_manylinux.manylinux1_compatible) + if version == _GLibCVersion(2, 12): + if hasattr(_manylinux, "manylinux2010_compatible"): + return bool(_manylinux.manylinux2010_compatible) + if version == _GLibCVersion(2, 17): + if hasattr(_manylinux, "manylinux2014_compatible"): + return bool(_manylinux.manylinux2014_compatible) + return True + + +_LEGACY_MANYLINUX_MAP = { + # CentOS 7 w/ glibc 2.17 (PEP 599) + (2, 17): "manylinux2014", + # CentOS 6 w/ glibc 2.12 (PEP 571) + (2, 12): "manylinux2010", + # CentOS 5 w/ glibc 2.5 (PEP 513) + (2, 5): "manylinux1", +} + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate manylinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be manylinux-compatible. + + :returns: An iterator of compatible manylinux tags. + """ + if not _have_compatible_abi(sys.executable, archs): + return + # Oldest glibc to be supported regardless of architecture is (2, 17). + too_old_glibc2 = _GLibCVersion(2, 16) + if set(archs) & {"x86_64", "i686"}: + # On x86/i686 also oldest glibc to be supported is (2, 5). + too_old_glibc2 = _GLibCVersion(2, 4) + current_glibc = _GLibCVersion(*_get_glibc_version()) + glibc_max_list = [current_glibc] + # We can assume compatibility across glibc major versions. + # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 + # + # Build a list of maximum glibc versions so that we can + # output the canonical list of all glibc from current_glibc + # down to too_old_glibc2, including all intermediary versions. + for glibc_major in range(current_glibc.major - 1, 1, -1): + glibc_minor = _LAST_GLIBC_MINOR[glibc_major] + glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) + for arch in archs: + for glibc_max in glibc_max_list: + if glibc_max.major == too_old_glibc2.major: + min_minor = too_old_glibc2.minor + else: + # For other glibc major versions oldest supported is (x, 0). + min_minor = -1 + for glibc_minor in range(glibc_max.minor, min_minor, -1): + glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) + tag = "manylinux_{}_{}".format(*glibc_version) + if _is_compatible(arch, glibc_version): + yield f"{tag}_{arch}" + # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. + if glibc_version in _LEGACY_MANYLINUX_MAP: + legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version] + if _is_compatible(arch, glibc_version): + yield f"{legacy_tag}_{arch}" diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/_musllinux.py b/data/miniconda3/lib/python3.13/site-packages/packaging/_musllinux.py new file mode 100644 index 0000000000000000000000000000000000000000..d2bf30b56319ba862c5c9a1a39a87c6d1cb68718 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/_musllinux.py @@ -0,0 +1,85 @@ +"""PEP 656 support. + +This module implements logic to detect if the currently running Python is +linked against musl, and what musl version is used. +""" + +from __future__ import annotations + +import functools +import re +import subprocess +import sys +from typing import Iterator, NamedTuple, Sequence + +from ._elffile import ELFFile + + +class _MuslVersion(NamedTuple): + major: int + minor: int + + +def _parse_musl_version(output: str) -> _MuslVersion | None: + lines = [n for n in (n.strip() for n in output.splitlines()) if n] + if len(lines) < 2 or lines[0][:4] != "musl": + return None + m = re.match(r"Version (\d+)\.(\d+)", lines[1]) + if not m: + return None + return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) + + +@functools.lru_cache +def _get_musl_version(executable: str) -> _MuslVersion | None: + """Detect currently-running musl runtime version. + + This is done by checking the specified executable's dynamic linking + information, and invoking the loader to parse its output for a version + string. If the loader is musl, the output would be something like:: + + musl libc (x86_64) + Version 1.2.2 + Dynamic Program Loader + """ + try: + with open(executable, "rb") as f: + ld = ELFFile(f).interpreter + except (OSError, TypeError, ValueError): + return None + if ld is None or "musl" not in ld: + return None + proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True) + return _parse_musl_version(proc.stderr) + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate musllinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be musllinux-compatible. + + :returns: An iterator of compatible musllinux tags. + """ + sys_musl = _get_musl_version(sys.executable) + if sys_musl is None: # Python not dynamically linked against musl. + return + for arch in archs: + for minor in range(sys_musl.minor, -1, -1): + yield f"musllinux_{sys_musl.major}_{minor}_{arch}" + + +if __name__ == "__main__": # pragma: no cover + import sysconfig + + plat = sysconfig.get_platform() + assert plat.startswith("linux-"), "not linux" + + print("plat:", plat) + print("musl:", _get_musl_version(sys.executable)) + print("tags:", end=" ") + for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])): + print(t, end="\n ") diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/_parser.py b/data/miniconda3/lib/python3.13/site-packages/packaging/_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..0007c0aa64aeae24c7e0ca90790a25ba51dbf7d6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/_parser.py @@ -0,0 +1,353 @@ +"""Handwritten parser of dependency specifiers. + +The docstring for each __parse_* function contains EBNF-inspired grammar representing +the implementation. +""" + +from __future__ import annotations + +import ast +from typing import NamedTuple, Sequence, Tuple, Union + +from ._tokenizer import DEFAULT_RULES, Tokenizer + + +class Node: + def __init__(self, value: str) -> None: + self.value = value + + def __str__(self) -> str: + return self.value + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}('{self}')>" + + def serialize(self) -> str: + raise NotImplementedError + + +class Variable(Node): + def serialize(self) -> str: + return str(self) + + +class Value(Node): + def serialize(self) -> str: + return f'"{self}"' + + +class Op(Node): + def serialize(self) -> str: + return str(self) + + +MarkerVar = Union[Variable, Value] +MarkerItem = Tuple[MarkerVar, Op, MarkerVar] +MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]] +MarkerList = Sequence[Union["MarkerList", MarkerAtom, str]] + + +class ParsedRequirement(NamedTuple): + name: str + url: str + extras: list[str] + specifier: str + marker: MarkerList | None + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for dependency specifier +# -------------------------------------------------------------------------------------- +def parse_requirement(source: str) -> ParsedRequirement: + return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: + """ + requirement = WS? IDENTIFIER WS? extras WS? requirement_details + """ + tokenizer.consume("WS") + + name_token = tokenizer.expect( + "IDENTIFIER", expected="package name at the start of dependency specifier" + ) + name = name_token.text + tokenizer.consume("WS") + + extras = _parse_extras(tokenizer) + tokenizer.consume("WS") + + url, specifier, marker = _parse_requirement_details(tokenizer) + tokenizer.expect("END", expected="end of dependency specifier") + + return ParsedRequirement(name, url, extras, specifier, marker) + + +def _parse_requirement_details( + tokenizer: Tokenizer, +) -> tuple[str, str, MarkerList | None]: + """ + requirement_details = AT URL (WS requirement_marker?)? + | specifier WS? (requirement_marker)? + """ + + specifier = "" + url = "" + marker = None + + if tokenizer.check("AT"): + tokenizer.read() + tokenizer.consume("WS") + + url_start = tokenizer.position + url = tokenizer.expect("URL", expected="URL after @").text + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + tokenizer.expect("WS", expected="whitespace after URL") + + # The input might end after whitespace. + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, span_start=url_start, after="URL and whitespace" + ) + else: + specifier_start = tokenizer.position + specifier = _parse_specifier(tokenizer) + tokenizer.consume("WS") + + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, + span_start=specifier_start, + after=( + "version specifier" + if specifier + else "name and no valid version specifier" + ), + ) + + return (url, specifier, marker) + + +def _parse_requirement_marker( + tokenizer: Tokenizer, *, span_start: int, after: str +) -> MarkerList: + """ + requirement_marker = SEMICOLON marker WS? + """ + + if not tokenizer.check("SEMICOLON"): + tokenizer.raise_syntax_error( + f"Expected end or semicolon (after {after})", + span_start=span_start, + ) + tokenizer.read() + + marker = _parse_marker(tokenizer) + tokenizer.consume("WS") + + return marker + + +def _parse_extras(tokenizer: Tokenizer) -> list[str]: + """ + extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? + """ + if not tokenizer.check("LEFT_BRACKET", peek=True): + return [] + + with tokenizer.enclosing_tokens( + "LEFT_BRACKET", + "RIGHT_BRACKET", + around="extras", + ): + tokenizer.consume("WS") + extras = _parse_extras_list(tokenizer) + tokenizer.consume("WS") + + return extras + + +def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: + """ + extras_list = identifier (wsp* ',' wsp* identifier)* + """ + extras: list[str] = [] + + if not tokenizer.check("IDENTIFIER"): + return extras + + extras.append(tokenizer.read().text) + + while True: + tokenizer.consume("WS") + if tokenizer.check("IDENTIFIER", peek=True): + tokenizer.raise_syntax_error("Expected comma between extra names") + elif not tokenizer.check("COMMA"): + break + + tokenizer.read() + tokenizer.consume("WS") + + extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") + extras.append(extra_token.text) + + return extras + + +def _parse_specifier(tokenizer: Tokenizer) -> str: + """ + specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS + | WS? version_many WS? + """ + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="version specifier", + ): + tokenizer.consume("WS") + parsed_specifiers = _parse_version_many(tokenizer) + tokenizer.consume("WS") + + return parsed_specifiers + + +def _parse_version_many(tokenizer: Tokenizer) -> str: + """ + version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? + """ + parsed_specifiers = "" + while tokenizer.check("SPECIFIER"): + span_start = tokenizer.position + parsed_specifiers += tokenizer.read().text + if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): + tokenizer.raise_syntax_error( + ".* suffix can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position + 1, + ) + if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): + tokenizer.raise_syntax_error( + "Local version label can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position, + ) + tokenizer.consume("WS") + if not tokenizer.check("COMMA"): + break + parsed_specifiers += tokenizer.read().text + tokenizer.consume("WS") + + return parsed_specifiers + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for marker expression +# -------------------------------------------------------------------------------------- +def parse_marker(source: str) -> MarkerList: + return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: + retval = _parse_marker(tokenizer) + tokenizer.expect("END", expected="end of marker expression") + return retval + + +def _parse_marker(tokenizer: Tokenizer) -> MarkerList: + """ + marker = marker_atom (BOOLOP marker_atom)+ + """ + expression = [_parse_marker_atom(tokenizer)] + while tokenizer.check("BOOLOP"): + token = tokenizer.read() + expr_right = _parse_marker_atom(tokenizer) + expression.extend((token.text, expr_right)) + return expression + + +def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: + """ + marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? + | WS? marker_item WS? + """ + + tokenizer.consume("WS") + if tokenizer.check("LEFT_PARENTHESIS", peek=True): + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="marker expression", + ): + tokenizer.consume("WS") + marker: MarkerAtom = _parse_marker(tokenizer) + tokenizer.consume("WS") + else: + marker = _parse_marker_item(tokenizer) + tokenizer.consume("WS") + return marker + + +def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: + """ + marker_item = WS? marker_var WS? marker_op WS? marker_var WS? + """ + tokenizer.consume("WS") + marker_var_left = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + marker_op = _parse_marker_op(tokenizer) + tokenizer.consume("WS") + marker_var_right = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + return (marker_var_left, marker_op, marker_var_right) + + +def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: + """ + marker_var = VARIABLE | QUOTED_STRING + """ + if tokenizer.check("VARIABLE"): + return process_env_var(tokenizer.read().text.replace(".", "_")) + elif tokenizer.check("QUOTED_STRING"): + return process_python_str(tokenizer.read().text) + else: + tokenizer.raise_syntax_error( + message="Expected a marker variable or quoted string" + ) + + +def process_env_var(env_var: str) -> Variable: + if env_var in ("platform_python_implementation", "python_implementation"): + return Variable("platform_python_implementation") + else: + return Variable(env_var) + + +def process_python_str(python_str: str) -> Value: + value = ast.literal_eval(python_str) + return Value(str(value)) + + +def _parse_marker_op(tokenizer: Tokenizer) -> Op: + """ + marker_op = IN | NOT IN | OP + """ + if tokenizer.check("IN"): + tokenizer.read() + return Op("in") + elif tokenizer.check("NOT"): + tokenizer.read() + tokenizer.expect("WS", expected="whitespace after 'not'") + tokenizer.expect("IN", expected="'in' after 'not'") + return Op("not in") + elif tokenizer.check("OP"): + return Op(tokenizer.read().text) + else: + return tokenizer.raise_syntax_error( + "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in" + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/_structures.py b/data/miniconda3/lib/python3.13/site-packages/packaging/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..90a6465f9682c886363eea5327dac64bf623a6ff --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/_structures.py @@ -0,0 +1,61 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + + +class InfinityType: + def __repr__(self) -> str: + return "Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return False + + def __le__(self, other: object) -> bool: + return False + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return True + + def __ge__(self, other: object) -> bool: + return True + + def __neg__(self: object) -> "NegativeInfinityType": + return NegativeInfinity + + +Infinity = InfinityType() + + +class NegativeInfinityType: + def __repr__(self) -> str: + return "-Infinity" + + def __hash__(self) -> int: + return hash(repr(self)) + + def __lt__(self, other: object) -> bool: + return True + + def __le__(self, other: object) -> bool: + return True + + def __eq__(self, other: object) -> bool: + return isinstance(other, self.__class__) + + def __gt__(self, other: object) -> bool: + return False + + def __ge__(self, other: object) -> bool: + return False + + def __neg__(self: object) -> InfinityType: + return Infinity + + +NegativeInfinity = NegativeInfinityType() diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/_tokenizer.py b/data/miniconda3/lib/python3.13/site-packages/packaging/_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..d28a9b6cf5daca9fa3ce5a8c8ae583a57ee84f12 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/_tokenizer.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import contextlib +import re +from dataclasses import dataclass +from typing import Iterator, NoReturn + +from .specifiers import Specifier + + +@dataclass +class Token: + name: str + text: str + position: int + + +class ParserSyntaxError(Exception): + """The provided source text could not be parsed correctly.""" + + def __init__( + self, + message: str, + *, + source: str, + span: tuple[int, int], + ) -> None: + self.span = span + self.message = message + self.source = source + + super().__init__() + + def __str__(self) -> str: + marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" + return "\n ".join([self.message, self.source, marker]) + + +DEFAULT_RULES: dict[str, str | re.Pattern[str]] = { + "LEFT_PARENTHESIS": r"\(", + "RIGHT_PARENTHESIS": r"\)", + "LEFT_BRACKET": r"\[", + "RIGHT_BRACKET": r"\]", + "SEMICOLON": r";", + "COMMA": r",", + "QUOTED_STRING": re.compile( + r""" + ( + ('[^']*') + | + ("[^"]*") + ) + """, + re.VERBOSE, + ), + "OP": r"(===|==|~=|!=|<=|>=|<|>)", + "BOOLOP": r"\b(or|and)\b", + "IN": r"\bin\b", + "NOT": r"\bnot\b", + "VARIABLE": re.compile( + r""" + \b( + python_version + |python_full_version + |os[._]name + |sys[._]platform + |platform_(release|system) + |platform[._](version|machine|python_implementation) + |python_implementation + |implementation_(name|version) + |extras? + |dependency_groups + )\b + """, + re.VERBOSE, + ), + "SPECIFIER": re.compile( + Specifier._operator_regex_str + Specifier._version_regex_str, + re.VERBOSE | re.IGNORECASE, + ), + "AT": r"\@", + "URL": r"[^ \t]+", + "IDENTIFIER": r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b", + "VERSION_PREFIX_TRAIL": r"\.\*", + "VERSION_LOCAL_LABEL_TRAIL": r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*", + "WS": r"[ \t]+", + "END": r"$", +} + + +class Tokenizer: + """Context-sensitive token parsing. + + Provides methods to examine the input stream to check whether the next token + matches. + """ + + def __init__( + self, + source: str, + *, + rules: dict[str, str | re.Pattern[str]], + ) -> None: + self.source = source + self.rules: dict[str, re.Pattern[str]] = { + name: re.compile(pattern) for name, pattern in rules.items() + } + self.next_token: Token | None = None + self.position = 0 + + def consume(self, name: str) -> None: + """Move beyond provided token name, if at current position.""" + if self.check(name): + self.read() + + def check(self, name: str, *, peek: bool = False) -> bool: + """Check whether the next token has the provided name. + + By default, if the check succeeds, the token *must* be read before + another check. If `peek` is set to `True`, the token is not loaded and + would need to be checked again. + """ + assert self.next_token is None, ( + f"Cannot check for {name!r}, already have {self.next_token!r}" + ) + assert name in self.rules, f"Unknown token name: {name!r}" + + expression = self.rules[name] + + match = expression.match(self.source, self.position) + if match is None: + return False + if not peek: + self.next_token = Token(name, match[0], self.position) + return True + + def expect(self, name: str, *, expected: str) -> Token: + """Expect a certain token name next, failing with a syntax error otherwise. + + The token is *not* read. + """ + if not self.check(name): + raise self.raise_syntax_error(f"Expected {expected}") + return self.read() + + def read(self) -> Token: + """Consume the next token and return it.""" + token = self.next_token + assert token is not None + + self.position += len(token.text) + self.next_token = None + + return token + + def raise_syntax_error( + self, + message: str, + *, + span_start: int | None = None, + span_end: int | None = None, + ) -> NoReturn: + """Raise ParserSyntaxError at the given position.""" + span = ( + self.position if span_start is None else span_start, + self.position if span_end is None else span_end, + ) + raise ParserSyntaxError( + message, + source=self.source, + span=span, + ) + + @contextlib.contextmanager + def enclosing_tokens( + self, open_token: str, close_token: str, *, around: str + ) -> Iterator[None]: + if self.check(open_token): + open_position = self.position + self.read() + else: + open_position = None + + yield + + if open_position is None: + return + + if not self.check(close_token): + self.raise_syntax_error( + f"Expected matching {close_token} for {open_token}, after {around}", + span_start=open_position, + ) + + self.read() diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/markers.py b/data/miniconda3/lib/python3.13/site-packages/packaging/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..e7cea57297a23809548fcd0d344740796bae945b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/markers.py @@ -0,0 +1,362 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import operator +import os +import platform +import sys +from typing import AbstractSet, Any, Callable, Literal, TypedDict, Union, cast + +from ._parser import MarkerAtom, MarkerList, Op, Value, Variable +from ._parser import parse_marker as _parse_marker +from ._tokenizer import ParserSyntaxError +from .specifiers import InvalidSpecifier, Specifier +from .utils import canonicalize_name + +__all__ = [ + "EvaluateContext", + "InvalidMarker", + "Marker", + "UndefinedComparison", + "UndefinedEnvironmentName", + "default_environment", +] + +Operator = Callable[[str, Union[str, AbstractSet[str]]], bool] +EvaluateContext = Literal["metadata", "lock_file", "requirement"] +MARKERS_ALLOWING_SET = {"extras", "dependency_groups"} + + +class InvalidMarker(ValueError): + """ + An invalid marker was found, users should refer to PEP 508. + """ + + +class UndefinedComparison(ValueError): + """ + An invalid operation was attempted on a value that doesn't support it. + """ + + +class UndefinedEnvironmentName(ValueError): + """ + A name was attempted to be used that does not exist inside of the + environment. + """ + + +class Environment(TypedDict): + implementation_name: str + """The implementation's identifier, e.g. ``'cpython'``.""" + + implementation_version: str + """ + The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or + ``'7.3.13'`` for PyPy3.10 v7.3.13. + """ + + os_name: str + """ + The value of :py:data:`os.name`. The name of the operating system dependent module + imported, e.g. ``'posix'``. + """ + + platform_machine: str + """ + Returns the machine type, e.g. ``'i386'``. + + An empty string if the value cannot be determined. + """ + + platform_release: str + """ + The system's release, e.g. ``'2.2.0'`` or ``'NT'``. + + An empty string if the value cannot be determined. + """ + + platform_system: str + """ + The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``. + + An empty string if the value cannot be determined. + """ + + platform_version: str + """ + The system's release version, e.g. ``'#3 on degas'``. + + An empty string if the value cannot be determined. + """ + + python_full_version: str + """ + The Python version as string ``'major.minor.patchlevel'``. + + Note that unlike the Python :py:data:`sys.version`, this value will always include + the patchlevel (it defaults to 0). + """ + + platform_python_implementation: str + """ + A string identifying the Python implementation, e.g. ``'CPython'``. + """ + + python_version: str + """The Python version as string ``'major.minor'``.""" + + sys_platform: str + """ + This string contains a platform identifier that can be used to append + platform-specific components to :py:data:`sys.path`, for instance. + + For Unix systems, except on Linux and AIX, this is the lowercased OS name as + returned by ``uname -s`` with the first part of the version as returned by + ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python + was built. + """ + + +def _normalize_extra_values(results: Any) -> Any: + """ + Normalize extra values. + """ + if isinstance(results[0], tuple): + lhs, op, rhs = results[0] + if isinstance(lhs, Variable) and lhs.value == "extra": + normalized_extra = canonicalize_name(rhs.value) + rhs = Value(normalized_extra) + elif isinstance(rhs, Variable) and rhs.value == "extra": + normalized_extra = canonicalize_name(lhs.value) + lhs = Value(normalized_extra) + results[0] = lhs, op, rhs + return results + + +def _format_marker( + marker: list[str] | MarkerAtom | str, first: bool | None = True +) -> str: + assert isinstance(marker, (list, tuple, str)) + + # Sometimes we have a structure like [[...]] which is a single item list + # where the single item is itself it's own list. In that case we want skip + # the rest of this function so that we don't get extraneous () on the + # outside. + if ( + isinstance(marker, list) + and len(marker) == 1 + and isinstance(marker[0], (list, tuple)) + ): + return _format_marker(marker[0]) + + if isinstance(marker, list): + inner = (_format_marker(m, first=False) for m in marker) + if first: + return " ".join(inner) + else: + return "(" + " ".join(inner) + ")" + elif isinstance(marker, tuple): + return " ".join([m.serialize() for m in marker]) + else: + return marker + + +_operators: dict[str, Operator] = { + "in": lambda lhs, rhs: lhs in rhs, + "not in": lambda lhs, rhs: lhs not in rhs, + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.ge, + ">": operator.gt, +} + + +def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str]) -> bool: + if isinstance(rhs, str): + try: + spec = Specifier("".join([op.serialize(), rhs])) + except InvalidSpecifier: + pass + else: + return spec.contains(lhs, prereleases=True) + + oper: Operator | None = _operators.get(op.serialize()) + if oper is None: + raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") + + return oper(lhs, rhs) + + +def _normalize( + lhs: str, rhs: str | AbstractSet[str], key: str +) -> tuple[str, str | AbstractSet[str]]: + # PEP 685 – Comparison of extra names for optional distribution dependencies + # https://peps.python.org/pep-0685/ + # > When comparing extra names, tools MUST normalize the names being + # > compared using the semantics outlined in PEP 503 for names + if key == "extra": + assert isinstance(rhs, str), "extra value must be a string" + return (canonicalize_name(lhs), canonicalize_name(rhs)) + if key in MARKERS_ALLOWING_SET: + if isinstance(rhs, str): # pragma: no cover + return (canonicalize_name(lhs), canonicalize_name(rhs)) + else: + return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs}) + + # other environment markers don't have such standards + return lhs, rhs + + +def _evaluate_markers( + markers: MarkerList, environment: dict[str, str | AbstractSet[str]] +) -> bool: + groups: list[list[bool]] = [[]] + + for marker in markers: + assert isinstance(marker, (list, tuple, str)) + + if isinstance(marker, list): + groups[-1].append(_evaluate_markers(marker, environment)) + elif isinstance(marker, tuple): + lhs, op, rhs = marker + + if isinstance(lhs, Variable): + environment_key = lhs.value + lhs_value = environment[environment_key] + rhs_value = rhs.value + else: + lhs_value = lhs.value + environment_key = rhs.value + rhs_value = environment[environment_key] + assert isinstance(lhs_value, str), "lhs must be a string" + lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) + groups[-1].append(_eval_op(lhs_value, op, rhs_value)) + else: + assert marker in ["and", "or"] + if marker == "or": + groups.append([]) + + return any(all(item) for item in groups) + + +def format_full_version(info: sys._version_info) -> str: + version = f"{info.major}.{info.minor}.{info.micro}" + kind = info.releaselevel + if kind != "final": + version += kind[0] + str(info.serial) + return version + + +def default_environment() -> Environment: + iver = format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + return { + "implementation_name": implementation_name, + "implementation_version": iver, + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": ".".join(platform.python_version_tuple()[:2]), + "sys_platform": sys.platform, + } + + +class Marker: + def __init__(self, marker: str) -> None: + # Note: We create a Marker object without calling this constructor in + # packaging.requirements.Requirement. If any additional logic is + # added here, make sure to mirror/adapt Requirement. + try: + self._markers = _normalize_extra_values(_parse_marker(marker)) + # The attribute `_markers` can be described in terms of a recursive type: + # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] + # + # For example, the following expression: + # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") + # + # is parsed into: + # [ + # (, ')>, ), + # 'and', + # [ + # (, , ), + # 'or', + # (, , ) + # ] + # ] + except ParserSyntaxError as e: + raise InvalidMarker(str(e)) from e + + def __str__(self) -> str: + return _format_marker(self._markers) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash((self.__class__.__name__, str(self))) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Marker): + return NotImplemented + + return str(self) == str(other) + + def evaluate( + self, + environment: dict[str, str] | None = None, + context: EvaluateContext = "metadata", + ) -> bool: + """Evaluate a marker. + + Return the boolean from evaluating the given marker against the + environment. environment is an optional argument to override all or + part of the determined environment. The *context* parameter specifies what + context the markers are being evaluated for, which influences what markers + are considered valid. Acceptable values are "metadata" (for core metadata; + default), "lock_file", and "requirement" (i.e. all other situations). + + The environment is determined from the current Python process. + """ + current_environment = cast( + "dict[str, str | AbstractSet[str]]", default_environment() + ) + if context == "lock_file": + current_environment.update( + extras=frozenset(), dependency_groups=frozenset() + ) + elif context == "metadata": + current_environment["extra"] = "" + if environment is not None: + current_environment.update(environment) + # The API used to allow setting extra to None. We need to handle this + # case for backwards compatibility. + if "extra" in current_environment and current_environment["extra"] is None: + current_environment["extra"] = "" + + return _evaluate_markers( + self._markers, _repair_python_full_version(current_environment) + ) + + +def _repair_python_full_version( + env: dict[str, str | AbstractSet[str]], +) -> dict[str, str | AbstractSet[str]]: + """ + Work around platform.python_version() returning something that is not PEP 440 + compliant for non-tagged Python builds. + """ + python_full_version = cast(str, env["python_full_version"]) + if python_full_version.endswith("+"): + env["python_full_version"] = f"{python_full_version}local" + return env diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/metadata.py b/data/miniconda3/lib/python3.13/site-packages/packaging/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd8602d36c53374f1f10a0716d28fdc64e2d3ac --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/metadata.py @@ -0,0 +1,862 @@ +from __future__ import annotations + +import email.feedparser +import email.header +import email.message +import email.parser +import email.policy +import pathlib +import sys +import typing +from typing import ( + Any, + Callable, + Generic, + Literal, + TypedDict, + cast, +) + +from . import licenses, requirements, specifiers, utils +from . import version as version_module +from .licenses import NormalizedLicenseExpression + +T = typing.TypeVar("T") + + +if sys.version_info >= (3, 11): # pragma: no cover + ExceptionGroup = ExceptionGroup +else: # pragma: no cover + + class ExceptionGroup(Exception): + """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. + + If :external:exc:`ExceptionGroup` is already defined by Python itself, + that version is used instead. + """ + + message: str + exceptions: list[Exception] + + def __init__(self, message: str, exceptions: list[Exception]) -> None: + self.message = message + self.exceptions = exceptions + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" + + +class InvalidMetadata(ValueError): + """A metadata field contains invalid data.""" + + field: str + """The name of the field that contains invalid data.""" + + def __init__(self, field: str, message: str) -> None: + self.field = field + super().__init__(message) + + +# The RawMetadata class attempts to make as few assumptions about the underlying +# serialization formats as possible. The idea is that as long as a serialization +# formats offer some very basic primitives in *some* way then we can support +# serializing to and from that format. +class RawMetadata(TypedDict, total=False): + """A dictionary of raw core metadata. + + Each field in core metadata maps to a key of this dictionary (when data is + provided). The key is lower-case and underscores are used instead of dashes + compared to the equivalent core metadata field. Any core metadata field that + can be specified multiple times or can hold multiple values in a single + field have a key with a plural name. See :class:`Metadata` whose attributes + match the keys of this dictionary. + + Core metadata fields that can be specified multiple times are stored as a + list or dict depending on which is appropriate for the field. Any fields + which hold multiple values in a single field are stored as a list. + + """ + + # Metadata 1.0 - PEP 241 + metadata_version: str + name: str + version: str + platforms: list[str] + summary: str + description: str + keywords: list[str] + home_page: str + author: str + author_email: str + license: str + + # Metadata 1.1 - PEP 314 + supported_platforms: list[str] + download_url: str + classifiers: list[str] + requires: list[str] + provides: list[str] + obsoletes: list[str] + + # Metadata 1.2 - PEP 345 + maintainer: str + maintainer_email: str + requires_dist: list[str] + provides_dist: list[str] + obsoletes_dist: list[str] + requires_python: str + requires_external: list[str] + project_urls: dict[str, str] + + # Metadata 2.0 + # PEP 426 attempted to completely revamp the metadata format + # but got stuck without ever being able to build consensus on + # it and ultimately ended up withdrawn. + # + # However, a number of tools had started emitting METADATA with + # `2.0` Metadata-Version, so for historical reasons, this version + # was skipped. + + # Metadata 2.1 - PEP 566 + description_content_type: str + provides_extra: list[str] + + # Metadata 2.2 - PEP 643 + dynamic: list[str] + + # Metadata 2.3 - PEP 685 + # No new fields were added in PEP 685, just some edge case were + # tightened up to provide better interoptability. + + # Metadata 2.4 - PEP 639 + license_expression: str + license_files: list[str] + + +_STRING_FIELDS = { + "author", + "author_email", + "description", + "description_content_type", + "download_url", + "home_page", + "license", + "license_expression", + "maintainer", + "maintainer_email", + "metadata_version", + "name", + "requires_python", + "summary", + "version", +} + +_LIST_FIELDS = { + "classifiers", + "dynamic", + "license_files", + "obsoletes", + "obsoletes_dist", + "platforms", + "provides", + "provides_dist", + "provides_extra", + "requires", + "requires_dist", + "requires_external", + "supported_platforms", +} + +_DICT_FIELDS = { + "project_urls", +} + + +def _parse_keywords(data: str) -> list[str]: + """Split a string of comma-separated keywords into a list of keywords.""" + return [k.strip() for k in data.split(",")] + + +def _parse_project_urls(data: list[str]) -> dict[str, str]: + """Parse a list of label/URL string pairings separated by a comma.""" + urls = {} + for pair in data: + # Our logic is slightly tricky here as we want to try and do + # *something* reasonable with malformed data. + # + # The main thing that we have to worry about, is data that does + # not have a ',' at all to split the label from the Value. There + # isn't a singular right answer here, and we will fail validation + # later on (if the caller is validating) so it doesn't *really* + # matter, but since the missing value has to be an empty str + # and our return value is dict[str, str], if we let the key + # be the missing value, then they'd have multiple '' values that + # overwrite each other in a accumulating dict. + # + # The other potentional issue is that it's possible to have the + # same label multiple times in the metadata, with no solid "right" + # answer with what to do in that case. As such, we'll do the only + # thing we can, which is treat the field as unparseable and add it + # to our list of unparsed fields. + parts = [p.strip() for p in pair.split(",", 1)] + parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items + + # TODO: The spec doesn't say anything about if the keys should be + # considered case sensitive or not... logically they should + # be case-preserving and case-insensitive, but doing that + # would open up more cases where we might have duplicate + # entries. + label, url = parts + if label in urls: + # The label already exists in our set of urls, so this field + # is unparseable, and we can just add the whole thing to our + # unparseable data and stop processing it. + raise KeyError("duplicate labels in project urls") + urls[label] = url + + return urls + + +def _get_payload(msg: email.message.Message, source: bytes | str) -> str: + """Get the body of the message.""" + # If our source is a str, then our caller has managed encodings for us, + # and we don't need to deal with it. + if isinstance(source, str): + payload = msg.get_payload() + assert isinstance(payload, str) + return payload + # If our source is a bytes, then we're managing the encoding and we need + # to deal with it. + else: + bpayload = msg.get_payload(decode=True) + assert isinstance(bpayload, bytes) + try: + return bpayload.decode("utf8", "strict") + except UnicodeDecodeError as exc: + raise ValueError("payload in an invalid encoding") from exc + + +# The various parse_FORMAT functions here are intended to be as lenient as +# possible in their parsing, while still returning a correctly typed +# RawMetadata. +# +# To aid in this, we also generally want to do as little touching of the +# data as possible, except where there are possibly some historic holdovers +# that make valid data awkward to work with. +# +# While this is a lower level, intermediate format than our ``Metadata`` +# class, some light touch ups can make a massive difference in usability. + +# Map METADATA fields to RawMetadata. +_EMAIL_TO_RAW_MAPPING = { + "author": "author", + "author-email": "author_email", + "classifier": "classifiers", + "description": "description", + "description-content-type": "description_content_type", + "download-url": "download_url", + "dynamic": "dynamic", + "home-page": "home_page", + "keywords": "keywords", + "license": "license", + "license-expression": "license_expression", + "license-file": "license_files", + "maintainer": "maintainer", + "maintainer-email": "maintainer_email", + "metadata-version": "metadata_version", + "name": "name", + "obsoletes": "obsoletes", + "obsoletes-dist": "obsoletes_dist", + "platform": "platforms", + "project-url": "project_urls", + "provides": "provides", + "provides-dist": "provides_dist", + "provides-extra": "provides_extra", + "requires": "requires", + "requires-dist": "requires_dist", + "requires-external": "requires_external", + "requires-python": "requires_python", + "summary": "summary", + "supported-platform": "supported_platforms", + "version": "version", +} +_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} + + +def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: + """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). + + This function returns a two-item tuple of dicts. The first dict is of + recognized fields from the core metadata specification. Fields that can be + parsed and translated into Python's built-in types are converted + appropriately. All other fields are left as-is. Fields that are allowed to + appear multiple times are stored as lists. + + The second dict contains all other fields from the metadata. This includes + any unrecognized fields. It also includes any fields which are expected to + be parsed into a built-in type but were not formatted appropriately. Finally, + any fields that are expected to appear only once but are repeated are + included in this dict. + + """ + raw: dict[str, str | list[str] | dict[str, str]] = {} + unparsed: dict[str, list[str]] = {} + + if isinstance(data, str): + parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) + else: + parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) + + # We have to wrap parsed.keys() in a set, because in the case of multiple + # values for a key (a list), the key will appear multiple times in the + # list of keys, but we're avoiding that by using get_all(). + for name in frozenset(parsed.keys()): + # Header names in RFC are case insensitive, so we'll normalize to all + # lower case to make comparisons easier. + name = name.lower() + + # We use get_all() here, even for fields that aren't multiple use, + # because otherwise someone could have e.g. two Name fields, and we + # would just silently ignore it rather than doing something about it. + headers = parsed.get_all(name) or [] + + # The way the email module works when parsing bytes is that it + # unconditionally decodes the bytes as ascii using the surrogateescape + # handler. When you pull that data back out (such as with get_all() ), + # it looks to see if the str has any surrogate escapes, and if it does + # it wraps it in a Header object instead of returning the string. + # + # As such, we'll look for those Header objects, and fix up the encoding. + value = [] + # Flag if we have run into any issues processing the headers, thus + # signalling that the data belongs in 'unparsed'. + valid_encoding = True + for h in headers: + # It's unclear if this can return more types than just a Header or + # a str, so we'll just assert here to make sure. + assert isinstance(h, (email.header.Header, str)) + + # If it's a header object, we need to do our little dance to get + # the real data out of it. In cases where there is invalid data + # we're going to end up with mojibake, but there's no obvious, good + # way around that without reimplementing parts of the Header object + # ourselves. + # + # That should be fine since, if mojibacked happens, this key is + # going into the unparsed dict anyways. + if isinstance(h, email.header.Header): + # The Header object stores it's data as chunks, and each chunk + # can be independently encoded, so we'll need to check each + # of them. + chunks: list[tuple[bytes, str | None]] = [] + for bin, encoding in email.header.decode_header(h): + try: + bin.decode("utf8", "strict") + except UnicodeDecodeError: + # Enable mojibake. + encoding = "latin1" + valid_encoding = False + else: + encoding = "utf8" + chunks.append((bin, encoding)) + + # Turn our chunks back into a Header object, then let that + # Header object do the right thing to turn them into a + # string for us. + value.append(str(email.header.make_header(chunks))) + # This is already a string, so just add it. + else: + value.append(h) + + # We've processed all of our values to get them into a list of str, + # but we may have mojibake data, in which case this is an unparsed + # field. + if not valid_encoding: + unparsed[name] = value + continue + + raw_name = _EMAIL_TO_RAW_MAPPING.get(name) + if raw_name is None: + # This is a bit of a weird situation, we've encountered a key that + # we don't know what it means, so we don't know whether it's meant + # to be a list or not. + # + # Since we can't really tell one way or another, we'll just leave it + # as a list, even though it may be a single item list, because that's + # what makes the most sense for email headers. + unparsed[name] = value + continue + + # If this is one of our string fields, then we'll check to see if our + # value is a list of a single item. If it is then we'll assume that + # it was emitted as a single string, and unwrap the str from inside + # the list. + # + # If it's any other kind of data, then we haven't the faintest clue + # what we should parse it as, and we have to just add it to our list + # of unparsed stuff. + if raw_name in _STRING_FIELDS and len(value) == 1: + raw[raw_name] = value[0] + # If this is one of our list of string fields, then we can just assign + # the value, since email *only* has strings, and our get_all() call + # above ensures that this is a list. + elif raw_name in _LIST_FIELDS: + raw[raw_name] = value + # Special Case: Keywords + # The keywords field is implemented in the metadata spec as a str, + # but it conceptually is a list of strings, and is serialized using + # ", ".join(keywords), so we'll do some light data massaging to turn + # this into what it logically is. + elif raw_name == "keywords" and len(value) == 1: + raw[raw_name] = _parse_keywords(value[0]) + # Special Case: Project-URL + # The project urls is implemented in the metadata spec as a list of + # specially-formatted strings that represent a key and a value, which + # is fundamentally a mapping, however the email format doesn't support + # mappings in a sane way, so it was crammed into a list of strings + # instead. + # + # We will do a little light data massaging to turn this into a map as + # it logically should be. + elif raw_name == "project_urls": + try: + raw[raw_name] = _parse_project_urls(value) + except KeyError: + unparsed[name] = value + # Nothing that we've done has managed to parse this, so it'll just + # throw it in our unparseable data and move on. + else: + unparsed[name] = value + + # We need to support getting the Description from the message payload in + # addition to getting it from the the headers. This does mean, though, there + # is the possibility of it being set both ways, in which case we put both + # in 'unparsed' since we don't know which is right. + try: + payload = _get_payload(parsed, data) + except ValueError: + unparsed.setdefault("description", []).append( + parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] + ) + else: + if payload: + # Check to see if we've already got a description, if so then both + # it, and this body move to unparseable. + if "description" in raw: + description_header = cast(str, raw.pop("description")) + unparsed.setdefault("description", []).extend( + [description_header, payload] + ) + elif "description" in unparsed: + unparsed["description"].append(payload) + else: + raw["description"] = payload + + # We need to cast our `raw` to a metadata, because a TypedDict only support + # literal key names, but we're computing our key names on purpose, but the + # way this function is implemented, our `TypedDict` can only have valid key + # names. + return cast(RawMetadata, raw), unparsed + + +_NOT_FOUND = object() + + +# Keep the two values in sync. +_VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4"] +_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4"] + +_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) + + +class _Validator(Generic[T]): + """Validate a metadata field. + + All _process_*() methods correspond to a core metadata field. The method is + called with the field's raw value. If the raw value is valid it is returned + in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). + If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause + as appropriate). + """ + + name: str + raw_name: str + added: _MetadataVersion + + def __init__( + self, + *, + added: _MetadataVersion = "1.0", + ) -> None: + self.added = added + + def __set_name__(self, _owner: Metadata, name: str) -> None: + self.name = name + self.raw_name = _RAW_TO_EMAIL_MAPPING[name] + + def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: + # With Python 3.8, the caching can be replaced with functools.cached_property(). + # No need to check the cache as attribute lookup will resolve into the + # instance's __dict__ before __get__ is called. + cache = instance.__dict__ + value = instance._raw.get(self.name) + + # To make the _process_* methods easier, we'll check if the value is None + # and if this field is NOT a required attribute, and if both of those + # things are true, we'll skip the the converter. This will mean that the + # converters never have to deal with the None union. + if self.name in _REQUIRED_ATTRS or value is not None: + try: + converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") + except AttributeError: + pass + else: + value = converter(value) + + cache[self.name] = value + try: + del instance._raw[self.name] # type: ignore[misc] + except KeyError: + pass + + return cast(T, value) + + def _invalid_metadata( + self, msg: str, cause: Exception | None = None + ) -> InvalidMetadata: + exc = InvalidMetadata( + self.raw_name, msg.format_map({"field": repr(self.raw_name)}) + ) + exc.__cause__ = cause + return exc + + def _process_metadata_version(self, value: str) -> _MetadataVersion: + # Implicitly makes Metadata-Version required. + if value not in _VALID_METADATA_VERSIONS: + raise self._invalid_metadata(f"{value!r} is not a valid metadata version") + return cast(_MetadataVersion, value) + + def _process_name(self, value: str) -> str: + if not value: + raise self._invalid_metadata("{field} is a required field") + # Validate the name as a side-effect. + try: + utils.canonicalize_name(value, validate=True) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return value + + def _process_version(self, value: str) -> version_module.Version: + if not value: + raise self._invalid_metadata("{field} is a required field") + try: + return version_module.parse(value) + except version_module.InvalidVersion as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_summary(self, value: str) -> str: + """Check the field contains no newlines.""" + if "\n" in value: + raise self._invalid_metadata("{field} must be a single line") + return value + + def _process_description_content_type(self, value: str) -> str: + content_types = {"text/plain", "text/x-rst", "text/markdown"} + message = email.message.EmailMessage() + message["content-type"] = value + + content_type, parameters = ( + # Defaults to `text/plain` if parsing failed. + message.get_content_type().lower(), + message["content-type"].params, + ) + # Check if content-type is valid or defaulted to `text/plain` and thus was + # not parseable. + if content_type not in content_types or content_type not in value.lower(): + raise self._invalid_metadata( + f"{{field}} must be one of {list(content_types)}, not {value!r}" + ) + + charset = parameters.get("charset", "UTF-8") + if charset != "UTF-8": + raise self._invalid_metadata( + f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" + ) + + markdown_variants = {"GFM", "CommonMark"} + variant = parameters.get("variant", "GFM") # Use an acceptable default. + if content_type == "text/markdown" and variant not in markdown_variants: + raise self._invalid_metadata( + f"valid Markdown variants for {{field}} are {list(markdown_variants)}, " + f"not {variant!r}", + ) + return value + + def _process_dynamic(self, value: list[str]) -> list[str]: + for dynamic_field in map(str.lower, value): + if dynamic_field in {"name", "version", "metadata-version"}: + raise self._invalid_metadata( + f"{dynamic_field!r} is not allowed as a dynamic field" + ) + elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: + raise self._invalid_metadata( + f"{dynamic_field!r} is not a valid dynamic field" + ) + return list(map(str.lower, value)) + + def _process_provides_extra( + self, + value: list[str], + ) -> list[utils.NormalizedName]: + normalized_names = [] + try: + for name in value: + normalized_names.append(utils.canonicalize_name(name, validate=True)) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return normalized_names + + def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: + try: + return specifiers.SpecifierSet(value) + except specifiers.InvalidSpecifier as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_requires_dist( + self, + value: list[str], + ) -> list[requirements.Requirement]: + reqs = [] + try: + for req in value: + reqs.append(requirements.Requirement(req)) + except requirements.InvalidRequirement as exc: + raise self._invalid_metadata( + f"{req!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return reqs + + def _process_license_expression( + self, value: str + ) -> NormalizedLicenseExpression | None: + try: + return licenses.canonicalize_license_expression(value) + except ValueError as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_license_files(self, value: list[str]) -> list[str]: + paths = [] + for path in value: + if ".." in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, " + "parent directory indicators are not allowed" + ) + if "*" in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be resolved" + ) + if ( + pathlib.PurePosixPath(path).is_absolute() + or pathlib.PureWindowsPath(path).is_absolute() + ): + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be relative" + ) + if pathlib.PureWindowsPath(path).as_posix() != path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must use '/' delimiter" + ) + paths.append(path) + return paths + + +class Metadata: + """Representation of distribution metadata. + + Compared to :class:`RawMetadata`, this class provides objects representing + metadata fields instead of only using built-in types. Any invalid metadata + will cause :exc:`InvalidMetadata` to be raised (with a + :py:attr:`~BaseException.__cause__` attribute as appropriate). + """ + + _raw: RawMetadata + + @classmethod + def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: + """Create an instance from :class:`RawMetadata`. + + If *validate* is true, all metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + ins = cls() + ins._raw = data.copy() # Mutations occur due to caching enriched values. + + if validate: + exceptions: list[Exception] = [] + try: + metadata_version = ins.metadata_version + metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) + except InvalidMetadata as metadata_version_exc: + exceptions.append(metadata_version_exc) + metadata_version = None + + # Make sure to check for the fields that are present, the required + # fields (so their absence can be reported). + fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS + # Remove fields that have already been checked. + fields_to_check -= {"metadata_version"} + + for key in fields_to_check: + try: + if metadata_version: + # Can't use getattr() as that triggers descriptor protocol which + # will fail due to no value for the instance argument. + try: + field_metadata_version = cls.__dict__[key].added + except KeyError: + exc = InvalidMetadata(key, f"unrecognized field: {key!r}") + exceptions.append(exc) + continue + field_age = _VALID_METADATA_VERSIONS.index( + field_metadata_version + ) + if field_age > metadata_age: + field = _RAW_TO_EMAIL_MAPPING[key] + exc = InvalidMetadata( + field, + f"{field} introduced in metadata version " + f"{field_metadata_version}, not {metadata_version}", + ) + exceptions.append(exc) + continue + getattr(ins, key) + except InvalidMetadata as exc: + exceptions.append(exc) + + if exceptions: + raise ExceptionGroup("invalid metadata", exceptions) + + return ins + + @classmethod + def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: + """Parse metadata from email headers. + + If *validate* is true, the metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + raw, unparsed = parse_email(data) + + if validate: + exceptions: list[Exception] = [] + for unparsed_key in unparsed: + if unparsed_key in _EMAIL_TO_RAW_MAPPING: + message = f"{unparsed_key!r} has invalid data" + else: + message = f"unrecognized field: {unparsed_key!r}" + exceptions.append(InvalidMetadata(unparsed_key, message)) + + if exceptions: + raise ExceptionGroup("unparsed", exceptions) + + try: + return cls.from_raw(raw, validate=validate) + except ExceptionGroup as exc_group: + raise ExceptionGroup( + "invalid or unparsed metadata", exc_group.exceptions + ) from None + + metadata_version: _Validator[_MetadataVersion] = _Validator() + """:external:ref:`core-metadata-metadata-version` + (required; validated to be a valid metadata version)""" + # `name` is not normalized/typed to NormalizedName so as to provide access to + # the original/raw name. + name: _Validator[str] = _Validator() + """:external:ref:`core-metadata-name` + (required; validated using :func:`~packaging.utils.canonicalize_name` and its + *validate* parameter)""" + version: _Validator[version_module.Version] = _Validator() + """:external:ref:`core-metadata-version` (required)""" + dynamic: _Validator[list[str] | None] = _Validator( + added="2.2", + ) + """:external:ref:`core-metadata-dynamic` + (validated against core metadata field names and lowercased)""" + platforms: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-platform`""" + supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-supported-platform`""" + summary: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" + description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body + """:external:ref:`core-metadata-description`""" + description_content_type: _Validator[str | None] = _Validator(added="2.1") + """:external:ref:`core-metadata-description-content-type` (validated)""" + keywords: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-keywords`""" + home_page: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-home-page`""" + download_url: _Validator[str | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-download-url`""" + author: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author`""" + author_email: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author-email`""" + maintainer: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer`""" + maintainer_email: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer-email`""" + license: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-license`""" + license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( + added="2.4" + ) + """:external:ref:`core-metadata-license-expression`""" + license_files: _Validator[list[str] | None] = _Validator(added="2.4") + """:external:ref:`core-metadata-license-file`""" + classifiers: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-classifier`""" + requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-dist`""" + requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-python`""" + # Because `Requires-External` allows for non-PEP 440 version specifiers, we + # don't do any processing on the values. + requires_external: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-requires-external`""" + project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-project-url`""" + # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation + # regardless of metadata version. + provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( + added="2.1", + ) + """:external:ref:`core-metadata-provides-extra`""" + provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-provides-dist`""" + obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-obsoletes-dist`""" + requires: _Validator[list[str] | None] = _Validator(added="1.1") + """``Requires`` (deprecated)""" + provides: _Validator[list[str] | None] = _Validator(added="1.1") + """``Provides`` (deprecated)""" + obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") + """``Obsoletes`` (deprecated)""" diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/py.typed b/data/miniconda3/lib/python3.13/site-packages/packaging/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/requirements.py b/data/miniconda3/lib/python3.13/site-packages/packaging/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..4e068c9567def3564f238a76fe7ab46b569f33e5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/requirements.py @@ -0,0 +1,91 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +from __future__ import annotations + +from typing import Any, Iterator + +from ._parser import parse_requirement as _parse_requirement +from ._tokenizer import ParserSyntaxError +from .markers import Marker, _normalize_extra_values +from .specifiers import SpecifierSet +from .utils import canonicalize_name + + +class InvalidRequirement(ValueError): + """ + An invalid requirement was found, users should refer to PEP 508. + """ + + +class Requirement: + """Parse a requirement. + + Parse a given requirement string into its parts, such as name, specifier, + URL, and extras. Raises InvalidRequirement on a badly-formed requirement + string. + """ + + # TODO: Can we test whether something is contained within a requirement? + # If so how do we do that? Do we need to test against the _name_ of + # the thing as well as the version? What about the markers? + # TODO: Can we normalize the name and extra name? + + def __init__(self, requirement_string: str) -> None: + try: + parsed = _parse_requirement(requirement_string) + except ParserSyntaxError as e: + raise InvalidRequirement(str(e)) from e + + self.name: str = parsed.name + self.url: str | None = parsed.url or None + self.extras: set[str] = set(parsed.extras or []) + self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) + self.marker: Marker | None = None + if parsed.marker is not None: + self.marker = Marker.__new__(Marker) + self.marker._markers = _normalize_extra_values(parsed.marker) + + def _iter_parts(self, name: str) -> Iterator[str]: + yield name + + if self.extras: + formatted_extras = ",".join(sorted(self.extras)) + yield f"[{formatted_extras}]" + + if self.specifier: + yield str(self.specifier) + + if self.url: + yield f"@ {self.url}" + if self.marker: + yield " " + + if self.marker: + yield f"; {self.marker}" + + def __str__(self) -> str: + return "".join(self._iter_parts(self.name)) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash( + ( + self.__class__.__name__, + *self._iter_parts(canonicalize_name(self.name)), + ) + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, Requirement): + return NotImplemented + + return ( + canonicalize_name(self.name) == canonicalize_name(other.name) + and self.extras == other.extras + and self.specifier == other.specifier + and self.url == other.url + and self.marker == other.marker + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/specifiers.py b/data/miniconda3/lib/python3.13/site-packages/packaging/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..c8448043006f1c60ee92df69da47986d10229b1d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/specifiers.py @@ -0,0 +1,1019 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier + from packaging.version import Version +""" + +from __future__ import annotations + +import abc +import itertools +import re +from typing import Callable, Iterable, Iterator, TypeVar, Union + +from .utils import canonicalize_version +from .version import Version + +UnparsedVersion = Union[Version, str] +UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) +CallableOperator = Callable[[Version, str], bool] + + +def _coerce_version(version: UnparsedVersion) -> Version: + if not isinstance(version, Version): + version = Version(version) + return version + + +class InvalidSpecifier(ValueError): + """ + Raised when attempting to create a :class:`Specifier` with a specifier + string that is invalid. + + >>> Specifier("lolwat") + Traceback (most recent call last): + ... + packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' + """ + + +class BaseSpecifier(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __str__(self) -> str: + """ + Returns the str representation of this Specifier-like object. This + should be representative of the Specifier itself. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Returns a hash value for this Specifier-like object. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Returns a boolean representing whether or not the two Specifier-like + objects are equal. + + :param other: The other object to check against. + """ + + @property + @abc.abstractmethod + def prereleases(self) -> bool | None: + """Whether or not pre-releases as a whole are allowed. + + This can be set to either ``True`` or ``False`` to explicitly enable or disable + prereleases or it can be set to ``None`` (the default) to use default semantics. + """ + + @prereleases.setter + def prereleases(self, value: bool) -> None: + """Setter for :attr:`prereleases`. + + :param value: The value to set. + """ + + @abc.abstractmethod + def contains(self, item: str, prereleases: bool | None = None) -> bool: + """ + Determines if the given item is contained within this specifier. + """ + + @abc.abstractmethod + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """ + Takes an iterable of items and filters them so that only items which + are contained within this specifier are allowed in it. + """ + + +class Specifier(BaseSpecifier): + """This class abstracts handling of version specifiers. + + .. tip:: + + It is generally not required to instantiate this manually. You should instead + prefer to work with :class:`SpecifierSet` instead, which can parse + comma-separated version specifiers (which is what package metadata contains). + """ + + _operator_regex_str = r""" + (?P(~=|==|!=|<=|>=|<|>|===)) + """ + _version_regex_str = r""" + (?P + (?: + # The identity operators allow for an escape hatch that will + # do an exact string match of the version you wish to install. + # This will not be parsed by PEP 440 and we cannot determine + # any semantic meaning from it. This operator is discouraged + # but included entirely as an escape hatch. + (?<====) # Only match for the identity operator + \s* + [^\s;)]* # The arbitrary version can be just about anything, + # we match everything except for whitespace, a + # semi-colon for marker support, and a closing paren + # since versions can be enclosed in them. + ) + | + (?: + # The (non)equality operators allow for wild card and local + # versions to be specified so we have to define these two + # operators separately to enable that. + (?<===|!=) # Only match for equals and not equals + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + + # You cannot use a wild card and a pre-release, post-release, a dev or + # local version together so group them with a | and make them optional. + (?: + \.\* # Wild card syntax of .* + | + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local + )? + ) + | + (?: + # The compatible operator requires at least two digits in the + # release segment. + (?<=~=) # Only match for the compatible operator + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + | + (?: + # All other operators only allow a sub set of what the + # (non)equality operators do. Specifically they do not allow + # local versions to be specified nor do they allow the prefix + # matching wild cards. + (?=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + "===": "arbitrary", + } + + def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: + """Initialize a Specifier instance. + + :param spec: + The string representation of a specifier which will be parsed and + normalized before use. + :param prereleases: + This tells the specifier if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + :raises InvalidSpecifier: + If the given specifier is invalid (i.e. bad syntax). + """ + match = self._regex.search(spec) + if not match: + raise InvalidSpecifier(f"Invalid specifier: {spec!r}") + + self._spec: tuple[str, str] = ( + match.group("operator").strip(), + match.group("version").strip(), + ) + + # Store whether or not this Specifier should accept prereleases + self._prereleases = prereleases + + # https://github.com/python/mypy/pull/13475#pullrequestreview-1079784515 + @property # type: ignore[override] + def prereleases(self) -> bool: + # If there is an explicit prereleases set for this, then we'll just + # blindly use that. + if self._prereleases is not None: + return self._prereleases + + # Look at all of our specifiers and determine if they are inclusive + # operators, and if they are if they are including an explicit + # prerelease. + operator, version = self._spec + if operator in ["==", ">=", "<=", "~=", "===", ">", "<"]: + # The == specifier can include a trailing .*, if it does we + # want to remove before parsing. + if operator == "==" and version.endswith(".*"): + version = version[:-2] + + # Parse the version, and if it is a pre-release than this + # specifier allows pre-releases. + if Version(version).is_prerelease: + return True + + return False + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + @property + def operator(self) -> str: + """The operator of this specifier. + + >>> Specifier("==1.2.3").operator + '==' + """ + return self._spec[0] + + @property + def version(self) -> str: + """The version of this specifier. + + >>> Specifier("==1.2.3").version + '1.2.3' + """ + return self._spec[1] + + def __repr__(self) -> str: + """A representation of the Specifier that shows all internal state. + + >>> Specifier('>=1.0.0') + =1.0.0')> + >>> Specifier('>=1.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> Specifier('>=1.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"<{self.__class__.__name__}({str(self)!r}{pre})>" + + def __str__(self) -> str: + """A string representation of the Specifier that can be round-tripped. + + >>> str(Specifier('>=1.0.0')) + '>=1.0.0' + >>> str(Specifier('>=1.0.0', prereleases=False)) + '>=1.0.0' + """ + return "{}{}".format(*self._spec) + + @property + def _canonical_spec(self) -> tuple[str, str]: + canonical_version = canonicalize_version( + self._spec[1], + strip_trailing_zero=(self._spec[0] != "~="), + ) + return self._spec[0], canonical_version + + def __hash__(self) -> int: + return hash(self._canonical_spec) + + def __eq__(self, other: object) -> bool: + """Whether or not the two Specifier-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") + True + >>> (Specifier("==1.2.3", prereleases=False) == + ... Specifier("==1.2.3", prereleases=True)) + True + >>> Specifier("==1.2.3") == "==1.2.3" + True + >>> Specifier("==1.2.3") == Specifier("==1.2.4") + False + >>> Specifier("==1.2.3") == Specifier("~=1.2.3") + False + """ + if isinstance(other, str): + try: + other = self.__class__(str(other)) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._canonical_spec == other._canonical_spec + + def _get_operator(self, op: str) -> CallableOperator: + operator_callable: CallableOperator = getattr( + self, f"_compare_{self._operators[op]}" + ) + return operator_callable + + def _compare_compatible(self, prospective: Version, spec: str) -> bool: + # Compatible releases have an equivalent combination of >= and ==. That + # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to + # implement this in terms of the other specifiers instead of + # implementing it ourselves. The only thing we need to do is construct + # the other specifiers. + + # We want everything but the last item in the version, but we want to + # ignore suffix segments. + prefix = _version_join( + list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] + ) + + # Add the prefix notation to the end of our string + prefix += ".*" + + return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( + prospective, prefix + ) + + def _compare_equal(self, prospective: Version, spec: str) -> bool: + # We need special logic to handle prefix matching + if spec.endswith(".*"): + # In the case of prefix matching we want to ignore local segment. + normalized_prospective = canonicalize_version( + prospective.public, strip_trailing_zero=False + ) + # Get the normalized version string ignoring the trailing .* + normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) + # Split the spec out by bangs and dots, and pretend that there is + # an implicit dot in between a release segment and a pre-release segment. + split_spec = _version_split(normalized_spec) + + # Split the prospective version out by bangs and dots, and pretend + # that there is an implicit dot in between a release segment and + # a pre-release segment. + split_prospective = _version_split(normalized_prospective) + + # 0-pad the prospective version before shortening it to get the correct + # shortened version. + padded_prospective, _ = _pad_version(split_prospective, split_spec) + + # Shorten the prospective version to be the same length as the spec + # so that we can determine if the specifier is a prefix of the + # prospective version or not. + shortened_prospective = padded_prospective[: len(split_spec)] + + return shortened_prospective == split_spec + else: + # Convert our spec string into a Version + spec_version = Version(spec) + + # If the specifier does not have a local segment, then we want to + # act as if the prospective version also does not have a local + # segment. + if not spec_version.local: + prospective = Version(prospective.public) + + return prospective == spec_version + + def _compare_not_equal(self, prospective: Version, spec: str) -> bool: + return not self._compare_equal(prospective, spec) + + def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) <= Version(spec) + + def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return Version(prospective.public) >= Version(spec) + + def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is less than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective < spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a pre-release version, that we do not accept pre-release + # versions for the version mentioned in the specifier (e.g. <3.1 should + # not match 3.1.dev0, but should match 3.0.dev0). + if not spec.is_prerelease and prospective.is_prerelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # less than the spec version *and* it's not a pre-release of the same + # version in the spec. + return True + + def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = Version(spec_str) + + # Check to see if the prospective version is greater than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective > spec: + return False + + # This special case is here so that, unless the specifier itself + # includes is a post-release version, that we do not accept + # post-release versions for the version mentioned in the specifier + # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). + if not spec.is_postrelease and prospective.is_postrelease: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # Ensure that we do not allow a local version of the version mentioned + # in the specifier, which is technically greater than, to match. + if prospective.local is not None: + if Version(prospective.base_version) == Version(spec.base_version): + return False + + # If we've gotten to here, it means that prospective version is both + # greater than the spec version *and* it's not a pre-release of the + # same version in the spec. + return True + + def _compare_arbitrary(self, prospective: Version, spec: str) -> bool: + return str(prospective).lower() == str(spec).lower() + + def __contains__(self, item: str | Version) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in Specifier(">=1.2.3") + True + >>> Version("1.2.3") in Specifier(">=1.2.3") + True + >>> "1.0.0" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) + True + """ + return self.contains(item) + + def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this Specifier. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> Specifier(">=1.2.3").contains("1.2.3") + True + >>> Specifier(">=1.2.3").contains(Version("1.2.3")) + True + >>> Specifier(">=1.2.3").contains("1.0.0") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + False + >>> Specifier(">=1.2.3", prereleases=True).contains("1.3.0a1") + True + >>> Specifier(">=1.2.3").contains("1.3.0a1", prereleases=True) + True + """ + + # Determine if prereleases are to be allowed or not. + if prereleases is None: + prereleases = self.prereleases + + # Normalize item to a Version, this allows us to have a shortcut for + # "2.0" in Specifier(">=2") + normalized_item = _coerce_version(item) + + # Determine if we should be supporting prereleases in this specifier + # or not, if we do not support prereleases than we can short circuit + # logic if this version is a prereleases. + if normalized_item.is_prerelease and not prereleases: + return False + + # Actually do the comparison to determine if this item is contained + # within this Specifier or not. + operator_callable: CallableOperator = self._get_operator(self.operator) + return operator_callable(normalized_item, self.version) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifier. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(Specifier().contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) + ['1.2.3', '1.3', ] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + """ + + yielded = False + found_prereleases = [] + + kw = {"prereleases": prereleases if prereleases is not None else True} + + # Attempt to iterate over all the values in the iterable and if any of + # them match, yield them. + for version in iterable: + parsed_version = _coerce_version(version) + + if self.contains(parsed_version, **kw): + # If our version is a prerelease, and we were not set to allow + # prereleases, then we'll store it for later in case nothing + # else matches this specifier. + if parsed_version.is_prerelease and not ( + prereleases or self.prereleases + ): + found_prereleases.append(version) + # Either this is not a prerelease, or we should have been + # accepting prereleases from the beginning. + else: + yielded = True + yield version + + # Now that we've iterated over everything, determine if we've yielded + # any values, and if we have not and we have any prereleases stored up + # then we will go ahead and yield the prereleases. + if not yielded and found_prereleases: + for version in found_prereleases: + yield version + + +_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") + + +def _version_split(version: str) -> list[str]: + """Split version into components. + + The split components are intended for version comparison. The logic does + not attempt to retain the original version string, so joining the + components back with :func:`_version_join` may not produce the original + version string. + """ + result: list[str] = [] + + epoch, _, rest = version.rpartition("!") + result.append(epoch or "0") + + for item in rest.split("."): + match = _prefix_regex.search(item) + if match: + result.extend(match.groups()) + else: + result.append(item) + return result + + +def _version_join(components: list[str]) -> str: + """Join split version components into a version string. + + This function assumes the input came from :func:`_version_split`, where the + first component must be the epoch (either empty or numeric), and all other + components numeric. + """ + epoch, *rest = components + return f"{epoch}!{'.'.join(rest)}" + + +def _is_not_suffix(segment: str) -> bool: + return not any( + segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") + ) + + +def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]: + left_split, right_split = [], [] + + # Get the release segment of our versions + left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) + right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) + + # Get the rest of our versions + left_split.append(left[len(left_split[0]) :]) + right_split.append(right[len(right_split[0]) :]) + + # Insert our padding + left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) + right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) + + return ( + list(itertools.chain.from_iterable(left_split)), + list(itertools.chain.from_iterable(right_split)), + ) + + +class SpecifierSet(BaseSpecifier): + """This class abstracts handling of a set of version specifiers. + + It can be passed a single specifier (``>=3.0``), a comma-separated list of + specifiers (``>=3.0,!=3.1``), or no specifier at all. + """ + + def __init__( + self, + specifiers: str | Iterable[Specifier] = "", + prereleases: bool | None = None, + ) -> None: + """Initialize a SpecifierSet instance. + + :param specifiers: + The string representation of a specifier or a comma-separated list of + specifiers which will be parsed and normalized before use. + May also be an iterable of ``Specifier`` instances, which will be used + as is. + :param prereleases: + This tells the SpecifierSet if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + + :raises InvalidSpecifier: + If the given ``specifiers`` are not parseable than this exception will be + raised. + """ + + if isinstance(specifiers, str): + # Split on `,` to break each individual specifier into its own item, and + # strip each item to remove leading/trailing whitespace. + split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] + + # Make each individual specifier a Specifier and save in a frozen set + # for later. + self._specs = frozenset(map(Specifier, split_specifiers)) + else: + # Save the supplied specifiers in a frozen set. + self._specs = frozenset(specifiers) + + # Store our prereleases value so we can use it later to determine if + # we accept prereleases or not. + self._prereleases = prereleases + + @property + def prereleases(self) -> bool | None: + # If we have been given an explicit prerelease modifier, then we'll + # pass that through here. + if self._prereleases is not None: + return self._prereleases + + # If we don't have any specifiers, and we don't have a forced value, + # then we'll just return None since we don't know if this should have + # pre-releases or not. + if not self._specs: + return None + + # Otherwise we'll see if any of the given specifiers accept + # prereleases, if any of them do we'll return True, otherwise False. + return any(s.prereleases for s in self._specs) + + @prereleases.setter + def prereleases(self, value: bool) -> None: + self._prereleases = value + + def __repr__(self) -> str: + """A representation of the specifier set that shows all internal state. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> SpecifierSet('>=1.0.0,!=2.0.0') + =1.0.0')> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"" + + def __str__(self) -> str: + """A string representation of the specifier set that can be round-tripped. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) + '!=1.0.1,>=1.0.0' + >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) + '!=1.0.1,>=1.0.0' + """ + return ",".join(sorted(str(s) for s in self._specs)) + + def __hash__(self) -> int: + return hash(self._specs) + + def __and__(self, other: SpecifierSet | str) -> SpecifierSet: + """Return a SpecifierSet which is a combination of the two sets. + + :param other: The other object to combine with. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' + =1.0.0')> + >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') + =1.0.0')> + """ + if isinstance(other, str): + other = SpecifierSet(other) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + specifier = SpecifierSet() + specifier._specs = frozenset(self._specs | other._specs) + + if self._prereleases is None and other._prereleases is not None: + specifier._prereleases = other._prereleases + elif self._prereleases is not None and other._prereleases is None: + specifier._prereleases = self._prereleases + elif self._prereleases == other._prereleases: + specifier._prereleases = self._prereleases + else: + raise ValueError( + "Cannot combine SpecifierSets with True and False prerelease overrides." + ) + + return specifier + + def __eq__(self, other: object) -> bool: + """Whether or not the two SpecifierSet-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == + ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") + False + """ + if isinstance(other, (str, Specifier)): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._specs == other._specs + + def __len__(self) -> int: + """Returns the number of specifiers in this specifier set.""" + return len(self._specs) + + def __iter__(self) -> Iterator[Specifier]: + """ + Returns an iterator over all the underlying :class:`Specifier` instances + in this specifier set. + + >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) + [, =1.0.0')>] + """ + return iter(self._specs) + + def __contains__(self, item: UnparsedVersion) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) + True + """ + return self.contains(item) + + def contains( + self, + item: UnparsedVersion, + prereleases: bool | None = None, + installed: bool | None = None, + ) -> bool: + """Return whether or not the item is contained in this SpecifierSet. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this SpecifierSet. If set to + ``None`` (the default), it uses :attr:`prereleases` to determine + whether or not prereleases are allowed. + + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True).contains("1.3.0a1") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) + True + """ + # Ensure that our item is a Version instance. + if not isinstance(item, Version): + item = Version(item) + + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # We can determine if we're going to allow pre-releases by looking to + # see if any of the underlying items supports them. If none of them do + # and this item is a pre-release then we do not allow it and we can + # short circuit that here. + # Note: This means that 1.0.dev1 would not be contained in something + # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 + if not prereleases and item.is_prerelease: + return False + + if installed and item.is_prerelease: + item = Version(item.base_version) + + # We simply dispatch to the underlying specs here to make sure that the + # given version is contained within all of them. + # Note: This use of all() here means that an empty set of specifiers + # will always return True, this is an explicit design decision. + return all(s.contains(item, prereleases=prereleases) for s in self._specs) + + def filter( + self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None + ) -> Iterator[UnparsedVersionVar]: + """Filter items in the given iterable, that match the specifiers in this set. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will be intelligently decide whether to allow + prereleases or not (based on the :attr:`prereleases` attribute, and + whether the only versions matching are prereleases). + + This method is smarter than just ``filter(SpecifierSet(...).contains, [...])`` + because it implements the rule from :pep:`440` that a prerelease item + SHOULD be accepted if no other versions match the given specifier. + + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) + ['1.3', ] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) + [] + >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + + An "empty" SpecifierSet will filter items based on the presence of prerelease + versions in the set. + + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet("").filter(["1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + """ + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None: + prereleases = self.prereleases + + # If we have any specifiers, then we want to wrap our iterable in the + # filter method for each one, this will act as a logical AND amongst + # each specifier. + if self._specs: + for spec in self._specs: + iterable = spec.filter(iterable, prereleases=bool(prereleases)) + return iter(iterable) + # If we do not have any specifiers, then we need to have a rough filter + # which will filter out any pre-releases, unless there are no final + # releases. + else: + filtered: list[UnparsedVersionVar] = [] + found_prereleases: list[UnparsedVersionVar] = [] + + for item in iterable: + parsed_version = _coerce_version(item) + + # Store any item which is a pre-release for later unless we've + # already found a final version or we are accepting prereleases + if parsed_version.is_prerelease and not prereleases: + if not filtered: + found_prereleases.append(item) + else: + filtered.append(item) + + # If we've found no items except for pre-releases, then we'll go + # ahead and use the pre-releases + if not filtered and found_prereleases and prereleases is None: + return iter(found_prereleases) + + return iter(filtered) diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/tags.py b/data/miniconda3/lib/python3.13/site-packages/packaging/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..8522f59c4f2d0039c1a02ea9aef66fe017dbdb20 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/tags.py @@ -0,0 +1,656 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import logging +import platform +import re +import struct +import subprocess +import sys +import sysconfig +from importlib.machinery import EXTENSION_SUFFIXES +from typing import ( + Iterable, + Iterator, + Sequence, + Tuple, + cast, +) + +from . import _manylinux, _musllinux + +logger = logging.getLogger(__name__) + +PythonVersion = Sequence[int] +AppleVersion = Tuple[int, int] + +INTERPRETER_SHORT_NAMES: dict[str, str] = { + "python": "py", # Generic. + "cpython": "cp", + "pypy": "pp", + "ironpython": "ip", + "jython": "jy", +} + + +_32_BIT_INTERPRETER = struct.calcsize("P") == 4 + + +class Tag: + """ + A representation of the tag triple for a wheel. + + Instances are considered immutable and thus are hashable. Equality checking + is also supported. + """ + + __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] + + def __init__(self, interpreter: str, abi: str, platform: str) -> None: + self._interpreter = interpreter.lower() + self._abi = abi.lower() + self._platform = platform.lower() + # The __hash__ of every single element in a Set[Tag] will be evaluated each time + # that a set calls its `.disjoint()` method, which may be called hundreds of + # times when scanning a page of links for packages with tags matching that + # Set[Tag]. Pre-computing the value here produces significant speedups for + # downstream consumers. + self._hash = hash((self._interpreter, self._abi, self._platform)) + + @property + def interpreter(self) -> str: + return self._interpreter + + @property + def abi(self) -> str: + return self._abi + + @property + def platform(self) -> str: + return self._platform + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Tag): + return NotImplemented + + return ( + (self._hash == other._hash) # Short-circuit ASAP for perf reasons. + and (self._platform == other._platform) + and (self._abi == other._abi) + and (self._interpreter == other._interpreter) + ) + + def __hash__(self) -> int: + return self._hash + + def __str__(self) -> str: + return f"{self._interpreter}-{self._abi}-{self._platform}" + + def __repr__(self) -> str: + return f"<{self} @ {id(self)}>" + + +def parse_tag(tag: str) -> frozenset[Tag]: + """ + Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. + + Returning a set is required due to the possibility that the tag is a + compressed tag set. + """ + tags = set() + interpreters, abis, platforms = tag.split("-") + for interpreter in interpreters.split("."): + for abi in abis.split("."): + for platform_ in platforms.split("."): + tags.add(Tag(interpreter, abi, platform_)) + return frozenset(tags) + + +def _get_config_var(name: str, warn: bool = False) -> int | str | None: + value: int | str | None = sysconfig.get_config_var(name) + if value is None and warn: + logger.debug( + "Config variable '%s' is unset, Python ABI tag may be incorrect", name + ) + return value + + +def _normalize_string(string: str) -> str: + return string.replace(".", "_").replace("-", "_").replace(" ", "_") + + +def _is_threaded_cpython(abis: list[str]) -> bool: + """ + Determine if the ABI corresponds to a threaded (`--disable-gil`) build. + + The threaded builds are indicated by a "t" in the abiflags. + """ + if len(abis) == 0: + return False + # expect e.g., cp313 + m = re.match(r"cp\d+(.*)", abis[0]) + if not m: + return False + abiflags = m.group(1) + return "t" in abiflags + + +def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: + """ + Determine if the Python version supports abi3. + + PEP 384 was first implemented in Python 3.2. The threaded (`--disable-gil`) + builds do not support abi3. + """ + return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading + + +def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: + py_version = tuple(py_version) # To allow for version comparison. + abis = [] + version = _version_nodot(py_version[:2]) + threading = debug = pymalloc = ucs4 = "" + with_debug = _get_config_var("Py_DEBUG", warn) + has_refcount = hasattr(sys, "gettotalrefcount") + # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled + # extension modules is the best option. + # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 + has_ext = "_d.pyd" in EXTENSION_SUFFIXES + if with_debug or (with_debug is None and (has_refcount or has_ext)): + debug = "d" + if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): + threading = "t" + if py_version < (3, 8): + with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) + if with_pymalloc or with_pymalloc is None: + pymalloc = "m" + if py_version < (3, 3): + unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) + if unicode_size == 4 or ( + unicode_size is None and sys.maxunicode == 0x10FFFF + ): + ucs4 = "u" + elif debug: + # Debug builds can also load "normal" extension modules. + # We can also assume no UCS-4 or pymalloc requirement. + abis.append(f"cp{version}{threading}") + abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") + return abis + + +def cpython_tags( + python_version: PythonVersion | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for a CPython interpreter. + + The tags consist of: + - cp-- + - cp-abi3- + - cp-none- + - cp-abi3- # Older Python versions down to 3.2. + + If python_version only specifies a major version then user-provided ABIs and + the 'none' ABItag will be used. + + If 'abi3' or 'none' are specified in 'abis' then they will be yielded at + their normal position and not at the beginning. + """ + if not python_version: + python_version = sys.version_info[:2] + + interpreter = f"cp{_version_nodot(python_version[:2])}" + + if abis is None: + if len(python_version) > 1: + abis = _cpython_abis(python_version, warn) + else: + abis = [] + abis = list(abis) + # 'abi3' and 'none' are explicitly handled later. + for explicit_abi in ("abi3", "none"): + try: + abis.remove(explicit_abi) + except ValueError: + pass + + platforms = list(platforms or platform_tags()) + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + threading = _is_threaded_cpython(abis) + use_abi3 = _abi3_applies(python_version, threading) + if use_abi3: + yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) + yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) + + if use_abi3: + for minor_version in range(python_version[1] - 1, 1, -1): + for platform_ in platforms: + version = _version_nodot((python_version[0], minor_version)) + interpreter = f"cp{version}" + yield Tag(interpreter, "abi3", platform_) + + +def _generic_abi() -> list[str]: + """ + Return the ABI tag based on EXT_SUFFIX. + """ + # The following are examples of `EXT_SUFFIX`. + # We want to keep the parts which are related to the ABI and remove the + # parts which are related to the platform: + # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 + # - mac: '.cpython-310-darwin.so' => cp310 + # - win: '.cp310-win_amd64.pyd' => cp310 + # - win: '.pyd' => cp37 (uses _cpython_abis()) + # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 + # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' + # => graalpy_38_native + + ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) + if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": + raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") + parts = ext_suffix.split(".") + if len(parts) < 3: + # CPython3.7 and earlier uses ".pyd" on Windows. + return _cpython_abis(sys.version_info[:2]) + soabi = parts[1] + if soabi.startswith("cpython"): + # non-windows + abi = "cp" + soabi.split("-")[1] + elif soabi.startswith("cp"): + # windows + abi = soabi.split("-")[0] + elif soabi.startswith("pypy"): + abi = "-".join(soabi.split("-")[:2]) + elif soabi.startswith("graalpy"): + abi = "-".join(soabi.split("-")[:3]) + elif soabi: + # pyston, ironpython, others? + abi = soabi + else: + return [] + return [_normalize_string(abi)] + + +def generic_tags( + interpreter: str | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for a generic interpreter. + + The tags consist of: + - -- + + The "none" ABI will be added if it was not explicitly provided. + """ + if not interpreter: + interp_name = interpreter_name() + interp_version = interpreter_version(warn=warn) + interpreter = "".join([interp_name, interp_version]) + if abis is None: + abis = _generic_abi() + else: + abis = list(abis) + platforms = list(platforms or platform_tags()) + if "none" not in abis: + abis.append("none") + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + +def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: + """ + Yields Python versions in descending order. + + After the latest version, the major-only version will be yielded, and then + all previous versions of that major version. + """ + if len(py_version) > 1: + yield f"py{_version_nodot(py_version[:2])}" + yield f"py{py_version[0]}" + if len(py_version) > 1: + for minor in range(py_version[1] - 1, -1, -1): + yield f"py{_version_nodot((py_version[0], minor))}" + + +def compatible_tags( + python_version: PythonVersion | None = None, + interpreter: str | None = None, + platforms: Iterable[str] | None = None, +) -> Iterator[Tag]: + """ + Yields the sequence of tags that are compatible with a specific version of Python. + + The tags consist of: + - py*-none- + - -none-any # ... if `interpreter` is provided. + - py*-none-any + """ + if not python_version: + python_version = sys.version_info[:2] + platforms = list(platforms or platform_tags()) + for version in _py_interpreter_range(python_version): + for platform_ in platforms: + yield Tag(version, "none", platform_) + if interpreter: + yield Tag(interpreter, "none", "any") + for version in _py_interpreter_range(python_version): + yield Tag(version, "none", "any") + + +def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: + if not is_32bit: + return arch + + if arch.startswith("ppc"): + return "ppc" + + return "i386" + + +def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: + formats = [cpu_arch] + if cpu_arch == "x86_64": + if version < (10, 4): + return [] + formats.extend(["intel", "fat64", "fat32"]) + + elif cpu_arch == "i386": + if version < (10, 4): + return [] + formats.extend(["intel", "fat32", "fat"]) + + elif cpu_arch == "ppc64": + # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? + if version > (10, 5) or version < (10, 4): + return [] + formats.append("fat64") + + elif cpu_arch == "ppc": + if version > (10, 6): + return [] + formats.extend(["fat32", "fat"]) + + if cpu_arch in {"arm64", "x86_64"}: + formats.append("universal2") + + if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: + formats.append("universal") + + return formats + + +def mac_platforms( + version: AppleVersion | None = None, arch: str | None = None +) -> Iterator[str]: + """ + Yields the platform tags for a macOS system. + + The `version` parameter is a two-item tuple specifying the macOS version to + generate platform tags for. The `arch` parameter is the CPU architecture to + generate platform tags for. Both parameters default to the appropriate value + for the current system. + """ + version_str, _, cpu_arch = platform.mac_ver() + if version is None: + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + if version == (10, 16): + # When built against an older macOS SDK, Python will report macOS 10.16 + # instead of the real version. + version_str = subprocess.run( + [ + sys.executable, + "-sS", + "-c", + "import platform; print(platform.mac_ver()[0])", + ], + check=True, + env={"SYSTEM_VERSION_COMPAT": "0"}, + stdout=subprocess.PIPE, + text=True, + ).stdout + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + else: + version = version + if arch is None: + arch = _mac_arch(cpu_arch) + else: + arch = arch + + if (10, 0) <= version and version < (11, 0): + # Prior to Mac OS 11, each yearly release of Mac OS bumped the + # "minor" version number. The major version was always 10. + major_version = 10 + for minor_version in range(version[1], -1, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Starting with Mac OS 11, each yearly release bumps the major version + # number. The minor versions are now the midyear updates. + minor_version = 0 + for major_version in range(version[0], 10, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Mac OS 11 on x86_64 is compatible with binaries from previous releases. + # Arm64 support was introduced in 11.0, so no Arm binaries from previous + # releases exist. + # + # However, the "universal2" binary format can have a + # macOS version earlier than 11.0 when the x86_64 part of the binary supports + # that version of macOS. + major_version = 10 + if arch == "x86_64": + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + else: + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_format = "universal2" + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + +def ios_platforms( + version: AppleVersion | None = None, multiarch: str | None = None +) -> Iterator[str]: + """ + Yields the platform tags for an iOS system. + + :param version: A two-item tuple specifying the iOS version to generate + platform tags for. Defaults to the current iOS version. + :param multiarch: The CPU architecture+ABI to generate platform tags for - + (the value used by `sys.implementation._multiarch` e.g., + `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current + multiarch value. + """ + if version is None: + # if iOS is the current platform, ios_ver *must* be defined. However, + # it won't exist for CPython versions before 3.13, which causes a mypy + # error. + _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] + version = cast("AppleVersion", tuple(map(int, release.split(".")[:2]))) + + if multiarch is None: + multiarch = sys.implementation._multiarch + multiarch = multiarch.replace("-", "_") + + ios_platform_template = "ios_{major}_{minor}_{multiarch}" + + # Consider any iOS major.minor version from the version requested, down to + # 12.0. 12.0 is the first iOS version that is known to have enough features + # to support CPython. Consider every possible minor release up to X.9. There + # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra + # candidates that won't ever match doesn't really hurt, and it saves us from + # having to keep an explicit list of known iOS versions in the code. Return + # the results descending order of version number. + + # If the requested major version is less than 12, there won't be any matches. + if version[0] < 12: + return + + # Consider the actual X.Y version that was requested. + yield ios_platform_template.format( + major=version[0], minor=version[1], multiarch=multiarch + ) + + # Consider every minor version from X.0 to the minor version prior to the + # version requested by the platform. + for minor in range(version[1] - 1, -1, -1): + yield ios_platform_template.format( + major=version[0], minor=minor, multiarch=multiarch + ) + + for major in range(version[0] - 1, 11, -1): + for minor in range(9, -1, -1): + yield ios_platform_template.format( + major=major, minor=minor, multiarch=multiarch + ) + + +def android_platforms( + api_level: int | None = None, abi: str | None = None +) -> Iterator[str]: + """ + Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on + non-Android platforms, the ``api_level`` and ``abi`` arguments are required. + + :param int api_level: The maximum `API level + `__ to return. Defaults + to the current system's version, as returned by ``platform.android_ver``. + :param str abi: The `Android ABI `__, + e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by + ``sysconfig.get_platform``. Hyphens and periods will be replaced with + underscores. + """ + if platform.system() != "Android" and (api_level is None or abi is None): + raise TypeError( + "on non-Android platforms, the api_level and abi arguments are required" + ) + + if api_level is None: + # Python 3.13 was the first version to return platform.system() == "Android", + # and also the first version to define platform.android_ver(). + api_level = platform.android_ver().api_level # type: ignore[attr-defined] + + if abi is None: + abi = sysconfig.get_platform().split("-")[-1] + abi = _normalize_string(abi) + + # 16 is the minimum API level known to have enough features to support CPython + # without major patching. Yield every API level from the maximum down to the + # minimum, inclusive. + min_api_level = 16 + for ver in range(api_level, min_api_level - 1, -1): + yield f"android_{ver}_{abi}" + + +def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: + linux = _normalize_string(sysconfig.get_platform()) + if not linux.startswith("linux_"): + # we should never be here, just yield the sysconfig one and return + yield linux + return + if is_32bit: + if linux == "linux_x86_64": + linux = "linux_i686" + elif linux == "linux_aarch64": + linux = "linux_armv8l" + _, arch = linux.split("_", 1) + archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) + yield from _manylinux.platform_tags(archs) + yield from _musllinux.platform_tags(archs) + for arch in archs: + yield f"linux_{arch}" + + +def _generic_platforms() -> Iterator[str]: + yield _normalize_string(sysconfig.get_platform()) + + +def platform_tags() -> Iterator[str]: + """ + Provides the platform tags for this installation. + """ + if platform.system() == "Darwin": + return mac_platforms() + elif platform.system() == "iOS": + return ios_platforms() + elif platform.system() == "Android": + return android_platforms() + elif platform.system() == "Linux": + return _linux_platforms() + else: + return _generic_platforms() + + +def interpreter_name() -> str: + """ + Returns the name of the running interpreter. + + Some implementations have a reserved, two-letter abbreviation which will + be returned when appropriate. + """ + name = sys.implementation.name + return INTERPRETER_SHORT_NAMES.get(name) or name + + +def interpreter_version(*, warn: bool = False) -> str: + """ + Returns the version of the running interpreter. + """ + version = _get_config_var("py_version_nodot", warn=warn) + if version: + version = str(version) + else: + version = _version_nodot(sys.version_info[:2]) + return version + + +def _version_nodot(version: PythonVersion) -> str: + return "".join(map(str, version)) + + +def sys_tags(*, warn: bool = False) -> Iterator[Tag]: + """ + Returns the sequence of tag triples for the running interpreter. + + The order of the sequence corresponds to priority order for the + interpreter, from most to least important. + """ + + interp_name = interpreter_name() + if interp_name == "cp": + yield from cpython_tags(warn=warn) + else: + yield from generic_tags() + + if interp_name == "pp": + interp = "pp3" + elif interp_name == "cp": + interp = "cp" + interpreter_version(warn=warn) + else: + interp = None + yield from compatible_tags(interpreter=interp) diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/utils.py b/data/miniconda3/lib/python3.13/site-packages/packaging/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..23450953df74eccd9c13cd2a955ce09d1f968565 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/utils.py @@ -0,0 +1,163 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import functools +import re +from typing import NewType, Tuple, Union, cast + +from .tags import Tag, parse_tag +from .version import InvalidVersion, Version, _TrimmedRelease + +BuildTag = Union[Tuple[()], Tuple[int, str]] +NormalizedName = NewType("NormalizedName", str) + + +class InvalidName(ValueError): + """ + An invalid distribution name; users should refer to the packaging user guide. + """ + + +class InvalidWheelFilename(ValueError): + """ + An invalid wheel filename was found, users should refer to PEP 427. + """ + + +class InvalidSdistFilename(ValueError): + """ + An invalid sdist filename was found, users should refer to the packaging user guide. + """ + + +# Core metadata spec for `Name` +_validate_regex = re.compile( + r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.IGNORECASE +) +_canonicalize_regex = re.compile(r"[-_.]+") +_normalized_regex = re.compile(r"^([a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9])$") +# PEP 427: The build number must start with a digit. +_build_tag_regex = re.compile(r"(\d+)(.*)") + + +def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: + if validate and not _validate_regex.match(name): + raise InvalidName(f"name is invalid: {name!r}") + # This is taken from PEP 503. + value = _canonicalize_regex.sub("-", name).lower() + return cast(NormalizedName, value) + + +def is_normalized_name(name: str) -> bool: + return _normalized_regex.match(name) is not None + + +@functools.singledispatch +def canonicalize_version( + version: Version | str, *, strip_trailing_zero: bool = True +) -> str: + """ + Return a canonical form of a version as a string. + + >>> canonicalize_version('1.0.1') + '1.0.1' + + Per PEP 625, versions may have multiple canonical forms, differing + only by trailing zeros. + + >>> canonicalize_version('1.0.0') + '1' + >>> canonicalize_version('1.0.0', strip_trailing_zero=False) + '1.0.0' + + Invalid versions are returned unaltered. + + >>> canonicalize_version('foo bar baz') + 'foo bar baz' + """ + return str(_TrimmedRelease(str(version)) if strip_trailing_zero else version) + + +@canonicalize_version.register +def _(version: str, *, strip_trailing_zero: bool = True) -> str: + try: + parsed = Version(version) + except InvalidVersion: + # Legacy versions cannot be normalized + return version + return canonicalize_version(parsed, strip_trailing_zero=strip_trailing_zero) + + +def parse_wheel_filename( + filename: str, +) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: + if not filename.endswith(".whl"): + raise InvalidWheelFilename( + f"Invalid wheel filename (extension must be '.whl'): {filename!r}" + ) + + filename = filename[:-4] + dashes = filename.count("-") + if dashes not in (4, 5): + raise InvalidWheelFilename( + f"Invalid wheel filename (wrong number of parts): {filename!r}" + ) + + parts = filename.split("-", dashes - 2) + name_part = parts[0] + # See PEP 427 for the rules on escaping the project name. + if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: + raise InvalidWheelFilename(f"Invalid project name: {filename!r}") + name = canonicalize_name(name_part) + + try: + version = Version(parts[1]) + except InvalidVersion as e: + raise InvalidWheelFilename( + f"Invalid wheel filename (invalid version): {filename!r}" + ) from e + + if dashes == 5: + build_part = parts[2] + build_match = _build_tag_regex.match(build_part) + if build_match is None: + raise InvalidWheelFilename( + f"Invalid build number: {build_part} in {filename!r}" + ) + build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2))) + else: + build = () + tags = parse_tag(parts[-1]) + return (name, version, build, tags) + + +def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: + if filename.endswith(".tar.gz"): + file_stem = filename[: -len(".tar.gz")] + elif filename.endswith(".zip"): + file_stem = filename[: -len(".zip")] + else: + raise InvalidSdistFilename( + f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" + f" {filename!r}" + ) + + # We are requiring a PEP 440 version, which cannot contain dashes, + # so we split on the last dash. + name_part, sep, version_part = file_stem.rpartition("-") + if not sep: + raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") + + name = canonicalize_name(name_part) + + try: + version = Version(version_part) + except InvalidVersion as e: + raise InvalidSdistFilename( + f"Invalid sdist filename (invalid version): {filename!r}" + ) from e + + return (name, version) diff --git a/data/miniconda3/lib/python3.13/site-packages/packaging/version.py b/data/miniconda3/lib/python3.13/site-packages/packaging/version.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bbda20e463b8d9389ecd65f74af33810a02bdd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/packaging/version.py @@ -0,0 +1,582 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.version import parse, Version +""" + +from __future__ import annotations + +import itertools +import re +from typing import Any, Callable, NamedTuple, SupportsInt, Tuple, Union + +from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType + +__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"] + +LocalType = Tuple[Union[int, str], ...] + +CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] +CmpLocalType = Union[ + NegativeInfinityType, + Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], +] +CmpKey = Tuple[ + int, + Tuple[int, ...], + CmpPrePostDevType, + CmpPrePostDevType, + CmpPrePostDevType, + CmpLocalType, +] +VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] + + +class _Version(NamedTuple): + epoch: int + release: tuple[int, ...] + dev: tuple[str, int] | None + pre: tuple[str, int] | None + post: tuple[str, int] | None + local: LocalType | None + + +def parse(version: str) -> Version: + """Parse the given version string. + + >>> parse('1.0.dev1') + + + :param version: The version string to parse. + :raises InvalidVersion: When the version string is not a valid version. + """ + return Version(version) + + +class InvalidVersion(ValueError): + """Raised when a version string is not a valid version. + + >>> Version("invalid") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'invalid' + """ + + +class _BaseVersion: + _key: tuple[Any, ...] + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +_VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+VERSION_PATTERN = _VERSION_PATTERN
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+:meta hide-value:
+"""
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+    """
+
+    _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
+    _key: CmpKey
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: {version!r}")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
+            post=_parse_letter_version(
+                match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+            ),
+            dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f""
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be round-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        # Pre-release
+        if self.pre is not None:
+            parts.append("".join(str(x) for x in self.pre))
+
+        # Post-release
+        if self.post is not None:
+            parts.append(f".post{self.post}")
+
+        # Development release
+        if self.dev is not None:
+            parts.append(f".dev{self.dev}")
+
+        # Local version segment
+        if self.local is not None:
+            parts.append(f"+{self.local}")
+
+        return "".join(parts)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._version.epoch
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._version.release
+
+    @property
+    def pre(self) -> tuple[str, int] | None:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._version.pre
+
+    @property
+    def post(self) -> int | None:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._version.post[1] if self._version.post else None
+
+    @property
+    def dev(self) -> int | None:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._version.dev[1] if self._version.dev else None
+
+    @property
+    def local(self) -> str | None:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._version.local:
+            return ".".join(str(x) for x in self._version.local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").public
+        '1!1.2.3.dev1'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        parts = []
+
+        # Epoch
+        if self.epoch != 0:
+            parts.append(f"{self.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self.release))
+
+        return "".join(parts)
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+class _TrimmedRelease(Version):
+    @property
+    def release(self) -> tuple[int, ...]:
+        """
+        Release segment without any trailing zeros.
+
+        >>> _TrimmedRelease('1.0.0').release
+        (1,)
+        >>> _TrimmedRelease('0.0').release
+        (0,)
+        """
+        rel = super().release
+        nonzeros = (index for index, val in enumerate(rel) if val)
+        last_nonzero = max(nonzeros, default=0)
+        return rel[: last_nonzero + 1]
+
+
+def _parse_letter_version(
+    letter: str | None, number: str | bytes | SupportsInt | None
+) -> tuple[str, int] | None:
+    if letter:
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+
+    assert not letter
+    if number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str | None) -> LocalType | None:
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+def _cmpkey(
+    epoch: int,
+    release: tuple[int, ...],
+    pre: tuple[str, int] | None,
+    post: tuple[str, int] | None,
+    dev: tuple[str, int] | None,
+    local: LocalType | None,
+) -> CmpKey:
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non zero, then take the rest
+    # re-reverse it back into the correct order and make it a tuple and use
+    # that for our sorting key.
+    _release = tuple(
+        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre segment, but we _only_ want to do this
+    # if there is not a pre or a post segment. If we have one of those then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        _pre: CmpPrePostDevType = NegativeInfinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        _pre = Infinity
+    else:
+        _pre = pre
+
+    # Versions without a post segment should sort before those with one.
+    if post is None:
+        _post: CmpPrePostDevType = NegativeInfinity
+
+    else:
+        _post = post
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        _dev: CmpPrePostDevType = Infinity
+
+    else:
+        _dev = dev
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        _local: CmpLocalType = NegativeInfinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alpha numeric segments sort before numeric segments
+        # - Alpha numeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        _local = tuple(
+            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
+        )
+
+    return epoch, _release, _pre, _post, _dev, _local
diff --git a/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
\ No newline at end of file
diff --git a/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..c3f7d1d33b9736fb44c73d76dff769efe3b2db4a
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/METADATA
@@ -0,0 +1,111 @@
+Metadata-Version: 2.4
+Name: pip
+Version: 25.3
+Summary: The PyPA recommended tool for installing Python packages.
+Author-email: The pip developers 
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-Expression: MIT
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Topic :: Software Development :: Build Tools
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+License-File: AUTHORS.txt
+License-File: LICENSE.txt
+License-File: src/pip/_vendor/cachecontrol/LICENSE.txt
+License-File: src/pip/_vendor/certifi/LICENSE
+License-File: src/pip/_vendor/dependency_groups/LICENSE.txt
+License-File: src/pip/_vendor/distlib/LICENSE.txt
+License-File: src/pip/_vendor/distro/LICENSE
+License-File: src/pip/_vendor/idna/LICENSE.md
+License-File: src/pip/_vendor/msgpack/COPYING
+License-File: src/pip/_vendor/packaging/LICENSE
+License-File: src/pip/_vendor/packaging/LICENSE.APACHE
+License-File: src/pip/_vendor/packaging/LICENSE.BSD
+License-File: src/pip/_vendor/pkg_resources/LICENSE
+License-File: src/pip/_vendor/platformdirs/LICENSE
+License-File: src/pip/_vendor/pygments/LICENSE
+License-File: src/pip/_vendor/pyproject_hooks/LICENSE
+License-File: src/pip/_vendor/requests/LICENSE
+License-File: src/pip/_vendor/resolvelib/LICENSE
+License-File: src/pip/_vendor/rich/LICENSE
+License-File: src/pip/_vendor/tomli/LICENSE
+License-File: src/pip/_vendor/tomli_w/LICENSE
+License-File: src/pip/_vendor/truststore/LICENSE
+License-File: src/pip/_vendor/urllib3/LICENSE.txt
+Project-URL: Changelog, https://pip.pypa.io/en/stable/news/
+Project-URL: Documentation, https://pip.pypa.io
+Project-URL: Homepage, https://pip.pypa.io/
+Project-URL: Source, https://github.com/pypa/pip
+
+pip - The Python Package Installer
+==================================
+
+.. |pypi-version| image:: https://img.shields.io/pypi/v/pip.svg
+   :target: https://pypi.org/project/pip/
+   :alt: PyPI
+
+.. |python-versions| image:: https://img.shields.io/pypi/pyversions/pip
+   :target: https://pypi.org/project/pip
+   :alt: PyPI - Python Version
+
+.. |docs-badge| image:: https://readthedocs.org/projects/pip/badge/?version=latest
+   :target: https://pip.pypa.io/en/latest
+   :alt: Documentation
+
+|pypi-version| |python-versions| |docs-badge|
+
+pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.
+
+Please take a look at our documentation for how to install and use pip:
+
+* `Installation`_
+* `Usage`_
+
+We release updates regularly, with a new version every 3 months. Find more details in our documentation:
+
+* `Release notes`_
+* `Release process`_
+
+If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
+
+* `Issue tracking`_
+* `Discourse channel`_
+* `User IRC`_
+
+If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:
+
+* `GitHub page`_
+* `Development documentation`_
+* `Development IRC`_
+
+Code of Conduct
+---------------
+
+Everyone interacting in the pip project's codebases, issue trackers, chat
+rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
+
+.. _package installer: https://packaging.python.org/guides/tool-recommendations/
+.. _Python Package Index: https://pypi.org
+.. _Installation: https://pip.pypa.io/en/stable/installation/
+.. _Usage: https://pip.pypa.io/en/stable/
+.. _Release notes: https://pip.pypa.io/en/stable/news.html
+.. _Release process: https://pip.pypa.io/en/latest/development/release-process/
+.. _GitHub page: https://github.com/pypa/pip
+.. _Development documentation: https://pip.pypa.io/en/latest/development
+.. _Issue tracking: https://github.com/pypa/pip/issues
+.. _Discourse channel: https://discuss.python.org/c/packaging
+.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa
+.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev
+.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
+
diff --git a/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..f5fa82f51ac742a39373689a7638511722bfdc7d
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/RECORD
@@ -0,0 +1,873 @@
+../../../bin/pip,sha256=txeBzKO9QDADcL0DeuZDgw-QwokIiFQZMB8HSlIFlBE,477
+../../../bin/pip3,sha256=txeBzKO9QDADcL0DeuZDgw-QwokIiFQZMB8HSlIFlBE,477
+../../../bin/pip3.13,sha256=txeBzKO9QDADcL0DeuZDgw-QwokIiFQZMB8HSlIFlBE,477
+pip-25.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pip-25.3.dist-info/METADATA,sha256=Khugcl59I2--LVxQpP_5yeP-NMpJTyzr3lxFw3kTedM,4672
+pip-25.3.dist-info/RECORD,,
+pip-25.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip-25.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+pip-25.3.dist-info/direct_url.json,sha256=zovFyNzAS7mmMhxuiLe9zDDt7V2ua1lMgBtWfatm9i0,93
+pip-25.3.dist-info/entry_points.txt,sha256=Vhf8s0IYgX37mtd4vGL73BPcxdKnqeCFPzB5-d30x8o,84
+pip-25.3.dist-info/licenses/AUTHORS.txt,sha256=H32ZhgFn-q5b3BAcDYqsSw0NN7RRVYHpWiNVNHQzzBs,11503
+pip-25.3.dist-info/licenses/LICENSE.txt,sha256=Y0MApmnUmurmWxLGxIySTFGkzfPR_whtw0VtyLyqIQQ,1093
+pip-25.3.dist-info/licenses/src/pip/_vendor/cachecontrol/LICENSE.txt,sha256=hu7uh74qQ_P_H1ZJb0UfaSQ5JvAl_tuwM2ZsMExMFhs,558
+pip-25.3.dist-info/licenses/src/pip/_vendor/certifi/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
+pip-25.3.dist-info/licenses/src/pip/_vendor/dependency_groups/LICENSE.txt,sha256=GrNuPipLqGMWJThPh-ngkdsfrtA0xbIzJbMjmr8sxSU,1099
+pip-25.3.dist-info/licenses/src/pip/_vendor/distlib/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531
+pip-25.3.dist-info/licenses/src/pip/_vendor/distro/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325
+pip-25.3.dist-info/licenses/src/pip/_vendor/idna/LICENSE.md,sha256=pZ8LDvNjWHQQmkRhykT_enDVBpboFHZ7-vch1Mmw2w8,1541
+pip-25.3.dist-info/licenses/src/pip/_vendor/msgpack/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614
+pip-25.3.dist-info/licenses/src/pip/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
+pip-25.3.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
+pip-25.3.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
+pip-25.3.dist-info/licenses/src/pip/_vendor/pkg_resources/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+pip-25.3.dist-info/licenses/src/pip/_vendor/platformdirs/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+pip-25.3.dist-info/licenses/src/pip/_vendor/pygments/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331
+pip-25.3.dist-info/licenses/src/pip/_vendor/pyproject_hooks/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081
+pip-25.3.dist-info/licenses/src/pip/_vendor/requests/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
+pip-25.3.dist-info/licenses/src/pip/_vendor/resolvelib/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
+pip-25.3.dist-info/licenses/src/pip/_vendor/rich/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056
+pip-25.3.dist-info/licenses/src/pip/_vendor/tomli/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+pip-25.3.dist-info/licenses/src/pip/_vendor/tomli_w/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+pip-25.3.dist-info/licenses/src/pip/_vendor/truststore/LICENSE,sha256=M757fo-k_Rmxdg4ajtimaL2rhSyRtpLdQUJLy3Jan8o,1086
+pip-25.3.dist-info/licenses/src/pip/_vendor/urllib3/LICENSE.txt,sha256=w3vxhuJ8-dvpYZ5V7f486nswCRzrPaY8fay-Dm13kHs,1115
+pip/__init__.py,sha256=vSLqqJJ91-qXOz5tXjaPnwj5TDBz-Ujn8I7ymNmdvtA,353
+pip/__main__.py,sha256=WzbhHXTbSE6gBY19mNN9m4s5o_365LOvTYSgqgbdBhE,854
+pip/__pip-runner__.py,sha256=JOoEZTwrtv7jRaXBkgSQKAE04yNyfFmGHxqpHiGHvL0,1450
+pip/__pycache__/__init__.cpython-313.pyc,,
+pip/__pycache__/__main__.cpython-313.pyc,,
+pip/__pycache__/__pip-runner__.cpython-313.pyc,,
+pip/_internal/__init__.py,sha256=S7i9Dn9aSZS0MG-2Wrve3dV9TImPzvQn5jjhp9t_uf0,511
+pip/_internal/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/__pycache__/build_env.cpython-313.pyc,,
+pip/_internal/__pycache__/cache.cpython-313.pyc,,
+pip/_internal/__pycache__/configuration.cpython-313.pyc,,
+pip/_internal/__pycache__/exceptions.cpython-313.pyc,,
+pip/_internal/__pycache__/main.cpython-313.pyc,,
+pip/_internal/__pycache__/pyproject.cpython-313.pyc,,
+pip/_internal/__pycache__/self_outdated_check.cpython-313.pyc,,
+pip/_internal/__pycache__/wheel_builder.cpython-313.pyc,,
+pip/_internal/build_env.py,sha256=oMRORdlWoHC591opA21PixmMykfhOfHw7P1MM7JgSrQ,14201
+pip/_internal/cache.py,sha256=nMh48Yv3yu1HS1yCdscouu6B6B5zYBWdV6bhqs7gL-E,10345
+pip/_internal/cli/__init__.py,sha256=Iqg_tKA771XuMO1P4t_sDHnSKPzkUb9D0DqunAmw_ko,131
+pip/_internal/cli/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/autocompletion.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/base_command.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/cmdoptions.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/command_context.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/index_command.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/main.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/main_parser.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/parser.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/progress_bars.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/req_command.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/spinners.cpython-313.pyc,,
+pip/_internal/cli/__pycache__/status_codes.cpython-313.pyc,,
+pip/_internal/cli/autocompletion.py,sha256=ZG2cM03nlcNrs-WG_SFTW46isx9s2Go5lUD_8-iv70o,7193
+pip/_internal/cli/base_command.py,sha256=1Nx919JRFlgURLis9XYJwtbyEEjRJa_NdHwM6iBkZvY,8716
+pip/_internal/cli/cmdoptions.py,sha256=2vOdyIS6NjzycGT5idxKxxOsfw6TgR43CRe2lStYYL0,31025
+pip/_internal/cli/command_context.py,sha256=kmu3EWZbfBega1oDamnGJTA_UaejhIQNuMj2CVmMXu0,817
+pip/_internal/cli/index_command.py,sha256=AHk6eSqboaxTXbG3v9mBrVd0dCK1MtW4w3PVudnj0WE,5717
+pip/_internal/cli/main.py,sha256=K9PtpRdg6uBrVKk8S2VZ14fAN0kP-cnA1o-FtJCN_OQ,2815
+pip/_internal/cli/main_parser.py,sha256=UugPD-hF1WtNQdow_WWduDLUH1DvElpc7EeUWjUkcNo,4329
+pip/_internal/cli/parser.py,sha256=B9PpyPy6iY9LMvkKJygJ-3PwQLG6DoirWa-Mhv3nVlE,10916
+pip/_internal/cli/progress_bars.py,sha256=nRTWNof-FjHfvirvECXIh7T7eAynTUVPTyHENfpbWiU,4668
+pip/_internal/cli/req_command.py,sha256=HNANn7-hDIIFiRTUbudj5oRfPWC9Kf2ukG3feYANx94,13799
+pip/_internal/cli/spinners.py,sha256=EJzZIZNyUtJljp3-WjcsyIrqxW-HUsfWzhuW84n_Tqw,7362
+pip/_internal/cli/status_codes.py,sha256=sEFHUaUJbqv8iArL3HAtcztWZmGOFX01hTesSytDEh0,116
+pip/_internal/commands/__init__.py,sha256=aNeCbQurGWihfhQq7BqaLXHqWDQ0i3I04OS7kxK6plQ,4026
+pip/_internal/commands/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/cache.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/check.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/completion.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/configuration.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/debug.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/download.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/freeze.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/hash.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/help.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/index.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/inspect.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/install.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/list.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/lock.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/search.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/show.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/uninstall.cpython-313.pyc,,
+pip/_internal/commands/__pycache__/wheel.cpython-313.pyc,,
+pip/_internal/commands/cache.py,sha256=OrrLS6EJEha_55yPa9fTaOaonw-VpH4_lVhjxuOTChQ,8230
+pip/_internal/commands/check.py,sha256=hVFBQezQ3zj4EydoWbFQj_afPUppMt7r9JPAlY22U6Y,2244
+pip/_internal/commands/completion.py,sha256=MDwhTOBjlM4WEbOhgbhrWnlDm710i4FMjop3RBXXXCc,4530
+pip/_internal/commands/configuration.py,sha256=6gNOGrVWnOLU15zUnAiNuOMhf76RRIZvCdVD0degPRk,10105
+pip/_internal/commands/debug.py,sha256=_8IqM8Fx1_lY2STu_qspr63tufF7zyFJCyYAXtxz0N4,6805
+pip/_internal/commands/download.py,sha256=pvB7I36z6soLPfv4IMwNRHn1WvY8I7zzM2h5se3nV6s,5075
+pip/_internal/commands/freeze.py,sha256=fxoW8AAc-bAqB_fXdNq2VnZ3JfWkFMg-bR6LcdDVO7A,3099
+pip/_internal/commands/hash.py,sha256=GO9pRN3wXC2kQaovK57TaLYBMc3IltOH92O6QEw6YE0,1679
+pip/_internal/commands/help.py,sha256=Bz3LcjNQXkz4Cu__pL4CZ86o4-HNLZj1NZWdlJhjuu0,1108
+pip/_internal/commands/index.py,sha256=8GMBVI5NvhRRHBSUq27YxDIE02DpvdJ_6qiBFgGd1co,5243
+pip/_internal/commands/inspect.py,sha256=ogm4UT7LRo8bIQcWUS1IiA25QdD4VHLa7JaPAodDttM,3177
+pip/_internal/commands/install.py,sha256=oUlST7YwoeuAE6IzWokkZk8IccSj39HT0ypQBOPj2fM,30472
+pip/_internal/commands/list.py,sha256=I4ZH604E5gpcROxEXA7eyaNEFhXx3VFVqvpscz_Ps_A,13514
+pip/_internal/commands/lock.py,sha256=5m0PskQFMuP1cYQYGfSiBLa81a8MDflUTC-iUsOU1u0,5797
+pip/_internal/commands/search.py,sha256=zbMsX_YASj6kXA6XIBgTDv0bGK51xG-CV3IynZJcE-c,5782
+pip/_internal/commands/show.py,sha256=oLVJIfKWmDKm0SsQGEi3pozNiqrXjTras_fbBSYKpBA,8066
+pip/_internal/commands/uninstall.py,sha256=CsOihqvb6ZA6O67L70oXeoLHeOfNzMM88H9g-9aocgw,3868
+pip/_internal/commands/wheel.py,sha256=-kIyzy98nPejpPic-CpJk37PSFGFVhm5lJ1UO9Zpu2s,6013
+pip/_internal/configuration.py,sha256=WxwwSwY_Bm6QzDgf32BsujEyO8dgRedegCpgbUfDvM8,14568
+pip/_internal/distributions/__init__.py,sha256=Hq6kt6gXBgjNit5hTTWLAzeCNOKoB-N0pGYSqehrli8,858
+pip/_internal/distributions/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/distributions/__pycache__/base.cpython-313.pyc,,
+pip/_internal/distributions/__pycache__/installed.cpython-313.pyc,,
+pip/_internal/distributions/__pycache__/sdist.cpython-313.pyc,,
+pip/_internal/distributions/__pycache__/wheel.cpython-313.pyc,,
+pip/_internal/distributions/base.py,sha256=l-OTCAIs25lsapejA6IYpPZxSM5-BET4sdZDkql8jiY,1830
+pip/_internal/distributions/installed.py,sha256=kgIEE_1NzjZxLBSC-v5s64uOFZlVEt3aPrjTtL6x2XY,929
+pip/_internal/distributions/sdist.py,sha256=RYwQIbuxpKy6OjlBZCAefxpMDaoocUQ4dFtheGsiTOQ,6627
+pip/_internal/distributions/wheel.py,sha256=_HbG0OehF8dwj4UX-xV__tXLwgPus9OjMEf2NTRqBbE,1364
+pip/_internal/exceptions.py,sha256=lqnWPeAx3sbetkBbckbEtQ1UHhbWfX68HPCeqILJffU,29592
+pip/_internal/index/__init__.py,sha256=tzwMH_fhQeubwMqHdSivasg1cRgTSbNg2CiMVnzMmyU,29
+pip/_internal/index/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/index/__pycache__/collector.cpython-313.pyc,,
+pip/_internal/index/__pycache__/package_finder.cpython-313.pyc,,
+pip/_internal/index/__pycache__/sources.cpython-313.pyc,,
+pip/_internal/index/collector.py,sha256=PCB3thVWRiSBowGtpv1elIPFc-GvEqhZiNgZD7b0vBc,16185
+pip/_internal/index/package_finder.py,sha256=xjsftTB2JIlsCdxorDInoecJ6afs1O0lsqUg4ExcXI0,38835
+pip/_internal/index/sources.py,sha256=nXJkOjhLy-O2FsrKU9RIqCOqgY2PsoKWybtZjjRgqU0,8639
+pip/_internal/locations/__init__.py,sha256=2SADX0Gr9BIpx19AO7Feq89nOmBQGEbl1IWjBpnaE9E,14185
+pip/_internal/locations/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/locations/__pycache__/_distutils.cpython-313.pyc,,
+pip/_internal/locations/__pycache__/_sysconfig.cpython-313.pyc,,
+pip/_internal/locations/__pycache__/base.cpython-313.pyc,,
+pip/_internal/locations/_distutils.py,sha256=jpFj4V00rD9IR3vA9TqrGkwcdNVFc58LsChZavge9JY,5975
+pip/_internal/locations/_sysconfig.py,sha256=NhcEi1_25w9cTTcH4RyOjD4UHW6Ijks0uKy1PL1_j_8,7716
+pip/_internal/locations/base.py,sha256=AImjYJWxOtDkc0KKc6Y4Gz677cg91caMA4L94B9FZEg,2550
+pip/_internal/main.py,sha256=1cHqjsfFCrMFf3B5twzocxTJUdHMLoXUpy5lJoFqUi8,338
+pip/_internal/metadata/__init__.py,sha256=vp-JAxiWg_-l5F8AT0Jcey72uUnh8CDwwol9-KktHZ8,5824
+pip/_internal/metadata/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/metadata/__pycache__/_json.cpython-313.pyc,,
+pip/_internal/metadata/__pycache__/base.cpython-313.pyc,,
+pip/_internal/metadata/__pycache__/pkg_resources.cpython-313.pyc,,
+pip/_internal/metadata/_json.py,sha256=hNvnMHOXLAyNlzirWhPL9Nx2CvCqa1iRma6Osq1YfV8,2711
+pip/_internal/metadata/base.py,sha256=BGuMenlcQT8i7j9iclrfdC3vSwgvhr8gjn955cCy16s,25420
+pip/_internal/metadata/importlib/__init__.py,sha256=jUUidoxnHcfITHHaAWG1G2i5fdBYklv_uJcjo2x7VYE,135
+pip/_internal/metadata/importlib/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/metadata/importlib/__pycache__/_compat.cpython-313.pyc,,
+pip/_internal/metadata/importlib/__pycache__/_dists.cpython-313.pyc,,
+pip/_internal/metadata/importlib/__pycache__/_envs.cpython-313.pyc,,
+pip/_internal/metadata/importlib/_compat.py,sha256=sneVh4_6WxQZK4ljdl3ylVuP-q0ttSqbgl9mWt0HnOg,2804
+pip/_internal/metadata/importlib/_dists.py,sha256=znZD7MN4RC73-87KXAn6tKZv9lAQRI0AxxK2bubDvPw,8420
+pip/_internal/metadata/importlib/_envs.py,sha256=H3qVLXVh4LWvrPvu_ekXf3dfbtwnlhNJQP2pxXpccfU,5333
+pip/_internal/metadata/pkg_resources.py,sha256=NO76ZrfR2-LKJTyaXrmQoGhmJMArALvacrlZHViSDT8,10544
+pip/_internal/models/__init__.py,sha256=AjmCEBxX_MH9f_jVjIGNCFJKYCYeSEe18yyvNx4uRKQ,62
+pip/_internal/models/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/models/__pycache__/candidate.cpython-313.pyc,,
+pip/_internal/models/__pycache__/direct_url.cpython-313.pyc,,
+pip/_internal/models/__pycache__/format_control.cpython-313.pyc,,
+pip/_internal/models/__pycache__/index.cpython-313.pyc,,
+pip/_internal/models/__pycache__/installation_report.cpython-313.pyc,,
+pip/_internal/models/__pycache__/link.cpython-313.pyc,,
+pip/_internal/models/__pycache__/pylock.cpython-313.pyc,,
+pip/_internal/models/__pycache__/scheme.cpython-313.pyc,,
+pip/_internal/models/__pycache__/search_scope.cpython-313.pyc,,
+pip/_internal/models/__pycache__/selection_prefs.cpython-313.pyc,,
+pip/_internal/models/__pycache__/target_python.cpython-313.pyc,,
+pip/_internal/models/__pycache__/wheel.cpython-313.pyc,,
+pip/_internal/models/candidate.py,sha256=zzgFRuw_kWPjKpGw7LC0ZUMD2CQ2EberUIYs8izjdCA,753
+pip/_internal/models/direct_url.py,sha256=4NMWacu_QzPPWREC1te7v6Wfv-2HkI4tvSJF-CBgLh4,6555
+pip/_internal/models/format_control.py,sha256=PwemYG1L27BM0f1KP61rm24wShENFyxqlD1TWu34alc,2471
+pip/_internal/models/index.py,sha256=tYnL8oxGi4aSNWur0mG8DAP7rC6yuha_MwJO8xw0crI,1030
+pip/_internal/models/installation_report.py,sha256=cqfWJ93ThCxjcacqSWryOCD2XtIn1CZrgzZxAv5FQZ0,2839
+pip/_internal/models/link.py,sha256=DRBzBDJreUy1laeDOrG2aIyZDW_Lhr8zJjvYTi8mGYg,21793
+pip/_internal/models/pylock.py,sha256=Vmaa71gOSV0ZYzRgWiIm4KwVbClaahMcuvKCkP_ZznA,6211
+pip/_internal/models/scheme.py,sha256=PakmHJM3e8OOWSZFtfz1Az7f1meONJnkGuQxFlt3wBE,575
+pip/_internal/models/search_scope.py,sha256=1hxU2IVsAaLZVjp0CbzJbYaYzCxv72_Qbg3JL0qhXo0,4507
+pip/_internal/models/selection_prefs.py,sha256=lgYyo4W8lb22wsYx2ElBBB0cvSNlBVgucwBzL43dfzE,2016
+pip/_internal/models/target_python.py,sha256=I0eFS-eia3kwhrOvgsphFZtNAB2IwXZ9Sr9fp6IjBP4,4243
+pip/_internal/models/wheel.py,sha256=1SdfDvN7ALTsbyZ9EOsNy1GPirP1n6EjHyzPrZyLSh8,2920
+pip/_internal/network/__init__.py,sha256=FMy06P__y6jMjUc8z3ZcQdKF-pmZ2zM14_vBeHPGhUI,49
+pip/_internal/network/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/network/__pycache__/auth.cpython-313.pyc,,
+pip/_internal/network/__pycache__/cache.cpython-313.pyc,,
+pip/_internal/network/__pycache__/download.cpython-313.pyc,,
+pip/_internal/network/__pycache__/lazy_wheel.cpython-313.pyc,,
+pip/_internal/network/__pycache__/session.cpython-313.pyc,,
+pip/_internal/network/__pycache__/utils.cpython-313.pyc,,
+pip/_internal/network/__pycache__/xmlrpc.cpython-313.pyc,,
+pip/_internal/network/auth.py,sha256=uAwRGAYnVtgNSZm4HMC3BMACkgA7ku4m8wupiX6LpK8,20681
+pip/_internal/network/cache.py,sha256=kmRXKQrG9E26xQRj211LHeEGpDg_SlYU9Dn1fJ-AMeI,4862
+pip/_internal/network/download.py,sha256=HgsFvTkPDdgg0zUehose_J-542-9R0FpyipRw5BhxAM,12682
+pip/_internal/network/lazy_wheel.py,sha256=y9gVksdJCSjnLfYzs_m3DYUAtl3hc_k-xFPDBd9DgOs,7646
+pip/_internal/network/session.py,sha256=eE-VUIJGU9YeeaVy7tVAvMRWigMsyuAMpxkjlbptbjo,19188
+pip/_internal/network/utils.py,sha256=ACsXd1msqNCidHVXsu7LHUSr8NgaypcOKQ4KG-Z_wJM,4091
+pip/_internal/network/xmlrpc.py,sha256=_-Rnk3vOff8uF9hAGmT6SLALflY1gMBcbGwS12fb_Y4,1830
+pip/_internal/operations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/operations/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/operations/__pycache__/check.cpython-313.pyc,,
+pip/_internal/operations/__pycache__/freeze.cpython-313.pyc,,
+pip/_internal/operations/__pycache__/prepare.cpython-313.pyc,,
+pip/_internal/operations/build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/operations/build/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/operations/build/__pycache__/build_tracker.cpython-313.pyc,,
+pip/_internal/operations/build/__pycache__/metadata.cpython-313.pyc,,
+pip/_internal/operations/build/__pycache__/metadata_editable.cpython-313.pyc,,
+pip/_internal/operations/build/__pycache__/wheel.cpython-313.pyc,,
+pip/_internal/operations/build/__pycache__/wheel_editable.cpython-313.pyc,,
+pip/_internal/operations/build/build_tracker.py,sha256=W3b5cmkMWPaE6QIwfzsTayJo7-OlxFHWDxfPuax1KcE,4771
+pip/_internal/operations/build/metadata.py,sha256=INHaeiRfOiLYCXApfDNRo9Cw2xI4VwTc0KItvfdfOjk,1421
+pip/_internal/operations/build/metadata_editable.py,sha256=oWudMsnjy4loO_Jy7g4N9nxsnaEX_iDlVRgCy7pu1rs,1509
+pip/_internal/operations/build/wheel.py,sha256=3bP-nNiJ4S8JvMaBnyessXQUBhxTqt1GBx6DQ1iPJDY,1136
+pip/_internal/operations/build/wheel_editable.py,sha256=q3kfElclM6FutVbFwE87JOTpVWt5ixDf3_UkHAIVfz4,1478
+pip/_internal/operations/check.py,sha256=yC2XWth6iehGGE_fj7XRJLjVKBsTIG3ZoWRkFi3rOwc,5894
+pip/_internal/operations/freeze.py,sha256=PDdY-y_ZtZZJLAKcaWPIGRKAGW7DXR48f0aMRU0j7BA,9854
+pip/_internal/operations/install/__init__.py,sha256=ak-UETcQPKlFZaWoYKWu5QVXbpFBvg0sXc3i0O4vSYY,50
+pip/_internal/operations/install/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/operations/install/__pycache__/wheel.cpython-313.pyc,,
+pip/_internal/operations/install/wheel.py,sha256=8aepxxAFmnzZFtcMCv-1I4T_maEkQd4hXZztYWE4yR0,27956
+pip/_internal/operations/prepare.py,sha256=PajSUvp7jMWSEC7sLPaBdKWv7sioYVdoB0JEWEorLsw,28914
+pip/_internal/pyproject.py,sha256=J-sTWqC-XfsKQgz9m1bypMWZPHItsSHzIN_NWeIRmhM,4555
+pip/_internal/req/__init__.py,sha256=WcY9z7D3rlIKX1QY8_tRnAsS_poebiGGdtQ7EJ5JQQo,3041
+pip/_internal/req/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/req/__pycache__/constructors.cpython-313.pyc,,
+pip/_internal/req/__pycache__/req_dependency_group.cpython-313.pyc,,
+pip/_internal/req/__pycache__/req_file.cpython-313.pyc,,
+pip/_internal/req/__pycache__/req_install.cpython-313.pyc,,
+pip/_internal/req/__pycache__/req_set.cpython-313.pyc,,
+pip/_internal/req/__pycache__/req_uninstall.cpython-313.pyc,,
+pip/_internal/req/constructors.py,sha256=Z4C41AHuF7YZFzsqTQXFEgXmUdACeUeakf8hLZEQr-E,18581
+pip/_internal/req/req_dependency_group.py,sha256=0yEQCUaO5Bza66Y3D5o9JRf0qII5QgCRugn1x5aRivA,2618
+pip/_internal/req/req_file.py,sha256=syUNcsC-AlOFofoBwxUI1Vf6FCReyBvZ_AHyvpuGWas,20130
+pip/_internal/req/req_install.py,sha256=vv5cbs3P5gf43e_1v72gwSQ2N_D_qpsfuXOyerMhDuI,31273
+pip/_internal/req/req_set.py,sha256=awkqIXnYA4Prmsj0Qb3zhqdbYUmXd-1o0P-KZ3mvRQs,2828
+pip/_internal/req/req_uninstall.py,sha256=dCmOHt-9RaJBq921L4tMH3PmIBDetGplnbjRKXmGt00,24099
+pip/_internal/resolution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/resolution/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/resolution/__pycache__/base.cpython-313.pyc,,
+pip/_internal/resolution/base.py,sha256=RIsqSP79olPdOgtPKW-oOQ364ICVopehA6RfGkRfe2s,577
+pip/_internal/resolution/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/resolution/legacy/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/resolution/legacy/__pycache__/resolver.cpython-313.pyc,,
+pip/_internal/resolution/legacy/resolver.py,sha256=bwUqE66etz2bcPabqxed18-iyqqb-kx3Er2aT6GeUJY,24060
+pip/_internal/resolution/resolvelib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/base.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-313.pyc,,
+pip/_internal/resolution/resolvelib/base.py,sha256=_AoP0ZWlaSct8CRDn2ol3CbNn4zDtnh_0zQGjXASDKI,5047
+pip/_internal/resolution/resolvelib/candidates.py,sha256=50AN7BfB-pCfEmbKNlFZSXtdC0C8ms1waJrF2arknQE,20454
+pip/_internal/resolution/resolvelib/factory.py,sha256=6rZjvJdcLvsCqNjPfHNAiGVKUzju31Z3OFlhmAjU7As,33628
+pip/_internal/resolution/resolvelib/found_candidates.py,sha256=8bZYDCZLXSdLHy_s1o5f4r15HmKvqFUhzBUQOF21Lr4,6018
+pip/_internal/resolution/resolvelib/provider.py,sha256=tbVPfFv4Vg780yZ2_XGoGFP5LVo0U2bFnZov3jpSAIk,11441
+pip/_internal/resolution/resolvelib/reporter.py,sha256=faSgjqme0k_uzv1fvM5T0ZatPQ2eEktNvKBqfvXeGjc,3909
+pip/_internal/resolution/resolvelib/requirements.py,sha256=z0gXmWfo03ynOnhF8kpj5SycgroerDhQV0VWzmAKAfg,8076
+pip/_internal/resolution/resolvelib/resolver.py,sha256=wQ94Hkep-7kWEHAc-NbMJhmzeEzgEAtxeBxyKVzZoeo,13437
+pip/_internal/self_outdated_check.py,sha256=Ghi_sifu9uf9QNSLto1reWU7bU-aj6i_dxpyfK1ih-k,8471
+pip/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_internal/utils/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/_jaraco_text.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/_log.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/appdirs.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/compat.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/compatibility_tags.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/datetime.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/deprecation.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/direct_url_helpers.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/egg_link.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/entrypoints.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/filesystem.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/filetypes.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/glibc.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/hashes.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/logging.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/misc.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/packaging.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/retry.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/subprocess.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/temp_dir.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/unpacking.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/urls.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/virtualenv.cpython-313.pyc,,
+pip/_internal/utils/__pycache__/wheel.cpython-313.pyc,,
+pip/_internal/utils/_jaraco_text.py,sha256=M15uUPIh5NpP1tdUGBxRau6q1ZAEtI8-XyLEETscFfE,3350
+pip/_internal/utils/_log.py,sha256=-jHLOE_THaZz5BFcCnoSL9EYAtJ0nXem49s9of4jvKw,1015
+pip/_internal/utils/appdirs.py,sha256=LrzDPZMKVh0rubtCx9vu3XlZbLCSug6VSj4Qsvt66BA,1681
+pip/_internal/utils/compat.py,sha256=C9LHXJAKkwAH8Hn3nPkz9EYK3rqPBeO_IXkOG2zzsdQ,2514
+pip/_internal/utils/compatibility_tags.py,sha256=DiNSLqpuruXUamGQwOJ2WZByDGLTGaXi9O-Xf8fOi34,6630
+pip/_internal/utils/datetime.py,sha256=Gt29Ml4ToPSM88j54iu43WKtrU9A-moP4QmMiiqzedU,241
+pip/_internal/utils/deprecation.py,sha256=HVhvyO5qiRFcG88PhZlp_87qdKQNwPTUIIHWtsTR2yI,3696
+pip/_internal/utils/direct_url_helpers.py,sha256=ttKv4GMUqlRwPPog9_CUopy6SDgoxVILzeBJzgfn2tg,3200
+pip/_internal/utils/egg_link.py,sha256=YWfsrbmfcrfWgqQYy6OuIjsyb9IfL1q_2v4zsms1WjI,2459
+pip/_internal/utils/entrypoints.py,sha256=uPjAyShKObdotjQjJUzprQ6r3xQvDIZwUYfHHqZ7Dok,3324
+pip/_internal/utils/filesystem.py,sha256=csVIpuOQnlOnApQOflj_AQAOSiYm_DUr3VZhv7zhtUM,5497
+pip/_internal/utils/filetypes.py,sha256=sEMa38qaqjvx1Zid3OCAUja31BOBU-USuSMPBvU3yjo,689
+pip/_internal/utils/glibc.py,sha256=sEh8RJJLYSdRvTqAO4THVPPA-YSDVLD4SI9So-bxX1U,3726
+pip/_internal/utils/hashes.py,sha256=d32UI1en8nyqZzdZQvxUVdfeBoe4ADWx7HtrIM4-XQ4,4998
+pip/_internal/utils/logging.py,sha256=RtRe7Vp0COC4UBewYdfKicXjCTmHXpDZHdReTzJvB78,12108
+pip/_internal/utils/misc.py,sha256=1jEpqjfqYmQ6K3D4_O8xXSPn8aEfH2uMOlNM7KPvSrg,23374
+pip/_internal/utils/packaging.py,sha256=s5tpUmFumwV0H9JSTzryrIY4JwQM8paGt7Sm7eNwt2Y,1601
+pip/_internal/utils/retry.py,sha256=83wReEB2rcntMZ5VLd7ascaYSjn_kLdlQCqxILxWkPM,1461
+pip/_internal/utils/subprocess.py,sha256=r4-Ba_Yc3uZXQpi0K4pZFsCT_QqdSvtF3XJ-204QWaA,8983
+pip/_internal/utils/temp_dir.py,sha256=D9c8D7WOProOO8GGDqpBeVSj10NGFmunG0o2TodjjIU,9307
+pip/_internal/utils/unpacking.py,sha256=ab1KcniWQR-K8YyyCL0b_JiPUVh7vOPmLQK5YTGNaLo,12974
+pip/_internal/utils/urls.py,sha256=aF_eg9ul5d8bMCxfSSSxQcfs-OpJdbStYqZHoy2K1RE,1601
+pip/_internal/utils/virtualenv.py,sha256=mX-UPyw1MPxhwUxKhbqWWX70J6PHXAJjVVrRnG0h9mc,3455
+pip/_internal/utils/wheel.py,sha256=YdRuj6MicG-Q9Mg03FbUv1WTLam6Lc7AgijY4voVyis,4468
+pip/_internal/vcs/__init__.py,sha256=UAqvzpbi0VbZo3Ub6skEeZAw-ooIZR-zX_WpCbxyCoU,596
+pip/_internal/vcs/__pycache__/__init__.cpython-313.pyc,,
+pip/_internal/vcs/__pycache__/bazaar.cpython-313.pyc,,
+pip/_internal/vcs/__pycache__/git.cpython-313.pyc,,
+pip/_internal/vcs/__pycache__/mercurial.cpython-313.pyc,,
+pip/_internal/vcs/__pycache__/subversion.cpython-313.pyc,,
+pip/_internal/vcs/__pycache__/versioncontrol.cpython-313.pyc,,
+pip/_internal/vcs/bazaar.py,sha256=3W1eHjkYx2vc6boeb2NBh4I_rlGAXM-vrzfNhLm1Rxg,3734
+pip/_internal/vcs/git.py,sha256=TTeqDuzS-_BFSNuUStVWmE2nGDpKuvUhBBJk_CCQXV0,19144
+pip/_internal/vcs/mercurial.py,sha256=w1ZJWLKqNP1onEjkfjlwBVnMqPZNSIER8ayjQcnTq4w,5575
+pip/_internal/vcs/subversion.py,sha256=uUgdPvxmvEB8Qwtjr0Hc0XgFjbiNi5cbvI4vARLOJXo,11787
+pip/_internal/vcs/versioncontrol.py,sha256=d-v1mcLxofg2FaIqBrV-e-ZcjOgQhS0oxXpki1v1yXs,22502
+pip/_internal/wheel_builder.py,sha256=yvEULStZtty9Kplp89tDis3hGdyKQ-2BUbFLmJ_5ink,9010
+pip/_vendor/README.rst,sha256=pKKBwCWhu3M3qQ9dDnsmxb3KdsRr-nWmMq2srbH_Bi0,9394
+pip/_vendor/__init__.py,sha256=WzusPTGWIMeQQWSVJ0h2rafGkVTa9WKJ2HT-2-EoZrU,4907
+pip/_vendor/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/cachecontrol/LICENSE.txt,sha256=hu7uh74qQ_P_H1ZJb0UfaSQ5JvAl_tuwM2ZsMExMFhs,558
+pip/_vendor/cachecontrol/__init__.py,sha256=BF2n5OeQz1QW2xSey2LxfNCtwbjnTadXdIH2toqJecg,677
+pip/_vendor/cachecontrol/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-313.pyc,,
+pip/_vendor/cachecontrol/__pycache__/adapter.cpython-313.pyc,,
+pip/_vendor/cachecontrol/__pycache__/cache.cpython-313.pyc,,
+pip/_vendor/cachecontrol/__pycache__/controller.cpython-313.pyc,,
+pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-313.pyc,,
+pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-313.pyc,,
+pip/_vendor/cachecontrol/__pycache__/serialize.cpython-313.pyc,,
+pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-313.pyc,,
+pip/_vendor/cachecontrol/_cmd.py,sha256=iist2EpzJvDVIhMAxXq8iFnTBsiZAd6iplxfmNboNyk,1737
+pip/_vendor/cachecontrol/adapter.py,sha256=8y6rTPXOzVHmDKCW5CR9sivLVuDv-cpdGcZYdRWNaPw,6599
+pip/_vendor/cachecontrol/cache.py,sha256=OXwv7Fn2AwnKNiahJHnjtvaKLndvVLv_-zO-ltlV9qI,1953
+pip/_vendor/cachecontrol/caches/__init__.py,sha256=dtrrroK5BnADR1GWjCZ19aZ0tFsMfvFBtLQQU1sp_ag,303
+pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-313.pyc,,
+pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-313.pyc,,
+pip/_vendor/cachecontrol/caches/file_cache.py,sha256=d8upFmy_zwaCmlbWEVBlLXFddt8Zw8c5SFpxeOZsdfw,4117
+pip/_vendor/cachecontrol/caches/redis_cache.py,sha256=9rmqwtYu_ljVkW6_oLqbC7EaX_a8YT_yLuna-eS0dgo,1386
+pip/_vendor/cachecontrol/controller.py,sha256=cx0Hl8xLZgUuXuy78Gih9AYjCtqurmYjVJxyA4yWt7w,19101
+pip/_vendor/cachecontrol/filewrapper.py,sha256=2ktXNPE0KqnyzF24aOsKCA58HQq1xeC6l2g6_zwjghc,4291
+pip/_vendor/cachecontrol/heuristics.py,sha256=gqMXU8w0gQuEQiSdu3Yg-0vd9kW7nrWKbLca75rheGE,4881
+pip/_vendor/cachecontrol/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/cachecontrol/serialize.py,sha256=HQd2IllQ05HzPkVLMXTF2uX5mjEQjDBkxCqUJUODpZk,5163
+pip/_vendor/cachecontrol/wrapper.py,sha256=hsGc7g8QGQTT-4f8tgz3AM5qwScg6FO0BSdLSRdEvpU,1417
+pip/_vendor/certifi/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
+pip/_vendor/certifi/__init__.py,sha256=jWkaYHMk4oIPSSBEK5bLMbO_qrkyNm_cRFx-D16-3Ks,94
+pip/_vendor/certifi/__main__.py,sha256=1k3Cr95vCxxGRGDljrW3wMdpZdL3Nhf0u1n-k2qdsCY,255
+pip/_vendor/certifi/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/certifi/__pycache__/__main__.cpython-313.pyc,,
+pip/_vendor/certifi/__pycache__/core.cpython-313.pyc,,
+pip/_vendor/certifi/cacert.pem,sha256=IIn8WiWDZAH67pn3IkYLAbOTmZdGoPuBeUNmbW7MBFg,291366
+pip/_vendor/certifi/core.py,sha256=gu_ECVI1m3Rq0ytpsNE61hgQGcKaOAt9Rs9G8KsTCOI,3442
+pip/_vendor/certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/dependency_groups/LICENSE.txt,sha256=GrNuPipLqGMWJThPh-ngkdsfrtA0xbIzJbMjmr8sxSU,1099
+pip/_vendor/dependency_groups/__init__.py,sha256=C3OFu0NGwDzQ4LOmmSOFPsRSvkbBn-mdd4j_5YqJw-s,250
+pip/_vendor/dependency_groups/__main__.py,sha256=UNTM7P5mfVtT7wDi9kOTXWgV3fu3e8bTrt1Qp1jvjKo,1709
+pip/_vendor/dependency_groups/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/dependency_groups/__pycache__/__main__.cpython-313.pyc,,
+pip/_vendor/dependency_groups/__pycache__/_implementation.cpython-313.pyc,,
+pip/_vendor/dependency_groups/__pycache__/_lint_dependency_groups.cpython-313.pyc,,
+pip/_vendor/dependency_groups/__pycache__/_pip_wrapper.cpython-313.pyc,,
+pip/_vendor/dependency_groups/__pycache__/_toml_compat.cpython-313.pyc,,
+pip/_vendor/dependency_groups/_implementation.py,sha256=Gqb2DlQELRakeHlKf6QtQSW0M-bcEomxHw4JsvID1ls,8041
+pip/_vendor/dependency_groups/_lint_dependency_groups.py,sha256=yp-DDqKXtbkDTNa0ifa-FmOA8ra24lPZEXftW-R5AuI,1710
+pip/_vendor/dependency_groups/_pip_wrapper.py,sha256=nuVW_w_ntVxpE26ELEvngMY0N04sFLsijXRyZZROFG8,1865
+pip/_vendor/dependency_groups/_toml_compat.py,sha256=BHnXnFacm3DeolsA35GjI6qkDApvua-1F20kv3BfZWE,285
+pip/_vendor/dependency_groups/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/distlib/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531
+pip/_vendor/distlib/__init__.py,sha256=Deo3uo98aUyIfdKJNqofeSEFWwDzrV2QeGLXLsgq0Ag,625
+pip/_vendor/distlib/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/distlib/__pycache__/compat.cpython-313.pyc,,
+pip/_vendor/distlib/__pycache__/resources.cpython-313.pyc,,
+pip/_vendor/distlib/__pycache__/scripts.cpython-313.pyc,,
+pip/_vendor/distlib/__pycache__/util.cpython-313.pyc,,
+pip/_vendor/distlib/compat.py,sha256=2jRSjRI4o-vlXeTK2BCGIUhkc6e9ZGhSsacRM5oseTw,41467
+pip/_vendor/distlib/resources.py,sha256=LwbPksc0A1JMbi6XnuPdMBUn83X7BPuFNWqPGEKI698,10820
+pip/_vendor/distlib/scripts.py,sha256=Qvp76E9Jc3IgyYubnpqI9fS7eseGOe4FjpeVKqKt9Iw,18612
+pip/_vendor/distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792
+pip/_vendor/distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784
+pip/_vendor/distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032
+pip/_vendor/distlib/util.py,sha256=vMPGvsS4j9hF6Y9k3Tyom1aaHLb0rFmZAEyzeAdel9w,66682
+pip/_vendor/distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648
+pip/_vendor/distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448
+pip/_vendor/distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888
+pip/_vendor/distro/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325
+pip/_vendor/distro/__init__.py,sha256=2fHjF-SfgPvjyNZ1iHh_wjqWdR_Yo5ODHwZC0jLBPhc,981
+pip/_vendor/distro/__main__.py,sha256=bu9d3TifoKciZFcqRBuygV3GSuThnVD_m2IK4cz96Vs,64
+pip/_vendor/distro/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/distro/__pycache__/__main__.cpython-313.pyc,,
+pip/_vendor/distro/__pycache__/distro.cpython-313.pyc,,
+pip/_vendor/distro/distro.py,sha256=XqbefacAhDT4zr_trnbA15eY8vdK4GTghgmvUGrEM_4,49430
+pip/_vendor/distro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/idna/LICENSE.md,sha256=pZ8LDvNjWHQQmkRhykT_enDVBpboFHZ7-vch1Mmw2w8,1541
+pip/_vendor/idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868
+pip/_vendor/idna/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/idna/__pycache__/codec.cpython-313.pyc,,
+pip/_vendor/idna/__pycache__/compat.cpython-313.pyc,,
+pip/_vendor/idna/__pycache__/core.cpython-313.pyc,,
+pip/_vendor/idna/__pycache__/idnadata.cpython-313.pyc,,
+pip/_vendor/idna/__pycache__/intranges.cpython-313.pyc,,
+pip/_vendor/idna/__pycache__/package_data.cpython-313.pyc,,
+pip/_vendor/idna/__pycache__/uts46data.cpython-313.pyc,,
+pip/_vendor/idna/codec.py,sha256=PEew3ItwzjW4hymbasnty2N2OXvNcgHB-JjrBuxHPYY,3422
+pip/_vendor/idna/compat.py,sha256=RzLy6QQCdl9784aFhb2EX9EKGCJjg0P3PilGdeXXcx8,316
+pip/_vendor/idna/core.py,sha256=YJYyAMnwiQEPjVC4-Fqu_p4CJ6yKKuDGmppBNQNQpFs,13239
+pip/_vendor/idna/idnadata.py,sha256=W30GcIGvtOWYwAjZj4ZjuouUutC6ffgNuyjJy7fZ-lo,78306
+pip/_vendor/idna/intranges.py,sha256=amUtkdhYcQG8Zr-CoMM_kVRacxkivC1WgxN1b63KKdU,1898
+pip/_vendor/idna/package_data.py,sha256=q59S3OXsc5VI8j6vSD0sGBMyk6zZ4vWFREE88yCJYKs,21
+pip/_vendor/idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/idna/uts46data.py,sha256=rt90K9J40gUSwppDPCrhjgi5AA6pWM65dEGRSf6rIhM,239289
+pip/_vendor/msgpack/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614
+pip/_vendor/msgpack/__init__.py,sha256=RA8gcqK17YpkxBnNwXJVa1oa2LygWDgfF1nA1NPw3mo,1109
+pip/_vendor/msgpack/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/msgpack/__pycache__/exceptions.cpython-313.pyc,,
+pip/_vendor/msgpack/__pycache__/ext.cpython-313.pyc,,
+pip/_vendor/msgpack/__pycache__/fallback.cpython-313.pyc,,
+pip/_vendor/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081
+pip/_vendor/msgpack/ext.py,sha256=kteJv03n9tYzd5oo3xYopVTo4vRaAxonBQQJhXohZZo,5726
+pip/_vendor/msgpack/fallback.py,sha256=0g1Pzp0vtmBEmJ5w9F3s_-JMVURP8RS4G1cc5TRaAsI,32390
+pip/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
+pip/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
+pip/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
+pip/_vendor/packaging/__init__.py,sha256=_0cDiPVf2S-bNfVmZguxxzmrIYWlyASxpqph4qsJWUc,494
+pip/_vendor/packaging/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/_elffile.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/_manylinux.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/_musllinux.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/_parser.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/_structures.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/_tokenizer.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/markers.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/metadata.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/requirements.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/specifiers.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/tags.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/utils.cpython-313.pyc,,
+pip/_vendor/packaging/__pycache__/version.cpython-313.pyc,,
+pip/_vendor/packaging/_elffile.py,sha256=UkrbDtW7aeq3qqoAfU16ojyHZ1xsTvGke_WqMTKAKd0,3286
+pip/_vendor/packaging/_manylinux.py,sha256=t4y_-dTOcfr36gLY-ztiOpxxJFGO2ikC11HgfysGxiM,9596
+pip/_vendor/packaging/_musllinux.py,sha256=p9ZqNYiOItGee8KcZFeHF_YcdhVwGHdK6r-8lgixvGQ,2694
+pip/_vendor/packaging/_parser.py,sha256=gYfnj0pRHflVc4RHZit13KNTyN9iiVcU2RUCGi22BwM,10221
+pip/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431
+pip/_vendor/packaging/_tokenizer.py,sha256=OYzt7qKxylOAJ-q0XyK1qAycyPRYLfMPdGQKRXkZWyI,5310
+pip/_vendor/packaging/licenses/__init__.py,sha256=3bx-gryo4sRv5LsrwApouy65VIs3u6irSORJzALkrzU,5727
+pip/_vendor/packaging/licenses/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/packaging/licenses/__pycache__/_spdx.cpython-313.pyc,,
+pip/_vendor/packaging/licenses/_spdx.py,sha256=oAm1ztPFwlsmCKe7lAAsv_OIOfS1cWDu9bNBkeu-2ns,48398
+pip/_vendor/packaging/markers.py,sha256=P0we27jm1xUzgGMJxBjtUFCIWeBxTsMeJTOJ6chZmAY,12049
+pip/_vendor/packaging/metadata.py,sha256=8IZErqQQnNm53dZZuYq4FGU4_dpyinMeH1QFBIWIkfE,34739
+pip/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/packaging/requirements.py,sha256=gYyRSAdbrIyKDY66ugIDUQjRMvxkH2ALioTmX3tnL6o,2947
+pip/_vendor/packaging/specifiers.py,sha256=yc9D_MycJEmwUpZvcs1OZL9HfiNFmyw0RZaeHRNHkPw,40079
+pip/_vendor/packaging/tags.py,sha256=41s97W9Zatrq2Ed7Rc3qeBDaHe8pKKvYq2mGjwahfXk,22745
+pip/_vendor/packaging/utils.py,sha256=0F3Hh9OFuRgrhTgGZUl5K22Fv1YP2tZl1z_2gO6kJiA,5050
+pip/_vendor/packaging/version.py,sha256=oiHqzTUv_p12hpjgsLDVcaF5hT7pDaSOViUNMD4GTW0,16688
+pip/_vendor/pkg_resources/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023
+pip/_vendor/pkg_resources/__init__.py,sha256=vbTJ0_ruUgGxQjlEqsruFmiNPVyh2t9q-zyTDT053xI,124451
+pip/_vendor/pkg_resources/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/platformdirs/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+pip/_vendor/platformdirs/__init__.py,sha256=UfeSHWl8AeTtbOBOoHAxK4dODOWkZtfy-m_i7cWdJ8c,22344
+pip/_vendor/platformdirs/__main__.py,sha256=jBJ8zb7Mpx5ebcqF83xrpO94MaeCpNGHVf9cvDN2JLg,1505
+pip/_vendor/platformdirs/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/platformdirs/__pycache__/__main__.cpython-313.pyc,,
+pip/_vendor/platformdirs/__pycache__/android.cpython-313.pyc,,
+pip/_vendor/platformdirs/__pycache__/api.cpython-313.pyc,,
+pip/_vendor/platformdirs/__pycache__/macos.cpython-313.pyc,,
+pip/_vendor/platformdirs/__pycache__/unix.cpython-313.pyc,,
+pip/_vendor/platformdirs/__pycache__/version.cpython-313.pyc,,
+pip/_vendor/platformdirs/__pycache__/windows.cpython-313.pyc,,
+pip/_vendor/platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013
+pip/_vendor/platformdirs/api.py,sha256=wPHOlwOsfz2oqQZ6A2FcCu5kEAj-JondzoNOHYFQ0h8,9281
+pip/_vendor/platformdirs/macos.py,sha256=0XoOgin1NK7Qki7iskD-oS8xKxw6bXgoKEgdqpCRAFQ,6322
+pip/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458
+pip/_vendor/platformdirs/version.py,sha256=sved76l3nstESjZInsYGzPryR4cPIaf3QHTJuTDYXNM,704
+pip/_vendor/platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125
+pip/_vendor/pygments/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331
+pip/_vendor/pygments/__init__.py,sha256=8uNqJCCwXqbEx5aSsBr0FykUQOBDKBihO5mPqiw1aqo,2983
+pip/_vendor/pygments/__main__.py,sha256=WrndpSe6i1ckX_SQ1KaxD9CTKGzD0EuCOFxcbwFpoLU,353
+pip/_vendor/pygments/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/__main__.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/console.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/filter.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/formatter.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/lexer.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/modeline.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/plugin.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/regexopt.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/scanner.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/sphinxext.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/style.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/token.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/unistring.cpython-313.pyc,,
+pip/_vendor/pygments/__pycache__/util.cpython-313.pyc,,
+pip/_vendor/pygments/console.py,sha256=AagDWqwea2yBWf10KC9ptBgMpMjxKp8yABAmh-NQOVk,1718
+pip/_vendor/pygments/filter.py,sha256=YLtpTnZiu07nY3oK9nfR6E9Y1FBHhP5PX8gvkJWcfag,1910
+pip/_vendor/pygments/filters/__init__.py,sha256=4U4jtA0X3iP83uQnB9-TI-HDSw8E8y8zMYHa0UjbbaI,40392
+pip/_vendor/pygments/filters/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/pygments/formatter.py,sha256=KZQMmyo_xkOIkQG8g66LYEkBh1bx7a0HyGCBcvhI9Ew,4390
+pip/_vendor/pygments/formatters/__init__.py,sha256=KTwBmnXlaopJhQDOemVHYHskiDghuq-08YtP6xPNJPg,5385
+pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-313.pyc,,
+pip/_vendor/pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176
+pip/_vendor/pygments/lexer.py,sha256=_kBrOJ_NT5Tl0IVM0rA9c8eysP6_yrlGzEQI0eVYB-A,35349
+pip/_vendor/pygments/lexers/__init__.py,sha256=wbIME35GH7bI1B9rNPJFqWT-ij_RApZDYPUlZycaLzA,12115
+pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-313.pyc,,
+pip/_vendor/pygments/lexers/__pycache__/python.cpython-313.pyc,,
+pip/_vendor/pygments/lexers/_mapping.py,sha256=l4tCXM8e9aPC2BD6sjIr0deT-J-z5tHgCwL-p1fS0PE,77602
+pip/_vendor/pygments/lexers/python.py,sha256=vxjn1cOHclIKJKxoyiBsQTY65GHbkZtZRuKQ2AVCKaw,53853
+pip/_vendor/pygments/modeline.py,sha256=K5eSkR8GS1r5OkXXTHOcV0aM_6xpk9eWNEIAW-OOJ2g,1005
+pip/_vendor/pygments/plugin.py,sha256=tPx0rJCTIZ9ioRgLNYG4pifCbAwTRUZddvLw-NfAk2w,1891
+pip/_vendor/pygments/regexopt.py,sha256=wXaP9Gjp_hKAdnICqoDkRxAOQJSc4v3X6mcxx3z-TNs,3072
+pip/_vendor/pygments/scanner.py,sha256=nNcETRR1tRuiTaHmHSTTECVYFPcLf6mDZu1e4u91A9E,3092
+pip/_vendor/pygments/sphinxext.py,sha256=5x7Zh9YlU6ISJ31dMwduiaanb5dWZnKg3MyEQsseNnQ,7981
+pip/_vendor/pygments/style.py,sha256=PlOZqlsnTVd58RGy50vkA2cXQ_lP5bF5EGMEBTno6DA,6420
+pip/_vendor/pygments/styles/__init__.py,sha256=x9ebctfyvCAFpMTlMJ5YxwcNYBzjgq6zJaKkNm78r4M,2042
+pip/_vendor/pygments/styles/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/pygments/styles/__pycache__/_mapping.cpython-313.pyc,,
+pip/_vendor/pygments/styles/_mapping.py,sha256=6lovFUE29tz6EsV3XYY4hgozJ7q1JL7cfO3UOlgnS8w,3312
+pip/_vendor/pygments/token.py,sha256=WbdWGhYm_Vosb0DDxW9lHNPgITXfWTsQmHt6cy9RbcM,6226
+pip/_vendor/pygments/unistring.py,sha256=al-_rBemRuGvinsrM6atNsHTmJ6DUbw24q2O2Ru1cBc,63208
+pip/_vendor/pygments/util.py,sha256=oRtSpiAo5jM9ulntkvVbgXUdiAW57jnuYGB7t9fYuhc,10031
+pip/_vendor/pyproject_hooks/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081
+pip/_vendor/pyproject_hooks/__init__.py,sha256=cPB_a9LXz5xvsRbX1o2qyAdjLatZJdQ_Lc5McNX-X7Y,691
+pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-313.pyc,,
+pip/_vendor/pyproject_hooks/_impl.py,sha256=jY-raxnmyRyB57ruAitrJRUzEexuAhGTpgMygqx67Z4,14936
+pip/_vendor/pyproject_hooks/_in_process/__init__.py,sha256=MJNPpfIxcO-FghxpBbxkG1rFiQf6HOUbV4U5mq0HFns,557
+pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/pyproject_hooks/_in_process/__pycache__/_in_process.cpython-313.pyc,,
+pip/_vendor/pyproject_hooks/_in_process/_in_process.py,sha256=qcXMhmx__MIJq10gGHW3mA4Tl8dy8YzHMccwnNoKlw0,12216
+pip/_vendor/pyproject_hooks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/requests/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
+pip/_vendor/requests/__init__.py,sha256=HlB_HzhrzGtfD_aaYUwUh1zWXLZ75_YCLyit75d0Vz8,5057
+pip/_vendor/requests/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/__version__.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/_internal_utils.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/adapters.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/api.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/auth.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/certs.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/compat.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/cookies.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/exceptions.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/help.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/hooks.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/models.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/packages.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/sessions.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/status_codes.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/structures.cpython-313.pyc,,
+pip/_vendor/requests/__pycache__/utils.cpython-313.pyc,,
+pip/_vendor/requests/__version__.py,sha256=QKDceK8K_ujqwDDc3oYrR0odOBYgKVOQQ5vFap_G_cg,435
+pip/_vendor/requests/_internal_utils.py,sha256=nMQymr4hs32TqVo5AbCrmcJEhvPUh7xXlluyqwslLiQ,1495
+pip/_vendor/requests/adapters.py,sha256=2MLFOK9GpYNhiTd6zLDUrAgSkIB-76i6pmSuUJjHC2w,26429
+pip/_vendor/requests/api.py,sha256=_Zb9Oa7tzVIizTKwFrPjDEY9ejtm_OnSRERnADxGsQs,6449
+pip/_vendor/requests/auth.py,sha256=kF75tqnLctZ9Mf_hm9TZIj4cQWnN5uxRz8oWsx5wmR0,10186
+pip/_vendor/requests/certs.py,sha256=kHDlkK_beuHXeMPc5jta2wgl8gdKeUWt5f2nTDVrvt8,441
+pip/_vendor/requests/compat.py,sha256=QfbmdTFiZzjSHMXiMrd4joCRU6RabtQ9zIcPoVaHIus,1822
+pip/_vendor/requests/cookies.py,sha256=bNi-iqEj4NPZ00-ob-rHvzkvObzN3lEpgw3g6paS3Xw,18590
+pip/_vendor/requests/exceptions.py,sha256=D1wqzYWne1mS2rU43tP9CeN1G7QAy7eqL9o1god6Ejw,4272
+pip/_vendor/requests/help.py,sha256=hRKaf9u0G7fdwrqMHtF3oG16RKktRf6KiwtSq2Fo1_0,3813
+pip/_vendor/requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733
+pip/_vendor/requests/models.py,sha256=taljlg6vJ4b-xMu2TaMNFFkaiwMex_VsEQ6qUTN3wzY,35575
+pip/_vendor/requests/packages.py,sha256=_ZQDCJTJ8SP3kVWunSqBsRZNPzj2c1WFVqbdr08pz3U,1057
+pip/_vendor/requests/sessions.py,sha256=Cl1dpEnOfwrzzPbku-emepNeN4Rt_0_58Iy2x-JGTm8,30503
+pip/_vendor/requests/status_codes.py,sha256=iJUAeA25baTdw-6PfD0eF4qhpINDJRJI-yaMqxs4LEI,4322
+pip/_vendor/requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912
+pip/_vendor/requests/utils.py,sha256=WS3wHSQaaEfceu1syiFo5jf4e_CWKUTep_IabOVI_J0,33225
+pip/_vendor/resolvelib/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
+pip/_vendor/resolvelib/__init__.py,sha256=yoX-d4STvwGGCiQRE5cJC9Cter69SgVgqClxOCvSP7M,541
+pip/_vendor/resolvelib/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/resolvelib/__pycache__/providers.cpython-313.pyc,,
+pip/_vendor/resolvelib/__pycache__/reporters.cpython-313.pyc,,
+pip/_vendor/resolvelib/__pycache__/structs.cpython-313.pyc,,
+pip/_vendor/resolvelib/providers.py,sha256=pIWJbIdJJ9GFtNbtwTH0Ia43Vj6hYCEJj2DOLue15FM,8914
+pip/_vendor/resolvelib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/resolvelib/reporters.py,sha256=pNJf4nFxLpAeKxlBUi2GEj0a2Ij1nikY0UabTKXesT4,2037
+pip/_vendor/resolvelib/resolvers/__init__.py,sha256=728M3EvmnPbVXS7ExXlv2kMu6b7wEsoPutEfl-uVk_I,640
+pip/_vendor/resolvelib/resolvers/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/resolvelib/resolvers/__pycache__/abstract.cpython-313.pyc,,
+pip/_vendor/resolvelib/resolvers/__pycache__/criterion.cpython-313.pyc,,
+pip/_vendor/resolvelib/resolvers/__pycache__/exceptions.cpython-313.pyc,,
+pip/_vendor/resolvelib/resolvers/__pycache__/resolution.cpython-313.pyc,,
+pip/_vendor/resolvelib/resolvers/abstract.py,sha256=CNeQPnpAudY77nmzOkONSmAgRlzIf06X-X9mvRYODms,1543
+pip/_vendor/resolvelib/resolvers/criterion.py,sha256=lcmZGv5sKHOnFD_RzZwvlGSj19MeA-5rCMpdf2Sgw7Y,1768
+pip/_vendor/resolvelib/resolvers/exceptions.py,sha256=ln_jaQtgLlRUSFY627yiHG2gD7AgaXzRKaElFVh7fDQ,1768
+pip/_vendor/resolvelib/resolvers/resolution.py,sha256=3J_zkW-sD3EY-BlNXjyln__njpyH5n0UZJT6uV7CheA,24212
+pip/_vendor/resolvelib/structs.py,sha256=pu-EJiR2IBITr2SQeNPRa0rXhjlStfmO_GEgAhr3004,6420
+pip/_vendor/rich/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056
+pip/_vendor/rich/__init__.py,sha256=dRxjIL-SbFVY0q3IjSMrfgBTHrm1LZDgLOygVBwiYZc,6090
+pip/_vendor/rich/__main__.py,sha256=e_aVC-tDzarWQW9SuZMuCgBr6ODV_iDNV2Wh2xkxOlw,7896
+pip/_vendor/rich/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/__main__.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_cell_widths.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_emoji_codes.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_emoji_replace.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_export_format.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_extension.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_fileno.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_inspect.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_log_render.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_loop.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_null_file.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_palettes.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_pick.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_ratio.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_spinners.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_stack.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_timer.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_win32_console.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_windows.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_windows_renderer.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/_wrap.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/abc.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/align.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/ansi.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/bar.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/box.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/cells.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/color.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/color_triplet.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/columns.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/console.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/constrain.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/containers.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/control.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/default_styles.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/diagnose.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/emoji.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/errors.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/file_proxy.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/filesize.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/highlighter.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/json.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/jupyter.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/layout.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/live.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/live_render.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/logging.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/markup.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/measure.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/padding.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/pager.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/palette.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/panel.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/pretty.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/progress.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/progress_bar.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/prompt.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/protocol.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/region.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/repr.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/rule.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/scope.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/screen.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/segment.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/spinner.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/status.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/style.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/styled.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/syntax.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/table.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/terminal_theme.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/text.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/theme.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/themes.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/traceback.cpython-313.pyc,,
+pip/_vendor/rich/__pycache__/tree.cpython-313.pyc,,
+pip/_vendor/rich/_cell_widths.py,sha256=fbmeyetEdHjzE_Vx2l1uK7tnPOhMs2X1lJfO3vsKDpA,10209
+pip/_vendor/rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235
+pip/_vendor/rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064
+pip/_vendor/rich/_export_format.py,sha256=RI08pSrm5tBSzPMvnbTqbD9WIalaOoN5d4M1RTmLq1Y,2128
+pip/_vendor/rich/_extension.py,sha256=Xt47QacCKwYruzjDi-gOBq724JReDj9Cm9xUi5fr-34,265
+pip/_vendor/rich/_fileno.py,sha256=HWZxP5C2ajMbHryvAQZseflVfQoGzsKOHzKGsLD8ynQ,799
+pip/_vendor/rich/_inspect.py,sha256=ROT0PLC2GMWialWZkqJIjmYq7INRijQQkoSokWTaAiI,9656
+pip/_vendor/rich/_log_render.py,sha256=1ByI0PA1ZpxZY3CGJOK54hjlq4X-Bz_boIjIqCd8Kns,3225
+pip/_vendor/rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236
+pip/_vendor/rich/_null_file.py,sha256=ADGKp1yt-k70FMKV6tnqCqecB-rSJzp-WQsD7LPL-kg,1394
+pip/_vendor/rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063
+pip/_vendor/rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423
+pip/_vendor/rich/_ratio.py,sha256=IOtl78sQCYZsmHyxhe45krkb68u9xVz7zFsXVJD-b2Y,5325
+pip/_vendor/rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919
+pip/_vendor/rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351
+pip/_vendor/rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417
+pip/_vendor/rich/_win32_console.py,sha256=BSaDRIMwBLITn_m0mTRLPqME5q-quGdSMuYMpYeYJwc,22755
+pip/_vendor/rich/_windows.py,sha256=aBwaD_S56SbgopIvayVmpk0Y28uwY2C5Bab1wl3Bp-I,1925
+pip/_vendor/rich/_windows_renderer.py,sha256=t74ZL3xuDCP3nmTp9pH1L5LiI2cakJuQRQleHCJerlk,2783
+pip/_vendor/rich/_wrap.py,sha256=FlSsom5EX0LVkA3KWy34yHnCfLtqX-ZIepXKh-70rpc,3404
+pip/_vendor/rich/abc.py,sha256=ON-E-ZqSSheZ88VrKX2M3PXpFbGEUUZPMa_Af0l-4f0,890
+pip/_vendor/rich/align.py,sha256=dg-7uY0ukMLLlUEsBDRLva22_sQgIJD4BK0dmZHFHug,10324
+pip/_vendor/rich/ansi.py,sha256=Avs1LHbSdcyOvDOdpELZUoULcBiYewY76eNBp6uFBhs,6921
+pip/_vendor/rich/bar.py,sha256=ldbVHOzKJOnflVNuv1xS7g6dLX2E3wMnXkdPbpzJTcs,3263
+pip/_vendor/rich/box.py,sha256=kmavBc_dn73L_g_8vxWSwYJD2uzBXOUFTtJOfpbczcM,10686
+pip/_vendor/rich/cells.py,sha256=KrQkj5-LghCCpJLSNQIyAZjndc4bnEqOEmi5YuZ9UCY,5130
+pip/_vendor/rich/color.py,sha256=3HSULVDj7qQkXUdFWv78JOiSZzfy5y1nkcYhna296V0,18211
+pip/_vendor/rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054
+pip/_vendor/rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131
+pip/_vendor/rich/console.py,sha256=t9azZpmRMVU5cphVBZSShNsmBxd2-IAWcTTlhor-E1s,100849
+pip/_vendor/rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288
+pip/_vendor/rich/containers.py,sha256=c_56TxcedGYqDepHBMTuZdUIijitAQgnox-Qde0Z1qo,5502
+pip/_vendor/rich/control.py,sha256=EUTSUFLQbxY6Zmo_sdM-5Ls323vIHTBfN8TPulqeHUY,6487
+pip/_vendor/rich/default_styles.py,sha256=khQFqqaoDs3bprMqWpHw8nO5UpG2DN6QtuTd6LzZwYc,8257
+pip/_vendor/rich/diagnose.py,sha256=fJl1TItRn19gGwouqTg-8zPUW3YqQBqGltrfPQs1H9w,1025
+pip/_vendor/rich/emoji.py,sha256=Wd4bQubZdSy6-PyrRQNuMHtn2VkljK9uPZPVlu2cmx0,2367
+pip/_vendor/rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642
+pip/_vendor/rich/file_proxy.py,sha256=Tl9THMDZ-Pk5Wm8sI1gGg_U5DhusmxD-FZ0fUbcU0W0,1683
+pip/_vendor/rich/filesize.py,sha256=_iz9lIpRgvW7MNSeCZnLg-HwzbP4GETg543WqD8SFs0,2484
+pip/_vendor/rich/highlighter.py,sha256=G_sn-8DKjM1sEjLG_oc4ovkWmiUpWvj8bXi0yed2LnY,9586
+pip/_vendor/rich/json.py,sha256=vVEoKdawoJRjAFayPwXkMBPLy7RSTs-f44wSQDR2nJ0,5031
+pip/_vendor/rich/jupyter.py,sha256=QyoKoE_8IdCbrtiSHp9TsTSNyTHY0FO5whE7jOTd9UE,3252
+pip/_vendor/rich/layout.py,sha256=ajkSFAtEVv9EFTcFs-w4uZfft7nEXhNzL7ZVdgrT5rI,14004
+pip/_vendor/rich/live.py,sha256=tF3ukAAJZ_N2ZbGclqZ-iwLoIoZ8f0HHUz79jAyJqj8,15180
+pip/_vendor/rich/live_render.py,sha256=It_39YdzrBm8o3LL0kaGorPFg-BfZWAcrBjLjFokbx4,3521
+pip/_vendor/rich/logging.py,sha256=5KaPPSMP9FxcXPBcKM4cGd_zW78PMgf-YbMVnvfSw0o,12468
+pip/_vendor/rich/markup.py,sha256=3euGKP5s41NCQwaSjTnJxus5iZMHjxpIM0W6fCxra38,8451
+pip/_vendor/rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305
+pip/_vendor/rich/padding.py,sha256=KVEI3tOwo9sgK1YNSuH__M1_jUWmLZwRVV_KmOtVzyM,4908
+pip/_vendor/rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828
+pip/_vendor/rich/palette.py,sha256=lInvR1ODDT2f3UZMfL1grq7dY_pDdKHw4bdUgOGaM4Y,3396
+pip/_vendor/rich/panel.py,sha256=9sQl00hPIqH5G2gALQo4NepFwpP0k9wT-s_gOms5pIc,11157
+pip/_vendor/rich/pretty.py,sha256=gy3S72u4FRg2ytoo7N1ZDWDIvB4unbzd5iUGdgm-8fc,36391
+pip/_vendor/rich/progress.py,sha256=CUc2lkU-X59mVdGfjMCBkZeiGPL3uxdONjhNJF2T7wY,60408
+pip/_vendor/rich/progress_bar.py,sha256=mZTPpJUwcfcdgQCTTz3kyY-fc79ddLwtx6Ghhxfo064,8162
+pip/_vendor/rich/prompt.py,sha256=l0RhQU-0UVTV9e08xW1BbIj0Jq2IXyChX4lC0lFNzt4,12447
+pip/_vendor/rich/protocol.py,sha256=5hHHDDNHckdk8iWH5zEbi-zuIVSF5hbU2jIo47R7lTE,1391
+pip/_vendor/rich/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166
+pip/_vendor/rich/repr.py,sha256=5MZJZmONgC6kud-QW-_m1okXwL2aR6u6y-pUcUCJz28,4431
+pip/_vendor/rich/rule.py,sha256=0fNaS_aERa3UMRc3T5WMpN_sumtDxfaor2y3of1ftBk,4602
+pip/_vendor/rich/scope.py,sha256=TMUU8qo17thyqQCPqjDLYpg_UU1k5qVd-WwiJvnJVas,2843
+pip/_vendor/rich/screen.py,sha256=YoeReESUhx74grqb0mSSb9lghhysWmFHYhsbMVQjXO8,1591
+pip/_vendor/rich/segment.py,sha256=otnKeKGEV-WRlQVosfJVeFDcDxAKHpvJ_hLzSu5lumM,24743
+pip/_vendor/rich/spinner.py,sha256=onIhpKlljRHppTZasxO8kXgtYyCHUkpSgKglRJ3o51g,4214
+pip/_vendor/rich/status.py,sha256=kkPph3YeAZBo-X-4wPp8gTqZyU466NLwZBA4PZTTewo,4424
+pip/_vendor/rich/style.py,sha256=W9Ccy8Py8lNICtlfcp-ryzMTuQaGxAU3av7-g5fHu0s,26990
+pip/_vendor/rich/styled.py,sha256=eZNnzGrI4ki_54pgY3Oj0T-x3lxdXTYh4_ryDB24wBU,1258
+pip/_vendor/rich/syntax.py,sha256=eDKIRwl--eZ0Lwo2da2RRtfutXGavrJO61Cl5OkS59U,36371
+pip/_vendor/rich/table.py,sha256=ZmT7V7MMCOYKw7TGY9SZLyYDf6JdM-WVf07FdVuVhTI,40049
+pip/_vendor/rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370
+pip/_vendor/rich/text.py,sha256=AO7JPCz6-gaN1thVLXMBntEmDPVYFgFNG1oM61_sanU,47552
+pip/_vendor/rich/theme.py,sha256=oNyhXhGagtDlbDye3tVu3esWOWk0vNkuxFw-_unlaK0,3771
+pip/_vendor/rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102
+pip/_vendor/rich/traceback.py,sha256=c0WmB_L04_UfZbLaoH982_U_s7eosxKMUiAVmDPdRYU,35861
+pip/_vendor/rich/tree.py,sha256=yWnQ6rAvRGJ3qZGqBrxS2SW2TKBTNrP0SdY8QxOFPuw,9451
+pip/_vendor/tomli/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+pip/_vendor/tomli/__init__.py,sha256=qzEGl8QHhqgQPCuLzfKyPIuH3KKPspf-UVPbZ0ppBD4,314
+pip/_vendor/tomli/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/tomli/__pycache__/_parser.cpython-313.pyc,,
+pip/_vendor/tomli/__pycache__/_re.cpython-313.pyc,,
+pip/_vendor/tomli/__pycache__/_types.cpython-313.pyc,,
+pip/_vendor/tomli/_parser.py,sha256=bO8tUYmnyA2K6m4TnbQbfUqmIFcDv7mG1KuC9gqRVmA,25778
+pip/_vendor/tomli/_re.py,sha256=n8-Io8ZK1U-F6jzlg7Pabc40hLFJsawE2uNLKH9w7iU,3235
+pip/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254
+pip/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
+pip/_vendor/tomli_w/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072
+pip/_vendor/tomli_w/__init__.py,sha256=0F8yDtXx3Uunhm874KrAcP76srsM98y7WyHQwCulZbo,169
+pip/_vendor/tomli_w/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/tomli_w/__pycache__/_writer.cpython-313.pyc,,
+pip/_vendor/tomli_w/_writer.py,sha256=dsifFS2xYf1i76mmRyfz9y125xC7Z_HQ845ZKhJsYXs,6961
+pip/_vendor/tomli_w/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
+pip/_vendor/truststore/LICENSE,sha256=M757fo-k_Rmxdg4ajtimaL2rhSyRtpLdQUJLy3Jan8o,1086
+pip/_vendor/truststore/__init__.py,sha256=Bu7kqkmpunhLsj5xCu8gT_25ktoPXcSnwe8VHk1GmJo,1320
+pip/_vendor/truststore/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/truststore/__pycache__/_api.cpython-313.pyc,,
+pip/_vendor/truststore/__pycache__/_macos.cpython-313.pyc,,
+pip/_vendor/truststore/__pycache__/_openssl.cpython-313.pyc,,
+pip/_vendor/truststore/__pycache__/_ssl_constants.cpython-313.pyc,,
+pip/_vendor/truststore/__pycache__/_windows.cpython-313.pyc,,
+pip/_vendor/truststore/_api.py,sha256=CYJCV5BTfttZYfqY3movdMBE-8az7uhET_LYbKT2Nn4,11413
+pip/_vendor/truststore/_macos.py,sha256=nZlLkOmszUE0g6ryRwBVGY5COzPyudcsiJtDWarM5LQ,20503
+pip/_vendor/truststore/_openssl.py,sha256=zB-SQvJydks7tQ0yIwrP6GD3fQNSSaPiq7zw4yF5T40,2412
+pip/_vendor/truststore/_ssl_constants.py,sha256=NUD4fVKdSD02ri7-db0tnO0VqLP9aHuzmStcW7tAl08,1130
+pip/_vendor/truststore/_windows.py,sha256=rAHyKYD8M7t-bXfG8VgOVa3TpfhVhbt4rZQlO45YuP8,17993
+pip/_vendor/truststore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/LICENSE.txt,sha256=w3vxhuJ8-dvpYZ5V7f486nswCRzrPaY8fay-Dm13kHs,1115
+pip/_vendor/urllib3/__init__.py,sha256=iXLcYiJySn0GNbWOOZDDApgBL1JgP44EZ8i1760S8Mc,3333
+pip/_vendor/urllib3/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/_collections.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/_version.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/connection.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/connectionpool.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/exceptions.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/fields.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/filepost.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/poolmanager.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/request.cpython-313.pyc,,
+pip/_vendor/urllib3/__pycache__/response.cpython-313.pyc,,
+pip/_vendor/urllib3/_collections.py,sha256=pyASJJhW7wdOpqJj9QJA8FyGRfr8E8uUUhqUvhF0728,11372
+pip/_vendor/urllib3/_version.py,sha256=t9wGB6ooOTXXgiY66K1m6BZS1CJyXHAU8EoWDTe6Shk,64
+pip/_vendor/urllib3/connection.py,sha256=ttIA909BrbTUzwkqEe_TzZVh4JOOj7g61Ysei2mrwGg,20314
+pip/_vendor/urllib3/connectionpool.py,sha256=e2eiAwNbFNCKxj4bwDKNK-w7HIdSz3OmMxU_TIt-evQ,40408
+pip/_vendor/urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/appengine.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/ntlmpool.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/securetransport.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/_appengine_environ.py,sha256=bDbyOEhW2CKLJcQqAKAyrEHN-aklsyHFKq6vF8ZFsmk,957
+pip/_vendor/urllib3/contrib/_securetransport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/contrib/_securetransport/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/_securetransport/__pycache__/bindings.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/_securetransport/__pycache__/low_level.cpython-313.pyc,,
+pip/_vendor/urllib3/contrib/_securetransport/bindings.py,sha256=4Xk64qIkPBt09A5q-RIFUuDhNc9mXilVapm7WnYnzRw,17632
+pip/_vendor/urllib3/contrib/_securetransport/low_level.py,sha256=B2JBB2_NRP02xK6DCa1Pa9IuxrPwxzDzZbixQkb7U9M,13922
+pip/_vendor/urllib3/contrib/appengine.py,sha256=VR68eAVE137lxTgjBDwCna5UiBZTOKa01Aj_-5BaCz4,11036
+pip/_vendor/urllib3/contrib/ntlmpool.py,sha256=NlfkW7WMdW8ziqudopjHoW299og1BTWi0IeIibquFwk,4528
+pip/_vendor/urllib3/contrib/pyopenssl.py,sha256=hDJh4MhyY_p-oKlFcYcQaVQRDv6GMmBGuW9yjxyeejM,17081
+pip/_vendor/urllib3/contrib/securetransport.py,sha256=Fef1IIUUFHqpevzXiDPbIGkDKchY2FVKeVeLGR1Qq3g,34446
+pip/_vendor/urllib3/contrib/socks.py,sha256=aRi9eWXo9ZEb95XUxef4Z21CFlnnjbEiAo9HOseoMt4,7097
+pip/_vendor/urllib3/exceptions.py,sha256=0Mnno3KHTNfXRfY7638NufOPkUb6mXOm-Lqj-4x2w8A,8217
+pip/_vendor/urllib3/fields.py,sha256=kvLDCg_JmH1lLjUUEY_FLS8UhY7hBvDPuVETbY8mdrM,8579
+pip/_vendor/urllib3/filepost.py,sha256=5b_qqgRHVlL7uLtdAYBzBh-GHmU5AfJVt_2N0XS3PeY,2440
+pip/_vendor/urllib3/packages/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/urllib3/packages/__pycache__/six.cpython-313.pyc,,
+pip/_vendor/urllib3/packages/backports/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pip/_vendor/urllib3/packages/backports/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/urllib3/packages/backports/__pycache__/makefile.cpython-313.pyc,,
+pip/_vendor/urllib3/packages/backports/__pycache__/weakref_finalize.cpython-313.pyc,,
+pip/_vendor/urllib3/packages/backports/makefile.py,sha256=nbzt3i0agPVP07jqqgjhaYjMmuAi_W5E0EywZivVO8E,1417
+pip/_vendor/urllib3/packages/backports/weakref_finalize.py,sha256=tRCal5OAhNSRyb0DhHp-38AtIlCsRP8BxF3NX-6rqIA,5343
+pip/_vendor/urllib3/packages/six.py,sha256=b9LM0wBXv7E7SrbCjAm4wwN-hrH-iNxv18LgWNMMKPo,34665
+pip/_vendor/urllib3/poolmanager.py,sha256=aWyhXRtNO4JUnCSVVqKTKQd8EXTvUm1VN9pgs2bcONo,19990
+pip/_vendor/urllib3/request.py,sha256=YTWFNr7QIwh7E1W9dde9LM77v2VWTJ5V78XuTTw7D1A,6691
+pip/_vendor/urllib3/response.py,sha256=fmDJAFkG71uFTn-sVSTh2Iw0WmcXQYqkbRjihvwBjU8,30641
+pip/_vendor/urllib3/util/__init__.py,sha256=JEmSmmqqLyaw8P51gUImZh8Gwg9i1zSe-DoqAitn2nc,1155
+pip/_vendor/urllib3/util/__pycache__/__init__.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/connection.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/proxy.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/queue.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/request.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/response.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/retry.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/timeout.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/url.cpython-313.pyc,,
+pip/_vendor/urllib3/util/__pycache__/wait.cpython-313.pyc,,
+pip/_vendor/urllib3/util/connection.py,sha256=5Lx2B1PW29KxBn2T0xkN1CBgRBa3gGVJBKoQoRogEVk,4901
+pip/_vendor/urllib3/util/proxy.py,sha256=zUvPPCJrp6dOF0N4GAVbOcl6o-4uXKSrGiTkkr5vUS4,1605
+pip/_vendor/urllib3/util/queue.py,sha256=nRgX8_eX-_VkvxoX096QWoz8Ps0QHUAExILCY_7PncM,498
+pip/_vendor/urllib3/util/request.py,sha256=C0OUt2tcU6LRiQJ7YYNP9GvPrSvl7ziIBekQ-5nlBZk,3997
+pip/_vendor/urllib3/util/response.py,sha256=GJpg3Egi9qaJXRwBh5wv-MNuRWan5BIu40oReoxWP28,3510
+pip/_vendor/urllib3/util/retry.py,sha256=6ENvOZ8PBDzh8kgixpql9lIrb2dxH-k7ZmBanJF2Ng4,22050
+pip/_vendor/urllib3/util/ssl_.py,sha256=QDuuTxPSCj1rYtZ4xpD7Ux-r20TD50aHyqKyhQ7Bq4A,17460
+pip/_vendor/urllib3/util/ssl_match_hostname.py,sha256=Ir4cZVEjmAk8gUAIHWSi7wtOO83UCYABY2xFD1Ql_WA,5758
+pip/_vendor/urllib3/util/ssltransport.py,sha256=NA-u5rMTrDFDFC8QzRKUEKMG0561hOD4qBTr3Z4pv6E,6895
+pip/_vendor/urllib3/util/timeout.py,sha256=cwq4dMk87mJHSBktK1miYJ-85G-3T3RmT20v7SFCpno,10168
+pip/_vendor/urllib3/util/url.py,sha256=lCAE7M5myA8EDdW0sJuyyZhVB9K_j38ljWhHAnFaWoE,14296
+pip/_vendor/urllib3/util/wait.py,sha256=fOX0_faozG2P7iVojQoE1mbydweNyTcm-hXEfFrTtLI,5403
+pip/_vendor/vendor.txt,sha256=vVQNxfrf_nPy_pjSSGklxQVWmH5hvhyDtZgbszGbw7c,343
+pip/py.typed,sha256=EBVvvPRTn_eIpz5e5QztSCdrMX7Qwd7VP93RSoIlZ2I,286
diff --git a/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.12.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..1a9cee0facc4533210c36ccff9a9c526d4e37b3a
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///home/task_176313218821961/conda-bld/pip_1763132220821/work"}
\ No newline at end of file
diff --git a/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/entry_points.txt b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c6436d21fcc6479564ce8581c93e30e2cc60a096
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pip-25.3.dist-info/entry_points.txt
@@ -0,0 +1,4 @@
+[console_scripts]
+pip=pip._internal.cli.main:main
+pip3=pip._internal.cli.main:main
+
diff --git a/data/miniconda3/lib/python3.13/site-packages/pkg_resources/__init__.py b/data/miniconda3/lib/python3.13/site-packages/pkg_resources/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..926765b8870704128577a990c7826f2cc4cc2f18
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pkg_resources/__init__.py
@@ -0,0 +1,3713 @@
+"""
+Package resource API
+--------------------
+
+A resource is a logical file contained within a package, or a logical
+subdirectory thereof.  The package resource API expects resource names
+to have their path parts separated with ``/``, *not* whatever the local
+path separator is.  Do not use os.path operations to manipulate resource
+names being passed into the API.
+
+The package resource API is designed to work with normal filesystem packages,
+.egg files, and unpacked .egg files.  It can also work in a limited way with
+.zip files and with custom PEP 302 loaders that support the ``get_data()``
+method.
+
+This module is deprecated. Users are directed to :mod:`importlib.resources`,
+:mod:`importlib.metadata` and :pypi:`packaging` instead.
+"""
+
+from __future__ import annotations
+
+import sys
+
+if sys.version_info < (3, 9):  # noqa: UP036 # Check for unsupported versions
+    raise RuntimeError("Python 3.9 or later is required")
+
+import _imp
+import collections
+import email.parser
+import errno
+import functools
+import importlib
+import importlib.abc
+import importlib.machinery
+import inspect
+import io
+import ntpath
+import operator
+import os
+import pkgutil
+import platform
+import plistlib
+import posixpath
+import re
+import stat
+import tempfile
+import textwrap
+import time
+import types
+import warnings
+import zipfile
+import zipimport
+from collections.abc import Iterable, Iterator, Mapping, MutableSequence
+from pkgutil import get_importer
+from typing import (
+    TYPE_CHECKING,
+    Any,
+    BinaryIO,
+    Callable,
+    Literal,
+    NamedTuple,
+    NoReturn,
+    Protocol,
+    TypeVar,
+    Union,
+    overload,
+)
+
+sys.path.extend(((vendor_path := os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setuptools', '_vendor')) not in sys.path) * [vendor_path])  # fmt: skip
+# workaround for #4476
+sys.modules.pop('backports', None)
+
+# capture these to bypass sandboxing
+from os import open as os_open, utime  # isort: skip
+from os.path import isdir, split  # isort: skip
+
+try:
+    from os import mkdir, rename, unlink
+
+    WRITE_SUPPORT = True
+except ImportError:
+    # no write support, probably under GAE
+    WRITE_SUPPORT = False
+
+import packaging.markers
+import packaging.requirements
+import packaging.specifiers
+import packaging.utils
+import packaging.version
+from jaraco.text import drop_comment, join_continuation, yield_lines
+from platformdirs import user_cache_dir as _user_cache_dir
+
+if TYPE_CHECKING:
+    from _typeshed import BytesPath, StrOrBytesPath, StrPath
+    from _typeshed.importlib import LoaderProtocol
+    from typing_extensions import Self, TypeAlias
+
+warnings.warn(
+    "pkg_resources is deprecated as an API. "
+    "See https://setuptools.pypa.io/en/latest/pkg_resources.html. "
+    "The pkg_resources package is slated for removal as early as "
+    "2025-11-30. Refrain from using this package or pin to "
+    "Setuptools<81.",
+    UserWarning,
+    stacklevel=2,
+)
+
+_T = TypeVar("_T")
+_DistributionT = TypeVar("_DistributionT", bound="Distribution")
+# Type aliases
+_NestedStr: TypeAlias = Union[str, Iterable[Union[str, Iterable["_NestedStr"]]]]
+_StrictInstallerType: TypeAlias = Callable[["Requirement"], "_DistributionT"]
+_InstallerType: TypeAlias = Callable[["Requirement"], Union["Distribution", None]]
+_PkgReqType: TypeAlias = Union[str, "Requirement"]
+_EPDistType: TypeAlias = Union["Distribution", _PkgReqType]
+_MetadataType: TypeAlias = Union["IResourceProvider", None]
+_ResolvedEntryPoint: TypeAlias = Any  # Can be any attribute in the module
+_ResourceStream: TypeAlias = Any  # TODO / Incomplete: A readable file-like object
+# Any object works, but let's indicate we expect something like a module (optionally has __loader__ or __file__)
+_ModuleLike: TypeAlias = Union[object, types.ModuleType]
+# Any: Should be _ModuleLike but we end up with issues where _ModuleLike doesn't have _ZipLoaderModule's __loader__
+_ProviderFactoryType: TypeAlias = Callable[[Any], "IResourceProvider"]
+_DistFinderType: TypeAlias = Callable[[_T, str, bool], Iterable["Distribution"]]
+_NSHandlerType: TypeAlias = Callable[[_T, str, str, types.ModuleType], Union[str, None]]
+_AdapterT = TypeVar(
+    "_AdapterT", _DistFinderType[Any], _ProviderFactoryType, _NSHandlerType[Any]
+)
+
+
+class _ZipLoaderModule(Protocol):
+    __loader__: zipimport.zipimporter
+
+
+_PEP440_FALLBACK = re.compile(r"^v?(?P(?:[0-9]+!)?[0-9]+(?:\.[0-9]+)*)", re.I)
+
+
+class PEP440Warning(RuntimeWarning):
+    """
+    Used when there is an issue with a version or specifier not complying with
+    PEP 440.
+    """
+
+
+parse_version = packaging.version.Version
+
+_state_vars: dict[str, str] = {}
+
+
+def _declare_state(vartype: str, varname: str, initial_value: _T) -> _T:
+    _state_vars[varname] = vartype
+    return initial_value
+
+
+def __getstate__() -> dict[str, Any]:
+    state = {}
+    g = globals()
+    for k, v in _state_vars.items():
+        state[k] = g['_sget_' + v](g[k])
+    return state
+
+
+def __setstate__(state: dict[str, Any]) -> dict[str, Any]:
+    g = globals()
+    for k, v in state.items():
+        g['_sset_' + _state_vars[k]](k, g[k], v)
+    return state
+
+
+def _sget_dict(val):
+    return val.copy()
+
+
+def _sset_dict(key, ob, state) -> None:
+    ob.clear()
+    ob.update(state)
+
+
+def _sget_object(val):
+    return val.__getstate__()
+
+
+def _sset_object(key, ob, state) -> None:
+    ob.__setstate__(state)
+
+
+_sget_none = _sset_none = lambda *args: None
+
+
+def get_supported_platform():
+    """Return this platform's maximum compatible version.
+
+    distutils.util.get_platform() normally reports the minimum version
+    of macOS that would be required to *use* extensions produced by
+    distutils.  But what we want when checking compatibility is to know the
+    version of macOS that we are *running*.  To allow usage of packages that
+    explicitly require a newer version of macOS, we must also know the
+    current version of the OS.
+
+    If this condition occurs for any other platform with a version in its
+    platform strings, this function should be extended accordingly.
+    """
+    plat = get_build_platform()
+    m = macosVersionString.match(plat)
+    if m is not None and sys.platform == "darwin":
+        try:
+            major_minor = '.'.join(_macos_vers()[:2])
+            build = m.group(3)
+            plat = f'macosx-{major_minor}-{build}'
+        except ValueError:
+            # not macOS
+            pass
+    return plat
+
+
+__all__ = [
+    # Basic resource access and distribution/entry point discovery
+    'require',
+    'run_script',
+    'get_provider',
+    'get_distribution',
+    'load_entry_point',
+    'get_entry_map',
+    'get_entry_info',
+    'iter_entry_points',
+    'resource_string',
+    'resource_stream',
+    'resource_filename',
+    'resource_listdir',
+    'resource_exists',
+    'resource_isdir',
+    # Environmental control
+    'declare_namespace',
+    'working_set',
+    'add_activation_listener',
+    'find_distributions',
+    'set_extraction_path',
+    'cleanup_resources',
+    'get_default_cache',
+    # Primary implementation classes
+    'Environment',
+    'WorkingSet',
+    'ResourceManager',
+    'Distribution',
+    'Requirement',
+    'EntryPoint',
+    # Exceptions
+    'ResolutionError',
+    'VersionConflict',
+    'DistributionNotFound',
+    'UnknownExtra',
+    'ExtractionError',
+    # Warnings
+    'PEP440Warning',
+    # Parsing functions and string utilities
+    'parse_requirements',
+    'parse_version',
+    'safe_name',
+    'safe_version',
+    'get_platform',
+    'compatible_platforms',
+    'yield_lines',
+    'split_sections',
+    'safe_extra',
+    'to_filename',
+    'invalid_marker',
+    'evaluate_marker',
+    # filesystem utilities
+    'ensure_directory',
+    'normalize_path',
+    # Distribution "precedence" constants
+    'EGG_DIST',
+    'BINARY_DIST',
+    'SOURCE_DIST',
+    'CHECKOUT_DIST',
+    'DEVELOP_DIST',
+    # "Provider" interfaces, implementations, and registration/lookup APIs
+    'IMetadataProvider',
+    'IResourceProvider',
+    'FileMetadata',
+    'PathMetadata',
+    'EggMetadata',
+    'EmptyProvider',
+    'empty_provider',
+    'NullProvider',
+    'EggProvider',
+    'DefaultProvider',
+    'ZipProvider',
+    'register_finder',
+    'register_namespace_handler',
+    'register_loader_type',
+    'fixup_namespace_packages',
+    'get_importer',
+    # Warnings
+    'PkgResourcesDeprecationWarning',
+    # Deprecated/backward compatibility only
+    'run_main',
+    'AvailableDistributions',
+]
+
+
+class ResolutionError(Exception):
+    """Abstract base for dependency resolution errors"""
+
+    def __repr__(self) -> str:
+        return self.__class__.__name__ + repr(self.args)
+
+
+class VersionConflict(ResolutionError):
+    """
+    An already-installed version conflicts with the requested version.
+
+    Should be initialized with the installed Distribution and the requested
+    Requirement.
+    """
+
+    _template = "{self.dist} is installed but {self.req} is required"
+
+    @property
+    def dist(self) -> Distribution:
+        return self.args[0]
+
+    @property
+    def req(self) -> Requirement:
+        return self.args[1]
+
+    def report(self):
+        return self._template.format(**locals())
+
+    def with_context(
+        self, required_by: set[Distribution | str]
+    ) -> Self | ContextualVersionConflict:
+        """
+        If required_by is non-empty, return a version of self that is a
+        ContextualVersionConflict.
+        """
+        if not required_by:
+            return self
+        args = self.args + (required_by,)
+        return ContextualVersionConflict(*args)
+
+
+class ContextualVersionConflict(VersionConflict):
+    """
+    A VersionConflict that accepts a third parameter, the set of the
+    requirements that required the installed Distribution.
+    """
+
+    _template = VersionConflict._template + ' by {self.required_by}'
+
+    @property
+    def required_by(self) -> set[str]:
+        return self.args[2]
+
+
+class DistributionNotFound(ResolutionError):
+    """A requested distribution was not found"""
+
+    _template = (
+        "The '{self.req}' distribution was not found "
+        "and is required by {self.requirers_str}"
+    )
+
+    @property
+    def req(self) -> Requirement:
+        return self.args[0]
+
+    @property
+    def requirers(self) -> set[str] | None:
+        return self.args[1]
+
+    @property
+    def requirers_str(self):
+        if not self.requirers:
+            return 'the application'
+        return ', '.join(self.requirers)
+
+    def report(self):
+        return self._template.format(**locals())
+
+    def __str__(self) -> str:
+        return self.report()
+
+
+class UnknownExtra(ResolutionError):
+    """Distribution doesn't have an "extra feature" of the given name"""
+
+
+_provider_factories: dict[type[_ModuleLike], _ProviderFactoryType] = {}
+
+PY_MAJOR = f'{sys.version_info.major}.{sys.version_info.minor}'
+EGG_DIST = 3
+BINARY_DIST = 2
+SOURCE_DIST = 1
+CHECKOUT_DIST = 0
+DEVELOP_DIST = -1
+
+
+def register_loader_type(
+    loader_type: type[_ModuleLike], provider_factory: _ProviderFactoryType
+) -> None:
+    """Register `provider_factory` to make providers for `loader_type`
+
+    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,
+    and `provider_factory` is a function that, passed a *module* object,
+    returns an ``IResourceProvider`` for that module.
+    """
+    _provider_factories[loader_type] = provider_factory
+
+
+@overload
+def get_provider(moduleOrReq: str) -> IResourceProvider: ...
+@overload
+def get_provider(moduleOrReq: Requirement) -> Distribution: ...
+def get_provider(moduleOrReq: str | Requirement) -> IResourceProvider | Distribution:
+    """Return an IResourceProvider for the named module or requirement"""
+    if isinstance(moduleOrReq, Requirement):
+        return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
+    try:
+        module = sys.modules[moduleOrReq]
+    except KeyError:
+        __import__(moduleOrReq)
+        module = sys.modules[moduleOrReq]
+    loader = getattr(module, '__loader__', None)
+    return _find_adapter(_provider_factories, loader)(module)
+
+
+@functools.cache
+def _macos_vers():
+    version = platform.mac_ver()[0]
+    # fallback for MacPorts
+    if version == '':
+        plist = '/System/Library/CoreServices/SystemVersion.plist'
+        if os.path.exists(plist):
+            with open(plist, 'rb') as fh:
+                plist_content = plistlib.load(fh)
+            if 'ProductVersion' in plist_content:
+                version = plist_content['ProductVersion']
+    return version.split('.')
+
+
+def _macos_arch(machine):
+    return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)
+
+
+def get_build_platform():
+    """Return this platform's string for platform-specific distributions"""
+    from sysconfig import get_platform
+
+    plat = get_platform()
+    if sys.platform == "darwin" and not plat.startswith('macosx-'):
+        try:
+            version = _macos_vers()
+            machine = _macos_arch(os.uname()[4].replace(" ", "_"))
+            return f"macosx-{version[0]}.{version[1]}-{machine}"
+        except ValueError:
+            # if someone is running a non-Mac darwin system, this will fall
+            # through to the default implementation
+            pass
+    return plat
+
+
+macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
+darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
+# XXX backward compat
+get_platform = get_build_platform
+
+
+def compatible_platforms(provided: str | None, required: str | None) -> bool:
+    """Can code for the `provided` platform run on the `required` platform?
+
+    Returns true if either platform is ``None``, or the platforms are equal.
+
+    XXX Needs compatibility checks for Linux and other unixy OSes.
+    """
+    if provided is None or required is None or provided == required:
+        # easy case
+        return True
+
+    # macOS special cases
+    reqMac = macosVersionString.match(required)
+    if reqMac:
+        provMac = macosVersionString.match(provided)
+
+        # is this a Mac package?
+        if not provMac:
+            # this is backwards compatibility for packages built before
+            # setuptools 0.6. All packages built after this point will
+            # use the new macOS designation.
+            provDarwin = darwinVersionString.match(provided)
+            if provDarwin:
+                dversion = int(provDarwin.group(1))
+                macosversion = f"{reqMac.group(1)}.{reqMac.group(2)}"
+                if (
+                    dversion == 7
+                    and macosversion >= "10.3"
+                    or dversion == 8
+                    and macosversion >= "10.4"
+                ):
+                    return True
+            # egg isn't macOS or legacy darwin
+            return False
+
+        # are they the same major version and machine type?
+        if provMac.group(1) != reqMac.group(1) or provMac.group(3) != reqMac.group(3):
+            return False
+
+        # is the required OS major update >= the provided one?
+        if int(provMac.group(2)) > int(reqMac.group(2)):
+            return False
+
+        return True
+
+    # XXX Linux and other platforms' special cases should go here
+    return False
+
+
+@overload
+def get_distribution(dist: _DistributionT) -> _DistributionT: ...
+@overload
+def get_distribution(dist: _PkgReqType) -> Distribution: ...
+def get_distribution(dist: Distribution | _PkgReqType) -> Distribution:
+    """Return a current distribution object for a Requirement or string"""
+    if isinstance(dist, str):
+        dist = Requirement.parse(dist)
+    if isinstance(dist, Requirement):
+        dist = get_provider(dist)
+    if not isinstance(dist, Distribution):
+        raise TypeError("Expected str, Requirement, or Distribution", dist)
+    return dist
+
+
+def load_entry_point(dist: _EPDistType, group: str, name: str) -> _ResolvedEntryPoint:
+    """Return `name` entry point of `group` for `dist` or raise ImportError"""
+    return get_distribution(dist).load_entry_point(group, name)
+
+
+@overload
+def get_entry_map(
+    dist: _EPDistType, group: None = None
+) -> dict[str, dict[str, EntryPoint]]: ...
+@overload
+def get_entry_map(dist: _EPDistType, group: str) -> dict[str, EntryPoint]: ...
+def get_entry_map(dist: _EPDistType, group: str | None = None):
+    """Return the entry point map for `group`, or the full entry map"""
+    return get_distribution(dist).get_entry_map(group)
+
+
+def get_entry_info(dist: _EPDistType, group: str, name: str) -> EntryPoint | None:
+    """Return the EntryPoint object for `group`+`name`, or ``None``"""
+    return get_distribution(dist).get_entry_info(group, name)
+
+
+class IMetadataProvider(Protocol):
+    def has_metadata(self, name: str) -> bool:
+        """Does the package's distribution contain the named metadata?"""
+        ...
+
+    def get_metadata(self, name: str) -> str:
+        """The named metadata resource as a string"""
+        ...
+
+    def get_metadata_lines(self, name: str) -> Iterator[str]:
+        """Yield named metadata resource as list of non-blank non-comment lines
+
+        Leading and trailing whitespace is stripped from each line, and lines
+        with ``#`` as the first non-blank character are omitted."""
+        ...
+
+    def metadata_isdir(self, name: str) -> bool:
+        """Is the named metadata a directory?  (like ``os.path.isdir()``)"""
+        ...
+
+    def metadata_listdir(self, name: str) -> list[str]:
+        """List of metadata names in the directory (like ``os.listdir()``)"""
+        ...
+
+    def run_script(self, script_name: str, namespace: dict[str, Any]) -> None:
+        """Execute the named script in the supplied namespace dictionary"""
+        ...
+
+
+class IResourceProvider(IMetadataProvider, Protocol):
+    """An object that provides access to package resources"""
+
+    def get_resource_filename(
+        self, manager: ResourceManager, resource_name: str
+    ) -> str:
+        """Return a true filesystem path for `resource_name`
+
+        `manager` must be a ``ResourceManager``"""
+        ...
+
+    def get_resource_stream(
+        self, manager: ResourceManager, resource_name: str
+    ) -> _ResourceStream:
+        """Return a readable file-like object for `resource_name`
+
+        `manager` must be a ``ResourceManager``"""
+        ...
+
+    def get_resource_string(
+        self, manager: ResourceManager, resource_name: str
+    ) -> bytes:
+        """Return the contents of `resource_name` as :obj:`bytes`
+
+        `manager` must be a ``ResourceManager``"""
+        ...
+
+    def has_resource(self, resource_name: str) -> bool:
+        """Does the package contain the named resource?"""
+        ...
+
+    def resource_isdir(self, resource_name: str) -> bool:
+        """Is the named resource a directory?  (like ``os.path.isdir()``)"""
+        ...
+
+    def resource_listdir(self, resource_name: str) -> list[str]:
+        """List of resource names in the directory (like ``os.listdir()``)"""
+        ...
+
+
+class WorkingSet:
+    """A collection of active distributions on sys.path (or a similar list)"""
+
+    def __init__(self, entries: Iterable[str] | None = None) -> None:
+        """Create working set from list of path entries (default=sys.path)"""
+        self.entries: list[str] = []
+        self.entry_keys: dict[str | None, list[str]] = {}
+        self.by_key: dict[str, Distribution] = {}
+        self.normalized_to_canonical_keys: dict[str, str] = {}
+        self.callbacks: list[Callable[[Distribution], object]] = []
+
+        if entries is None:
+            entries = sys.path
+
+        for entry in entries:
+            self.add_entry(entry)
+
+    @classmethod
+    def _build_master(cls):
+        """
+        Prepare the master working set.
+        """
+        ws = cls()
+        try:
+            from __main__ import __requires__
+        except ImportError:
+            # The main program does not list any requirements
+            return ws
+
+        # ensure the requirements are met
+        try:
+            ws.require(__requires__)
+        except VersionConflict:
+            return cls._build_from_requirements(__requires__)
+
+        return ws
+
+    @classmethod
+    def _build_from_requirements(cls, req_spec):
+        """
+        Build a working set from a requirement spec. Rewrites sys.path.
+        """
+        # try it without defaults already on sys.path
+        # by starting with an empty path
+        ws = cls([])
+        reqs = parse_requirements(req_spec)
+        dists = ws.resolve(reqs, Environment())
+        for dist in dists:
+            ws.add(dist)
+
+        # add any missing entries from sys.path
+        for entry in sys.path:
+            if entry not in ws.entries:
+                ws.add_entry(entry)
+
+        # then copy back to sys.path
+        sys.path[:] = ws.entries
+        return ws
+
+    def add_entry(self, entry: str) -> None:
+        """Add a path item to ``.entries``, finding any distributions on it
+
+        ``find_distributions(entry, True)`` is used to find distributions
+        corresponding to the path entry, and they are added.  `entry` is
+        always appended to ``.entries``, even if it is already present.
+        (This is because ``sys.path`` can contain the same value more than
+        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
+        equal ``sys.path``.)
+        """
+        self.entry_keys.setdefault(entry, [])
+        self.entries.append(entry)
+        for dist in find_distributions(entry, True):
+            self.add(dist, entry, False)
+
+    def __contains__(self, dist: Distribution) -> bool:
+        """True if `dist` is the active distribution for its project"""
+        return self.by_key.get(dist.key) == dist
+
+    def find(self, req: Requirement) -> Distribution | None:
+        """Find a distribution matching requirement `req`
+
+        If there is an active distribution for the requested project, this
+        returns it as long as it meets the version requirement specified by
+        `req`.  But, if there is an active distribution for the project and it
+        does *not* meet the `req` requirement, ``VersionConflict`` is raised.
+        If there is no active distribution for the requested project, ``None``
+        is returned.
+        """
+        dist: Distribution | None = None
+
+        candidates = (
+            req.key,
+            self.normalized_to_canonical_keys.get(req.key),
+            safe_name(req.key).replace(".", "-"),
+        )
+
+        for candidate in filter(None, candidates):
+            dist = self.by_key.get(candidate)
+            if dist:
+                req.key = candidate
+                break
+
+        if dist is not None and dist not in req:
+            # XXX add more info
+            raise VersionConflict(dist, req)
+        return dist
+
+    def iter_entry_points(
+        self, group: str, name: str | None = None
+    ) -> Iterator[EntryPoint]:
+        """Yield entry point objects from `group` matching `name`
+
+        If `name` is None, yields all entry points in `group` from all
+        distributions in the working set, otherwise only ones matching
+        both `group` and `name` are yielded (in distribution order).
+        """
+        return (
+            entry
+            for dist in self
+            for entry in dist.get_entry_map(group).values()
+            if name is None or name == entry.name
+        )
+
+    def run_script(self, requires: str, script_name: str) -> None:
+        """Locate distribution for `requires` and run `script_name` script"""
+        ns = sys._getframe(1).f_globals
+        name = ns['__name__']
+        ns.clear()
+        ns['__name__'] = name
+        self.require(requires)[0].run_script(script_name, ns)
+
+    def __iter__(self) -> Iterator[Distribution]:
+        """Yield distributions for non-duplicate projects in the working set
+
+        The yield order is the order in which the items' path entries were
+        added to the working set.
+        """
+        seen = set()
+        for item in self.entries:
+            if item not in self.entry_keys:
+                # workaround a cache issue
+                continue
+
+            for key in self.entry_keys[item]:
+                if key not in seen:
+                    seen.add(key)
+                    yield self.by_key[key]
+
+    def add(
+        self,
+        dist: Distribution,
+        entry: str | None = None,
+        insert: bool = True,
+        replace: bool = False,
+    ) -> None:
+        """Add `dist` to working set, associated with `entry`
+
+        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
+        On exit from this routine, `entry` is added to the end of the working
+        set's ``.entries`` (if it wasn't already present).
+
+        `dist` is only added to the working set if it's for a project that
+        doesn't already have a distribution in the set, unless `replace=True`.
+        If it's added, any callbacks registered with the ``subscribe()`` method
+        will be called.
+        """
+        if insert:
+            dist.insert_on(self.entries, entry, replace=replace)
+
+        if entry is None:
+            entry = dist.location
+        keys = self.entry_keys.setdefault(entry, [])
+        keys2 = self.entry_keys.setdefault(dist.location, [])
+        if not replace and dist.key in self.by_key:
+            # ignore hidden distros
+            return
+
+        self.by_key[dist.key] = dist
+        normalized_name = packaging.utils.canonicalize_name(dist.key)
+        self.normalized_to_canonical_keys[normalized_name] = dist.key
+        if dist.key not in keys:
+            keys.append(dist.key)
+        if dist.key not in keys2:
+            keys2.append(dist.key)
+        self._added_new(dist)
+
+    @overload
+    def resolve(
+        self,
+        requirements: Iterable[Requirement],
+        env: Environment | None,
+        installer: _StrictInstallerType[_DistributionT],
+        replace_conflicting: bool = False,
+        extras: tuple[str, ...] | None = None,
+    ) -> list[_DistributionT]: ...
+    @overload
+    def resolve(
+        self,
+        requirements: Iterable[Requirement],
+        env: Environment | None = None,
+        *,
+        installer: _StrictInstallerType[_DistributionT],
+        replace_conflicting: bool = False,
+        extras: tuple[str, ...] | None = None,
+    ) -> list[_DistributionT]: ...
+    @overload
+    def resolve(
+        self,
+        requirements: Iterable[Requirement],
+        env: Environment | None = None,
+        installer: _InstallerType | None = None,
+        replace_conflicting: bool = False,
+        extras: tuple[str, ...] | None = None,
+    ) -> list[Distribution]: ...
+    def resolve(
+        self,
+        requirements: Iterable[Requirement],
+        env: Environment | None = None,
+        installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None,
+        replace_conflicting: bool = False,
+        extras: tuple[str, ...] | None = None,
+    ) -> list[Distribution] | list[_DistributionT]:
+        """List all distributions needed to (recursively) meet `requirements`
+
+        `requirements` must be a sequence of ``Requirement`` objects.  `env`,
+        if supplied, should be an ``Environment`` instance.  If
+        not supplied, it defaults to all distributions available within any
+        entry or distribution in the working set.  `installer`, if supplied,
+        will be invoked with each requirement that cannot be met by an
+        already-installed distribution; it should return a ``Distribution`` or
+        ``None``.
+
+        Unless `replace_conflicting=True`, raises a VersionConflict exception
+        if
+        any requirements are found on the path that have the correct name but
+        the wrong version.  Otherwise, if an `installer` is supplied it will be
+        invoked to obtain the correct version of the requirement and activate
+        it.
+
+        `extras` is a list of the extras to be used with these requirements.
+        This is important because extra requirements may look like `my_req;
+        extra = "my_extra"`, which would otherwise be interpreted as a purely
+        optional requirement.  Instead, we want to be able to assert that these
+        requirements are truly required.
+        """
+
+        # set up the stack
+        requirements = list(requirements)[::-1]
+        # set of processed requirements
+        processed = set()
+        # key -> dist
+        best: dict[str, Distribution] = {}
+        to_activate: list[Distribution] = []
+
+        req_extras = _ReqExtras()
+
+        # Mapping of requirement to set of distributions that required it;
+        # useful for reporting info about conflicts.
+        required_by = collections.defaultdict[Requirement, set[str]](set)
+
+        while requirements:
+            # process dependencies breadth-first
+            req = requirements.pop(0)
+            if req in processed:
+                # Ignore cyclic or redundant dependencies
+                continue
+
+            if not req_extras.markers_pass(req, extras):
+                continue
+
+            dist = self._resolve_dist(
+                req, best, replace_conflicting, env, installer, required_by, to_activate
+            )
+
+            # push the new requirements onto the stack
+            new_requirements = dist.requires(req.extras)[::-1]
+            requirements.extend(new_requirements)
+
+            # Register the new requirements needed by req
+            for new_requirement in new_requirements:
+                required_by[new_requirement].add(req.project_name)
+                req_extras[new_requirement] = req.extras
+
+            processed.add(req)
+
+        # return list of distros to activate
+        return to_activate
+
+    def _resolve_dist(
+        self, req, best, replace_conflicting, env, installer, required_by, to_activate
+    ) -> Distribution:
+        dist = best.get(req.key)
+        if dist is None:
+            # Find the best distribution and add it to the map
+            dist = self.by_key.get(req.key)
+            if dist is None or (dist not in req and replace_conflicting):
+                ws = self
+                if env is None:
+                    if dist is None:
+                        env = Environment(self.entries)
+                    else:
+                        # Use an empty environment and workingset to avoid
+                        # any further conflicts with the conflicting
+                        # distribution
+                        env = Environment([])
+                        ws = WorkingSet([])
+                dist = best[req.key] = env.best_match(
+                    req, ws, installer, replace_conflicting=replace_conflicting
+                )
+                if dist is None:
+                    requirers = required_by.get(req, None)
+                    raise DistributionNotFound(req, requirers)
+            to_activate.append(dist)
+        if dist not in req:
+            # Oops, the "best" so far conflicts with a dependency
+            dependent_req = required_by[req]
+            raise VersionConflict(dist, req).with_context(dependent_req)
+        return dist
+
+    @overload
+    def find_plugins(
+        self,
+        plugin_env: Environment,
+        full_env: Environment | None,
+        installer: _StrictInstallerType[_DistributionT],
+        fallback: bool = True,
+    ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ...
+    @overload
+    def find_plugins(
+        self,
+        plugin_env: Environment,
+        full_env: Environment | None = None,
+        *,
+        installer: _StrictInstallerType[_DistributionT],
+        fallback: bool = True,
+    ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ...
+    @overload
+    def find_plugins(
+        self,
+        plugin_env: Environment,
+        full_env: Environment | None = None,
+        installer: _InstallerType | None = None,
+        fallback: bool = True,
+    ) -> tuple[list[Distribution], dict[Distribution, Exception]]: ...
+    def find_plugins(
+        self,
+        plugin_env: Environment,
+        full_env: Environment | None = None,
+        installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None,
+        fallback: bool = True,
+    ) -> tuple[
+        list[Distribution] | list[_DistributionT],
+        dict[Distribution, Exception],
+    ]:
+        """Find all activatable distributions in `plugin_env`
+
+        Example usage::
+
+            distributions, errors = working_set.find_plugins(
+                Environment(plugin_dirlist)
+            )
+            # add plugins+libs to sys.path
+            map(working_set.add, distributions)
+            # display errors
+            print('Could not load', errors)
+
+        The `plugin_env` should be an ``Environment`` instance that contains
+        only distributions that are in the project's "plugin directory" or
+        directories. The `full_env`, if supplied, should be an ``Environment``
+        contains all currently-available distributions.  If `full_env` is not
+        supplied, one is created automatically from the ``WorkingSet`` this
+        method is called on, which will typically mean that every directory on
+        ``sys.path`` will be scanned for distributions.
+
+        `installer` is a standard installer callback as used by the
+        ``resolve()`` method. The `fallback` flag indicates whether we should
+        attempt to resolve older versions of a plugin if the newest version
+        cannot be resolved.
+
+        This method returns a 2-tuple: (`distributions`, `error_info`), where
+        `distributions` is a list of the distributions found in `plugin_env`
+        that were loadable, along with any other distributions that are needed
+        to resolve their dependencies.  `error_info` is a dictionary mapping
+        unloadable plugin distributions to an exception instance describing the
+        error that occurred. Usually this will be a ``DistributionNotFound`` or
+        ``VersionConflict`` instance.
+        """
+
+        plugin_projects = list(plugin_env)
+        # scan project names in alphabetic order
+        plugin_projects.sort()
+
+        error_info: dict[Distribution, Exception] = {}
+        distributions: dict[Distribution, Exception | None] = {}
+
+        if full_env is None:
+            env = Environment(self.entries)
+            env += plugin_env
+        else:
+            env = full_env + plugin_env
+
+        shadow_set = self.__class__([])
+        # put all our entries in shadow_set
+        list(map(shadow_set.add, self))
+
+        for project_name in plugin_projects:
+            for dist in plugin_env[project_name]:
+                req = [dist.as_requirement()]
+
+                try:
+                    resolvees = shadow_set.resolve(req, env, installer)
+
+                except ResolutionError as v:
+                    # save error info
+                    error_info[dist] = v
+                    if fallback:
+                        # try the next older version of project
+                        continue
+                    else:
+                        # give up on this project, keep going
+                        break
+
+                else:
+                    list(map(shadow_set.add, resolvees))
+                    distributions.update(dict.fromkeys(resolvees))
+
+                    # success, no need to try any more versions of this project
+                    break
+
+        sorted_distributions = list(distributions)
+        sorted_distributions.sort()
+
+        return sorted_distributions, error_info
+
+    def require(self, *requirements: _NestedStr) -> list[Distribution]:
+        """Ensure that distributions matching `requirements` are activated
+
+        `requirements` must be a string or a (possibly-nested) sequence
+        thereof, specifying the distributions and versions required.  The
+        return value is a sequence of the distributions that needed to be
+        activated to fulfill the requirements; all relevant distributions are
+        included, even if they were already activated in this working set.
+        """
+        needed = self.resolve(parse_requirements(requirements))
+
+        for dist in needed:
+            self.add(dist)
+
+        return needed
+
+    def subscribe(
+        self, callback: Callable[[Distribution], object], existing: bool = True
+    ) -> None:
+        """Invoke `callback` for all distributions
+
+        If `existing=True` (default),
+        call on all existing ones, as well.
+        """
+        if callback in self.callbacks:
+            return
+        self.callbacks.append(callback)
+        if not existing:
+            return
+        for dist in self:
+            callback(dist)
+
+    def _added_new(self, dist) -> None:
+        for callback in self.callbacks:
+            callback(dist)
+
+    def __getstate__(
+        self,
+    ) -> tuple[
+        list[str],
+        dict[str | None, list[str]],
+        dict[str, Distribution],
+        dict[str, str],
+        list[Callable[[Distribution], object]],
+    ]:
+        return (
+            self.entries[:],
+            self.entry_keys.copy(),
+            self.by_key.copy(),
+            self.normalized_to_canonical_keys.copy(),
+            self.callbacks[:],
+        )
+
+    def __setstate__(self, e_k_b_n_c) -> None:
+        entries, keys, by_key, normalized_to_canonical_keys, callbacks = e_k_b_n_c
+        self.entries = entries[:]
+        self.entry_keys = keys.copy()
+        self.by_key = by_key.copy()
+        self.normalized_to_canonical_keys = normalized_to_canonical_keys.copy()
+        self.callbacks = callbacks[:]
+
+
+class _ReqExtras(dict["Requirement", tuple[str, ...]]):
+    """
+    Map each requirement to the extras that demanded it.
+    """
+
+    def markers_pass(self, req: Requirement, extras: tuple[str, ...] | None = None):
+        """
+        Evaluate markers for req against each extra that
+        demanded it.
+
+        Return False if the req has a marker and fails
+        evaluation. Otherwise, return True.
+        """
+        return not req.marker or any(
+            req.marker.evaluate({'extra': extra})
+            for extra in self.get(req, ()) + (extras or ("",))
+        )
+
+
+class Environment:
+    """Searchable snapshot of distributions on a search path"""
+
+    def __init__(
+        self,
+        search_path: Iterable[str] | None = None,
+        platform: str | None = get_supported_platform(),
+        python: str | None = PY_MAJOR,
+    ) -> None:
+        """Snapshot distributions available on a search path
+
+        Any distributions found on `search_path` are added to the environment.
+        `search_path` should be a sequence of ``sys.path`` items.  If not
+        supplied, ``sys.path`` is used.
+
+        `platform` is an optional string specifying the name of the platform
+        that platform-specific distributions must be compatible with.  If
+        unspecified, it defaults to the current platform.  `python` is an
+        optional string naming the desired version of Python (e.g. ``'3.6'``);
+        it defaults to the current version.
+
+        You may explicitly set `platform` (and/or `python`) to ``None`` if you
+        wish to map *all* distributions, not just those compatible with the
+        running platform or Python version.
+        """
+        self._distmap: dict[str, list[Distribution]] = {}
+        self.platform = platform
+        self.python = python
+        self.scan(search_path)
+
+    def can_add(self, dist: Distribution) -> bool:
+        """Is distribution `dist` acceptable for this environment?
+
+        The distribution must match the platform and python version
+        requirements specified when this environment was created, or False
+        is returned.
+        """
+        py_compat = (
+            self.python is None
+            or dist.py_version is None
+            or dist.py_version == self.python
+        )
+        return py_compat and compatible_platforms(dist.platform, self.platform)
+
+    def remove(self, dist: Distribution) -> None:
+        """Remove `dist` from the environment"""
+        self._distmap[dist.key].remove(dist)
+
+    def scan(self, search_path: Iterable[str] | None = None) -> None:
+        """Scan `search_path` for distributions usable in this environment
+
+        Any distributions found are added to the environment.
+        `search_path` should be a sequence of ``sys.path`` items.  If not
+        supplied, ``sys.path`` is used.  Only distributions conforming to
+        the platform/python version defined at initialization are added.
+        """
+        if search_path is None:
+            search_path = sys.path
+
+        for item in search_path:
+            for dist in find_distributions(item):
+                self.add(dist)
+
+    def __getitem__(self, project_name: str) -> list[Distribution]:
+        """Return a newest-to-oldest list of distributions for `project_name`
+
+        Uses case-insensitive `project_name` comparison, assuming all the
+        project's distributions use their project's name converted to all
+        lowercase as their key.
+
+        """
+        distribution_key = project_name.lower()
+        return self._distmap.get(distribution_key, [])
+
+    def add(self, dist: Distribution) -> None:
+        """Add `dist` if we ``can_add()`` it and it has not already been added"""
+        if self.can_add(dist) and dist.has_version():
+            dists = self._distmap.setdefault(dist.key, [])
+            if dist not in dists:
+                dists.append(dist)
+                dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
+
+    @overload
+    def best_match(
+        self,
+        req: Requirement,
+        working_set: WorkingSet,
+        installer: _StrictInstallerType[_DistributionT],
+        replace_conflicting: bool = False,
+    ) -> _DistributionT: ...
+    @overload
+    def best_match(
+        self,
+        req: Requirement,
+        working_set: WorkingSet,
+        installer: _InstallerType | None = None,
+        replace_conflicting: bool = False,
+    ) -> Distribution | None: ...
+    def best_match(
+        self,
+        req: Requirement,
+        working_set: WorkingSet,
+        installer: _InstallerType | None | _StrictInstallerType[_DistributionT] = None,
+        replace_conflicting: bool = False,
+    ) -> Distribution | None:
+        """Find distribution best matching `req` and usable on `working_set`
+
+        This calls the ``find(req)`` method of the `working_set` to see if a
+        suitable distribution is already active.  (This may raise
+        ``VersionConflict`` if an unsuitable version of the project is already
+        active in the specified `working_set`.)  If a suitable distribution
+        isn't active, this method returns the newest distribution in the
+        environment that meets the ``Requirement`` in `req`.  If no suitable
+        distribution is found, and `installer` is supplied, then the result of
+        calling the environment's ``obtain(req, installer)`` method will be
+        returned.
+        """
+        try:
+            dist = working_set.find(req)
+        except VersionConflict:
+            if not replace_conflicting:
+                raise
+            dist = None
+        if dist is not None:
+            return dist
+        for dist in self[req.key]:
+            if dist in req:
+                return dist
+        # try to download/install
+        return self.obtain(req, installer)
+
+    @overload
+    def obtain(
+        self,
+        requirement: Requirement,
+        installer: _StrictInstallerType[_DistributionT],
+    ) -> _DistributionT: ...
+    @overload
+    def obtain(
+        self,
+        requirement: Requirement,
+        installer: Callable[[Requirement], None] | None = None,
+    ) -> None: ...
+    @overload
+    def obtain(
+        self,
+        requirement: Requirement,
+        installer: _InstallerType | None = None,
+    ) -> Distribution | None: ...
+    def obtain(
+        self,
+        requirement: Requirement,
+        installer: Callable[[Requirement], None]
+        | _InstallerType
+        | None
+        | _StrictInstallerType[_DistributionT] = None,
+    ) -> Distribution | None:
+        """Obtain a distribution matching `requirement` (e.g. via download)
+
+        Obtain a distro that matches requirement (e.g. via download).  In the
+        base ``Environment`` class, this routine just returns
+        ``installer(requirement)``, unless `installer` is None, in which case
+        None is returned instead.  This method is a hook that allows subclasses
+        to attempt other ways of obtaining a distribution before falling back
+        to the `installer` argument."""
+        return installer(requirement) if installer else None
+
+    def __iter__(self) -> Iterator[str]:
+        """Yield the unique project names of the available distributions"""
+        for key in self._distmap.keys():
+            if self[key]:
+                yield key
+
+    def __iadd__(self, other: Distribution | Environment) -> Self:
+        """In-place addition of a distribution or environment"""
+        if isinstance(other, Distribution):
+            self.add(other)
+        elif isinstance(other, Environment):
+            for project in other:
+                for dist in other[project]:
+                    self.add(dist)
+        else:
+            raise TypeError(f"Can't add {other!r} to environment")
+        return self
+
+    def __add__(self, other: Distribution | Environment) -> Self:
+        """Add an environment or distribution to an environment"""
+        new = self.__class__([], platform=None, python=None)
+        for env in self, other:
+            new += env
+        return new
+
+
+# XXX backward compatibility
+AvailableDistributions = Environment
+
+
+class ExtractionError(RuntimeError):
+    """An error occurred extracting a resource
+
+    The following attributes are available from instances of this exception:
+
+    manager
+        The resource manager that raised this exception
+
+    cache_path
+        The base directory for resource extraction
+
+    original_error
+        The exception instance that caused extraction to fail
+    """
+
+    manager: ResourceManager
+    cache_path: str
+    original_error: BaseException | None
+
+
+class ResourceManager:
+    """Manage resource extraction and packages"""
+
+    extraction_path: str | None = None
+
+    def __init__(self) -> None:
+        # acts like a set
+        self.cached_files: dict[str, Literal[True]] = {}
+
+    def resource_exists(
+        self, package_or_requirement: _PkgReqType, resource_name: str
+    ) -> bool:
+        """Does the named resource exist?"""
+        return get_provider(package_or_requirement).has_resource(resource_name)
+
+    def resource_isdir(
+        self, package_or_requirement: _PkgReqType, resource_name: str
+    ) -> bool:
+        """Is the named resource an existing directory?"""
+        return get_provider(package_or_requirement).resource_isdir(resource_name)
+
+    def resource_filename(
+        self, package_or_requirement: _PkgReqType, resource_name: str
+    ) -> str:
+        """Return a true filesystem path for specified resource"""
+        return get_provider(package_or_requirement).get_resource_filename(
+            self, resource_name
+        )
+
+    def resource_stream(
+        self, package_or_requirement: _PkgReqType, resource_name: str
+    ) -> _ResourceStream:
+        """Return a readable file-like object for specified resource"""
+        return get_provider(package_or_requirement).get_resource_stream(
+            self, resource_name
+        )
+
+    def resource_string(
+        self, package_or_requirement: _PkgReqType, resource_name: str
+    ) -> bytes:
+        """Return specified resource as :obj:`bytes`"""
+        return get_provider(package_or_requirement).get_resource_string(
+            self, resource_name
+        )
+
+    def resource_listdir(
+        self, package_or_requirement: _PkgReqType, resource_name: str
+    ) -> list[str]:
+        """List the contents of the named resource directory"""
+        return get_provider(package_or_requirement).resource_listdir(resource_name)
+
+    def extraction_error(self) -> NoReturn:
+        """Give an error message for problems extracting file(s)"""
+
+        old_exc = sys.exc_info()[1]
+        cache_path = self.extraction_path or get_default_cache()
+
+        tmpl = textwrap.dedent(
+            """
+            Can't extract file(s) to egg cache
+
+            The following error occurred while trying to extract file(s)
+            to the Python egg cache:
+
+              {old_exc}
+
+            The Python egg cache directory is currently set to:
+
+              {cache_path}
+
+            Perhaps your account does not have write access to this directory?
+            You can change the cache directory by setting the PYTHON_EGG_CACHE
+            environment variable to point to an accessible directory.
+            """
+        ).lstrip()
+        err = ExtractionError(tmpl.format(**locals()))
+        err.manager = self
+        err.cache_path = cache_path
+        err.original_error = old_exc
+        raise err
+
+    def get_cache_path(self, archive_name: str, names: Iterable[StrPath] = ()) -> str:
+        """Return absolute location in cache for `archive_name` and `names`
+
+        The parent directory of the resulting path will be created if it does
+        not already exist.  `archive_name` should be the base filename of the
+        enclosing egg (which may not be the name of the enclosing zipfile!),
+        including its ".egg" extension.  `names`, if provided, should be a
+        sequence of path name parts "under" the egg's extraction location.
+
+        This method should only be called by resource providers that need to
+        obtain an extraction location, and only for names they intend to
+        extract, as it tracks the generated names for possible cleanup later.
+        """
+        extract_path = self.extraction_path or get_default_cache()
+        target_path = os.path.join(extract_path, archive_name + '-tmp', *names)
+        try:
+            _bypass_ensure_directory(target_path)
+        except Exception:
+            self.extraction_error()
+
+        self._warn_unsafe_extraction_path(extract_path)
+
+        self.cached_files[target_path] = True
+        return target_path
+
+    @staticmethod
+    def _warn_unsafe_extraction_path(path) -> None:
+        """
+        If the default extraction path is overridden and set to an insecure
+        location, such as /tmp, it opens up an opportunity for an attacker to
+        replace an extracted file with an unauthorized payload. Warn the user
+        if a known insecure location is used.
+
+        See Distribute #375 for more details.
+        """
+        if os.name == 'nt' and not path.startswith(os.environ['windir']):
+            # On Windows, permissions are generally restrictive by default
+            #  and temp directories are not writable by other users, so
+            #  bypass the warning.
+            return
+        mode = os.stat(path).st_mode
+        if mode & stat.S_IWOTH or mode & stat.S_IWGRP:
+            msg = (
+                "Extraction path is writable by group/others "
+                "and vulnerable to attack when "
+                "used with get_resource_filename ({path}). "
+                "Consider a more secure "
+                "location (set with .set_extraction_path or the "
+                "PYTHON_EGG_CACHE environment variable)."
+            ).format(**locals())
+            warnings.warn(msg, UserWarning)
+
+    def postprocess(self, tempname: StrOrBytesPath, filename: StrOrBytesPath) -> None:
+        """Perform any platform-specific postprocessing of `tempname`
+
+        This is where Mac header rewrites should be done; other platforms don't
+        have anything special they should do.
+
+        Resource providers should call this method ONLY after successfully
+        extracting a compressed resource.  They must NOT call it on resources
+        that are already in the filesystem.
+
+        `tempname` is the current (temporary) name of the file, and `filename`
+        is the name it will be renamed to by the caller after this routine
+        returns.
+        """
+
+        if os.name == 'posix':
+            # Make the resource executable
+            mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777
+            os.chmod(tempname, mode)
+
+    def set_extraction_path(self, path: str) -> None:
+        """Set the base path where resources will be extracted to, if needed.
+
+        If you do not call this routine before any extractions take place, the
+        path defaults to the return value of ``get_default_cache()``.  (Which
+        is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
+        platform-specific fallbacks.  See that routine's documentation for more
+        details.)
+
+        Resources are extracted to subdirectories of this path based upon
+        information given by the ``IResourceProvider``.  You may set this to a
+        temporary directory, but then you must call ``cleanup_resources()`` to
+        delete the extracted files when done.  There is no guarantee that
+        ``cleanup_resources()`` will be able to remove all extracted files.
+
+        (Note: you may not change the extraction path for a given resource
+        manager once resources have been extracted, unless you first call
+        ``cleanup_resources()``.)
+        """
+        if self.cached_files:
+            raise ValueError("Can't change extraction path, files already extracted")
+
+        self.extraction_path = path
+
+    def cleanup_resources(self, force: bool = False) -> list[str]:
+        """
+        Delete all extracted resource files and directories, returning a list
+        of the file and directory names that could not be successfully removed.
+        This function does not have any concurrency protection, so it should
+        generally only be called when the extraction path is a temporary
+        directory exclusive to a single process.  This method is not
+        automatically called; you must call it explicitly or register it as an
+        ``atexit`` function if you wish to ensure cleanup of a temporary
+        directory used for extractions.
+        """
+        # XXX
+        return []
+
+
+def get_default_cache() -> str:
+    """
+    Return the ``PYTHON_EGG_CACHE`` environment variable
+    or a platform-relevant user cache dir for an app
+    named "Python-Eggs".
+    """
+    return os.environ.get('PYTHON_EGG_CACHE') or _user_cache_dir(appname='Python-Eggs')
+
+
+def safe_name(name: str) -> str:
+    """Convert an arbitrary string to a standard distribution name
+
+    Any runs of non-alphanumeric/. characters are replaced with a single '-'.
+    """
+    return re.sub('[^A-Za-z0-9.]+', '-', name)
+
+
+def safe_version(version: str) -> str:
+    """
+    Convert an arbitrary string to a standard version string
+    """
+    try:
+        # normalize the version
+        return str(packaging.version.Version(version))
+    except packaging.version.InvalidVersion:
+        version = version.replace(' ', '.')
+        return re.sub('[^A-Za-z0-9.]+', '-', version)
+
+
+def _forgiving_version(version) -> str:
+    """Fallback when ``safe_version`` is not safe enough
+    >>> parse_version(_forgiving_version('0.23ubuntu1'))
+    
+    >>> parse_version(_forgiving_version('0.23-'))
+    
+    >>> parse_version(_forgiving_version('0.-_'))
+    
+    >>> parse_version(_forgiving_version('42.+?1'))
+    
+    >>> parse_version(_forgiving_version('hello world'))
+    
+    """
+    version = version.replace(' ', '.')
+    match = _PEP440_FALLBACK.search(version)
+    if match:
+        safe = match["safe"]
+        rest = version[len(safe) :]
+    else:
+        safe = "0"
+        rest = version
+    local = f"sanitized.{_safe_segment(rest)}".strip(".")
+    return f"{safe}.dev0+{local}"
+
+
+def _safe_segment(segment):
+    """Convert an arbitrary string into a safe segment"""
+    segment = re.sub('[^A-Za-z0-9.]+', '-', segment)
+    segment = re.sub('-[^A-Za-z0-9]+', '-', segment)
+    return re.sub(r'\.[^A-Za-z0-9]+', '.', segment).strip(".-")
+
+
+def safe_extra(extra: str) -> str:
+    """Convert an arbitrary string to a standard 'extra' name
+
+    Any runs of non-alphanumeric characters are replaced with a single '_',
+    and the result is always lowercased.
+    """
+    return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()
+
+
+def to_filename(name: str) -> str:
+    """Convert a project or version name to its filename-escaped form
+
+    Any '-' characters are currently replaced with '_'.
+    """
+    return name.replace('-', '_')
+
+
+def invalid_marker(text: str) -> SyntaxError | Literal[False]:
+    """
+    Validate text as a PEP 508 environment marker; return an exception
+    if invalid or False otherwise.
+    """
+    try:
+        evaluate_marker(text)
+    except SyntaxError as e:
+        e.filename = None
+        e.lineno = None
+        return e
+    return False
+
+
+def evaluate_marker(text: str, extra: str | None = None) -> bool:
+    """
+    Evaluate a PEP 508 environment marker.
+    Return a boolean indicating the marker result in this environment.
+    Raise SyntaxError if marker is invalid.
+
+    This implementation uses the 'pyparsing' module.
+    """
+    try:
+        marker = packaging.markers.Marker(text)
+        return marker.evaluate()
+    except packaging.markers.InvalidMarker as e:
+        raise SyntaxError(e) from e
+
+
+class NullProvider:
+    """Try to implement resources and metadata for arbitrary PEP 302 loaders"""
+
+    egg_name: str | None = None
+    egg_info: str | None = None
+    loader: LoaderProtocol | None = None
+
+    def __init__(self, module: _ModuleLike) -> None:
+        self.loader = getattr(module, '__loader__', None)
+        self.module_path = os.path.dirname(getattr(module, '__file__', ''))
+
+    def get_resource_filename(
+        self, manager: ResourceManager, resource_name: str
+    ) -> str:
+        return self._fn(self.module_path, resource_name)
+
+    def get_resource_stream(
+        self, manager: ResourceManager, resource_name: str
+    ) -> BinaryIO:
+        return io.BytesIO(self.get_resource_string(manager, resource_name))
+
+    def get_resource_string(
+        self, manager: ResourceManager, resource_name: str
+    ) -> bytes:
+        return self._get(self._fn(self.module_path, resource_name))
+
+    def has_resource(self, resource_name: str) -> bool:
+        return self._has(self._fn(self.module_path, resource_name))
+
+    def _get_metadata_path(self, name):
+        return self._fn(self.egg_info, name)
+
+    def has_metadata(self, name: str) -> bool:
+        if not self.egg_info:
+            return False
+
+        path = self._get_metadata_path(name)
+        return self._has(path)
+
+    def get_metadata(self, name: str) -> str:
+        if not self.egg_info:
+            return ""
+        path = self._get_metadata_path(name)
+        value = self._get(path)
+        try:
+            return value.decode('utf-8')
+        except UnicodeDecodeError as exc:
+            # Include the path in the error message to simplify
+            # troubleshooting, and without changing the exception type.
+            exc.reason += f' in {name} file at path: {path}'
+            raise
+
+    def get_metadata_lines(self, name: str) -> Iterator[str]:
+        return yield_lines(self.get_metadata(name))
+
+    def resource_isdir(self, resource_name: str) -> bool:
+        return self._isdir(self._fn(self.module_path, resource_name))
+
+    def metadata_isdir(self, name: str) -> bool:
+        return bool(self.egg_info and self._isdir(self._fn(self.egg_info, name)))
+
+    def resource_listdir(self, resource_name: str) -> list[str]:
+        return self._listdir(self._fn(self.module_path, resource_name))
+
+    def metadata_listdir(self, name: str) -> list[str]:
+        if self.egg_info:
+            return self._listdir(self._fn(self.egg_info, name))
+        return []
+
+    def run_script(self, script_name: str, namespace: dict[str, Any]) -> None:
+        script = 'scripts/' + script_name
+        if not self.has_metadata(script):
+            raise ResolutionError(
+                "Script {script!r} not found in metadata at {self.egg_info!r}".format(
+                    **locals()
+                ),
+            )
+
+        script_text = self.get_metadata(script).replace('\r\n', '\n')
+        script_text = script_text.replace('\r', '\n')
+        script_filename = self._fn(self.egg_info, script)
+        namespace['__file__'] = script_filename
+        if os.path.exists(script_filename):
+            source = _read_utf8_with_fallback(script_filename)
+            code = compile(source, script_filename, 'exec')
+            exec(code, namespace, namespace)
+        else:
+            from linecache import cache
+
+            cache[script_filename] = (
+                len(script_text),
+                0,
+                script_text.split('\n'),
+                script_filename,
+            )
+            script_code = compile(script_text, script_filename, 'exec')
+            exec(script_code, namespace, namespace)
+
+    def _has(self, path) -> bool:
+        raise NotImplementedError(
+            "Can't perform this operation for unregistered loader type"
+        )
+
+    def _isdir(self, path) -> bool:
+        raise NotImplementedError(
+            "Can't perform this operation for unregistered loader type"
+        )
+
+    def _listdir(self, path) -> list[str]:
+        raise NotImplementedError(
+            "Can't perform this operation for unregistered loader type"
+        )
+
+    def _fn(self, base: str | None, resource_name: str):
+        if base is None:
+            raise TypeError(
+                "`base` parameter in `_fn` is `None`. Either override this method or check the parameter first."
+            )
+        self._validate_resource_path(resource_name)
+        if resource_name:
+            return os.path.join(base, *resource_name.split('/'))
+        return base
+
+    @staticmethod
+    def _validate_resource_path(path) -> None:
+        """
+        Validate the resource paths according to the docs.
+        https://setuptools.pypa.io/en/latest/pkg_resources.html#basic-resource-access
+
+        >>> warned = getfixture('recwarn')
+        >>> warnings.simplefilter('always')
+        >>> vrp = NullProvider._validate_resource_path
+        >>> vrp('foo/bar.txt')
+        >>> bool(warned)
+        False
+        >>> vrp('../foo/bar.txt')
+        >>> bool(warned)
+        True
+        >>> warned.clear()
+        >>> vrp('/foo/bar.txt')
+        >>> bool(warned)
+        True
+        >>> vrp('foo/../../bar.txt')
+        >>> bool(warned)
+        True
+        >>> warned.clear()
+        >>> vrp('foo/f../bar.txt')
+        >>> bool(warned)
+        False
+
+        Windows path separators are straight-up disallowed.
+        >>> vrp(r'\\foo/bar.txt')
+        Traceback (most recent call last):
+        ...
+        ValueError: Use of .. or absolute path in a resource path \
+is not allowed.
+
+        >>> vrp(r'C:\\foo/bar.txt')
+        Traceback (most recent call last):
+        ...
+        ValueError: Use of .. or absolute path in a resource path \
+is not allowed.
+
+        Blank values are allowed
+
+        >>> vrp('')
+        >>> bool(warned)
+        False
+
+        Non-string values are not.
+
+        >>> vrp(None)
+        Traceback (most recent call last):
+        ...
+        AttributeError: ...
+        """
+        invalid = (
+            os.path.pardir in path.split(posixpath.sep)
+            or posixpath.isabs(path)
+            or ntpath.isabs(path)
+            or path.startswith("\\")
+        )
+        if not invalid:
+            return
+
+        msg = "Use of .. or absolute path in a resource path is not allowed."
+
+        # Aggressively disallow Windows absolute paths
+        if (path.startswith("\\") or ntpath.isabs(path)) and not posixpath.isabs(path):
+            raise ValueError(msg)
+
+        # for compatibility, warn; in future
+        # raise ValueError(msg)
+        issue_warning(
+            msg[:-1] + " and will raise exceptions in a future release.",
+            DeprecationWarning,
+        )
+
+    def _get(self, path) -> bytes:
+        if hasattr(self.loader, 'get_data') and self.loader:
+            # Already checked get_data exists
+            return self.loader.get_data(path)  # type: ignore[attr-defined]
+        raise NotImplementedError(
+            "Can't perform this operation for loaders without 'get_data()'"
+        )
+
+
+register_loader_type(object, NullProvider)
+
+
+def _parents(path):
+    """
+    yield all parents of path including path
+    """
+    last = None
+    while path != last:
+        yield path
+        last = path
+        path, _ = os.path.split(path)
+
+
+class EggProvider(NullProvider):
+    """Provider based on a virtual filesystem"""
+
+    def __init__(self, module: _ModuleLike) -> None:
+        super().__init__(module)
+        self._setup_prefix()
+
+    def _setup_prefix(self):
+        # Assume that metadata may be nested inside a "basket"
+        # of multiple eggs and use module_path instead of .archive.
+        eggs = filter(_is_egg_path, _parents(self.module_path))
+        egg = next(eggs, None)
+        egg and self._set_egg(egg)
+
+    def _set_egg(self, path: str) -> None:
+        self.egg_name = os.path.basename(path)
+        self.egg_info = os.path.join(path, 'EGG-INFO')
+        self.egg_root = path
+
+
+class DefaultProvider(EggProvider):
+    """Provides access to package resources in the filesystem"""
+
+    def _has(self, path) -> bool:
+        return os.path.exists(path)
+
+    def _isdir(self, path) -> bool:
+        return os.path.isdir(path)
+
+    def _listdir(self, path):
+        return os.listdir(path)
+
+    def get_resource_stream(
+        self, manager: object, resource_name: str
+    ) -> io.BufferedReader:
+        return open(self._fn(self.module_path, resource_name), 'rb')
+
+    def _get(self, path) -> bytes:
+        with open(path, 'rb') as stream:
+            return stream.read()
+
+    @classmethod
+    def _register(cls) -> None:
+        loader_names = (
+            'SourceFileLoader',
+            'SourcelessFileLoader',
+        )
+        for name in loader_names:
+            loader_cls = getattr(importlib.machinery, name, type(None))
+            register_loader_type(loader_cls, cls)
+
+
+DefaultProvider._register()
+
+
+class EmptyProvider(NullProvider):
+    """Provider that returns nothing for all requests"""
+
+    # A special case, we don't want all Providers inheriting from NullProvider to have a potentially None module_path
+    module_path: str | None = None  # type: ignore[assignment]
+
+    _isdir = _has = lambda self, path: False
+
+    def _get(self, path) -> bytes:
+        return b''
+
+    def _listdir(self, path):
+        return []
+
+    def __init__(self) -> None:
+        pass
+
+
+empty_provider = EmptyProvider()
+
+
+class ZipManifests(dict[str, "MemoizedZipManifests.manifest_mod"]):
+    """
+    zip manifest builder
+    """
+
+    # `path` could be `StrPath | IO[bytes]` but that violates the LSP for `MemoizedZipManifests.load`
+    @classmethod
+    def build(cls, path: str) -> dict[str, zipfile.ZipInfo]:
+        """
+        Build a dictionary similar to the zipimport directory
+        caches, except instead of tuples, store ZipInfo objects.
+
+        Use a platform-specific path separator (os.sep) for the path keys
+        for compatibility with pypy on Windows.
+        """
+        with zipfile.ZipFile(path) as zfile:
+            items = (
+                (
+                    name.replace('/', os.sep),
+                    zfile.getinfo(name),
+                )
+                for name in zfile.namelist()
+            )
+            return dict(items)
+
+    load = build
+
+
+class MemoizedZipManifests(ZipManifests):
+    """
+    Memoized zipfile manifests.
+    """
+
+    class manifest_mod(NamedTuple):
+        manifest: dict[str, zipfile.ZipInfo]
+        mtime: float
+
+    def load(self, path: str) -> dict[str, zipfile.ZipInfo]:  # type: ignore[override] # ZipManifests.load is a classmethod
+        """
+        Load a manifest at path or return a suitable manifest already loaded.
+        """
+        path = os.path.normpath(path)
+        mtime = os.stat(path).st_mtime
+
+        if path not in self or self[path].mtime != mtime:
+            manifest = self.build(path)
+            self[path] = self.manifest_mod(manifest, mtime)
+
+        return self[path].manifest
+
+
+class ZipProvider(EggProvider):
+    """Resource support for zips and eggs"""
+
+    eagers: list[str] | None = None
+    _zip_manifests = MemoizedZipManifests()
+    # ZipProvider's loader should always be a zipimporter or equivalent
+    loader: zipimport.zipimporter
+
+    def __init__(self, module: _ZipLoaderModule) -> None:
+        super().__init__(module)
+        self.zip_pre = self.loader.archive + os.sep
+
+    def _zipinfo_name(self, fspath):
+        # Convert a virtual filename (full path to file) into a zipfile subpath
+        # usable with the zipimport directory cache for our target archive
+        fspath = fspath.rstrip(os.sep)
+        if fspath == self.loader.archive:
+            return ''
+        if fspath.startswith(self.zip_pre):
+            return fspath[len(self.zip_pre) :]
+        raise AssertionError(f"{fspath} is not a subpath of {self.zip_pre}")
+
+    def _parts(self, zip_path):
+        # Convert a zipfile subpath into an egg-relative path part list.
+        # pseudo-fs path
+        fspath = self.zip_pre + zip_path
+        if fspath.startswith(self.egg_root + os.sep):
+            return fspath[len(self.egg_root) + 1 :].split(os.sep)
+        raise AssertionError(f"{fspath} is not a subpath of {self.egg_root}")
+
+    @property
+    def zipinfo(self):
+        return self._zip_manifests.load(self.loader.archive)
+
+    def get_resource_filename(
+        self, manager: ResourceManager, resource_name: str
+    ) -> str:
+        if not self.egg_name:
+            raise NotImplementedError(
+                "resource_filename() only supported for .egg, not .zip"
+            )
+        # no need to lock for extraction, since we use temp names
+        zip_path = self._resource_to_zip(resource_name)
+        eagers = self._get_eager_resources()
+        if '/'.join(self._parts(zip_path)) in eagers:
+            for name in eagers:
+                self._extract_resource(manager, self._eager_to_zip(name))
+        return self._extract_resource(manager, zip_path)
+
+    @staticmethod
+    def _get_date_and_size(zip_stat):
+        size = zip_stat.file_size
+        # ymdhms+wday, yday, dst
+        date_time = zip_stat.date_time + (0, 0, -1)
+        # 1980 offset already done
+        timestamp = time.mktime(date_time)
+        return timestamp, size
+
+    # FIXME: 'ZipProvider._extract_resource' is too complex (12)
+    def _extract_resource(self, manager: ResourceManager, zip_path) -> str:  # noqa: C901
+        if zip_path in self._index():
+            for name in self._index()[zip_path]:
+                last = self._extract_resource(manager, os.path.join(zip_path, name))
+            # return the extracted directory name
+            return os.path.dirname(last)
+
+        timestamp, _size = self._get_date_and_size(self.zipinfo[zip_path])
+
+        if not WRITE_SUPPORT:
+            raise OSError(
+                '"os.rename" and "os.unlink" are not supported on this platform'
+            )
+        try:
+            if not self.egg_name:
+                raise OSError(
+                    '"egg_name" is empty. This likely means no egg could be found from the "module_path".'
+                )
+            real_path = manager.get_cache_path(self.egg_name, self._parts(zip_path))
+
+            if self._is_current(real_path, zip_path):
+                return real_path
+
+            outf, tmpnam = _mkstemp(
+                ".$extract",
+                dir=os.path.dirname(real_path),
+            )
+            os.write(outf, self.loader.get_data(zip_path))
+            os.close(outf)
+            utime(tmpnam, (timestamp, timestamp))
+            manager.postprocess(tmpnam, real_path)
+
+            try:
+                rename(tmpnam, real_path)
+
+            except OSError:
+                if os.path.isfile(real_path):
+                    if self._is_current(real_path, zip_path):
+                        # the file became current since it was checked above,
+                        #  so proceed.
+                        return real_path
+                    # Windows, del old file and retry
+                    elif os.name == 'nt':
+                        unlink(real_path)
+                        rename(tmpnam, real_path)
+                        return real_path
+                raise
+
+        except OSError:
+            # report a user-friendly error
+            manager.extraction_error()
+
+        return real_path
+
+    def _is_current(self, file_path, zip_path):
+        """
+        Return True if the file_path is current for this zip_path
+        """
+        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])
+        if not os.path.isfile(file_path):
+            return False
+        stat = os.stat(file_path)
+        if stat.st_size != size or stat.st_mtime != timestamp:
+            return False
+        # check that the contents match
+        zip_contents = self.loader.get_data(zip_path)
+        with open(file_path, 'rb') as f:
+            file_contents = f.read()
+        return zip_contents == file_contents
+
+    def _get_eager_resources(self):
+        if self.eagers is None:
+            eagers = []
+            for name in ('native_libs.txt', 'eager_resources.txt'):
+                if self.has_metadata(name):
+                    eagers.extend(self.get_metadata_lines(name))
+            self.eagers = eagers
+        return self.eagers
+
+    def _index(self):
+        try:
+            return self._dirindex
+        except AttributeError:
+            ind = {}
+            for path in self.zipinfo:
+                parts = path.split(os.sep)
+                while parts:
+                    parent = os.sep.join(parts[:-1])
+                    if parent in ind:
+                        ind[parent].append(parts[-1])
+                        break
+                    else:
+                        ind[parent] = [parts.pop()]
+            self._dirindex = ind
+            return ind
+
+    def _has(self, fspath) -> bool:
+        zip_path = self._zipinfo_name(fspath)
+        return zip_path in self.zipinfo or zip_path in self._index()
+
+    def _isdir(self, fspath) -> bool:
+        return self._zipinfo_name(fspath) in self._index()
+
+    def _listdir(self, fspath):
+        return list(self._index().get(self._zipinfo_name(fspath), ()))
+
+    def _eager_to_zip(self, resource_name: str):
+        return self._zipinfo_name(self._fn(self.egg_root, resource_name))
+
+    def _resource_to_zip(self, resource_name: str):
+        return self._zipinfo_name(self._fn(self.module_path, resource_name))
+
+
+register_loader_type(zipimport.zipimporter, ZipProvider)
+
+
+class FileMetadata(EmptyProvider):
+    """Metadata handler for standalone PKG-INFO files
+
+    Usage::
+
+        metadata = FileMetadata("/path/to/PKG-INFO")
+
+    This provider rejects all data and metadata requests except for PKG-INFO,
+    which is treated as existing, and will be the contents of the file at
+    the provided location.
+    """
+
+    def __init__(self, path: StrPath) -> None:
+        self.path = path
+
+    def _get_metadata_path(self, name):
+        return self.path
+
+    def has_metadata(self, name: str) -> bool:
+        return name == 'PKG-INFO' and os.path.isfile(self.path)
+
+    def get_metadata(self, name: str) -> str:
+        if name != 'PKG-INFO':
+            raise KeyError("No metadata except PKG-INFO is available")
+
+        with open(self.path, encoding='utf-8', errors="replace") as f:
+            metadata = f.read()
+        self._warn_on_replacement(metadata)
+        return metadata
+
+    def _warn_on_replacement(self, metadata) -> None:
+        replacement_char = '�'
+        if replacement_char in metadata:
+            tmpl = "{self.path} could not be properly decoded in UTF-8"
+            msg = tmpl.format(**locals())
+            warnings.warn(msg)
+
+    def get_metadata_lines(self, name: str) -> Iterator[str]:
+        return yield_lines(self.get_metadata(name))
+
+
+class PathMetadata(DefaultProvider):
+    """Metadata provider for egg directories
+
+    Usage::
+
+        # Development eggs:
+
+        egg_info = "/path/to/PackageName.egg-info"
+        base_dir = os.path.dirname(egg_info)
+        metadata = PathMetadata(base_dir, egg_info)
+        dist_name = os.path.splitext(os.path.basename(egg_info))[0]
+        dist = Distribution(basedir, project_name=dist_name, metadata=metadata)
+
+        # Unpacked egg directories:
+
+        egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
+        metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
+        dist = Distribution.from_filename(egg_path, metadata=metadata)
+    """
+
+    def __init__(self, path: str, egg_info: str) -> None:
+        self.module_path = path
+        self.egg_info = egg_info
+
+
+class EggMetadata(ZipProvider):
+    """Metadata provider for .egg files"""
+
+    def __init__(self, importer: zipimport.zipimporter) -> None:
+        """Create a metadata provider from a zipimporter"""
+
+        self.zip_pre = importer.archive + os.sep
+        self.loader = importer
+        if importer.prefix:
+            self.module_path = os.path.join(importer.archive, importer.prefix)
+        else:
+            self.module_path = importer.archive
+        self._setup_prefix()
+
+
+_distribution_finders: dict[type, _DistFinderType[Any]] = _declare_state(
+    'dict', '_distribution_finders', {}
+)
+
+
+def register_finder(
+    importer_type: type[_T], distribution_finder: _DistFinderType[_T]
+) -> None:
+    """Register `distribution_finder` to find distributions in sys.path items
+
+    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
+    handler), and `distribution_finder` is a callable that, passed a path
+    item and the importer instance, yields ``Distribution`` instances found on
+    that path item.  See ``pkg_resources.find_on_path`` for an example."""
+    _distribution_finders[importer_type] = distribution_finder
+
+
+def find_distributions(path_item: str, only: bool = False) -> Iterable[Distribution]:
+    """Yield distributions accessible via `path_item`"""
+    importer = get_importer(path_item)
+    finder = _find_adapter(_distribution_finders, importer)
+    return finder(importer, path_item, only)
+
+
+def find_eggs_in_zip(
+    importer: zipimport.zipimporter, path_item: str, only: bool = False
+) -> Iterator[Distribution]:
+    """
+    Find eggs in zip files; possibly multiple nested eggs.
+    """
+    if importer.archive.endswith('.whl'):
+        # wheels are not supported with this finder
+        # they don't have PKG-INFO metadata, and won't ever contain eggs
+        return
+    metadata = EggMetadata(importer)
+    if metadata.has_metadata('PKG-INFO'):
+        yield Distribution.from_filename(path_item, metadata=metadata)
+    if only:
+        # don't yield nested distros
+        return
+    for subitem in metadata.resource_listdir(''):
+        if _is_egg_path(subitem):
+            subpath = os.path.join(path_item, subitem)
+            dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
+            yield from dists
+        elif subitem.lower().endswith(('.dist-info', '.egg-info')):
+            subpath = os.path.join(path_item, subitem)
+            submeta = EggMetadata(zipimport.zipimporter(subpath))
+            submeta.egg_info = subpath
+            yield Distribution.from_location(path_item, subitem, submeta)
+
+
+register_finder(zipimport.zipimporter, find_eggs_in_zip)
+
+
+def find_nothing(
+    importer: object | None, path_item: str | None, only: bool | None = False
+):
+    return ()
+
+
+register_finder(object, find_nothing)
+
+
+def find_on_path(importer: object | None, path_item, only=False):
+    """Yield distributions accessible on a sys.path directory"""
+    path_item = _normalize_cached(path_item)
+
+    if _is_unpacked_egg(path_item):
+        yield Distribution.from_filename(
+            path_item,
+            metadata=PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')),
+        )
+        return
+
+    entries = (os.path.join(path_item, child) for child in safe_listdir(path_item))
+
+    # scan for .egg and .egg-info in directory
+    for entry in sorted(entries):
+        fullpath = os.path.join(path_item, entry)
+        factory = dist_factory(path_item, entry, only)
+        yield from factory(fullpath)
+
+
+def dist_factory(path_item, entry, only):
+    """Return a dist_factory for the given entry."""
+    lower = entry.lower()
+    is_egg_info = lower.endswith('.egg-info')
+    is_dist_info = lower.endswith('.dist-info') and os.path.isdir(
+        os.path.join(path_item, entry)
+    )
+    is_meta = is_egg_info or is_dist_info
+    return (
+        distributions_from_metadata
+        if is_meta
+        else find_distributions
+        if not only and _is_egg_path(entry)
+        else resolve_egg_link
+        if not only and lower.endswith('.egg-link')
+        else NoDists()
+    )
+
+
+class NoDists:
+    """
+    >>> bool(NoDists())
+    False
+
+    >>> list(NoDists()('anything'))
+    []
+    """
+
+    def __bool__(self) -> Literal[False]:
+        return False
+
+    def __call__(self, fullpath: object):
+        return iter(())
+
+
+def safe_listdir(path: StrOrBytesPath):
+    """
+    Attempt to list contents of path, but suppress some exceptions.
+    """
+    try:
+        return os.listdir(path)
+    except (PermissionError, NotADirectoryError):
+        pass
+    except OSError as e:
+        # Ignore the directory if does not exist, not a directory or
+        # permission denied
+        if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT):
+            raise
+    return ()
+
+
+def distributions_from_metadata(path: str):
+    root = os.path.dirname(path)
+    if os.path.isdir(path):
+        if len(os.listdir(path)) == 0:
+            # empty metadata dir; skip
+            return
+        metadata: _MetadataType = PathMetadata(root, path)
+    else:
+        metadata = FileMetadata(path)
+    entry = os.path.basename(path)
+    yield Distribution.from_location(
+        root,
+        entry,
+        metadata,
+        precedence=DEVELOP_DIST,
+    )
+
+
+def non_empty_lines(path):
+    """
+    Yield non-empty lines from file at path
+    """
+    for line in _read_utf8_with_fallback(path).splitlines():
+        line = line.strip()
+        if line:
+            yield line
+
+
+def resolve_egg_link(path):
+    """
+    Given a path to an .egg-link, resolve distributions
+    present in the referenced path.
+    """
+    referenced_paths = non_empty_lines(path)
+    resolved_paths = (
+        os.path.join(os.path.dirname(path), ref) for ref in referenced_paths
+    )
+    dist_groups = map(find_distributions, resolved_paths)
+    return next(dist_groups, ())
+
+
+if hasattr(pkgutil, 'ImpImporter'):
+    register_finder(pkgutil.ImpImporter, find_on_path)
+
+register_finder(importlib.machinery.FileFinder, find_on_path)
+
+_namespace_handlers: dict[type, _NSHandlerType[Any]] = _declare_state(
+    'dict', '_namespace_handlers', {}
+)
+_namespace_packages: dict[str | None, list[str]] = _declare_state(
+    'dict', '_namespace_packages', {}
+)
+
+
+def register_namespace_handler(
+    importer_type: type[_T], namespace_handler: _NSHandlerType[_T]
+) -> None:
+    """Register `namespace_handler` to declare namespace packages
+
+    `importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
+    handler), and `namespace_handler` is a callable like this::
+
+        def namespace_handler(importer, path_entry, moduleName, module):
+            # return a path_entry to use for child packages
+
+    Namespace handlers are only called if the importer object has already
+    agreed that it can handle the relevant path item, and they should only
+    return a subpath if the module __path__ does not already contain an
+    equivalent subpath.  For an example namespace handler, see
+    ``pkg_resources.file_ns_handler``.
+    """
+    _namespace_handlers[importer_type] = namespace_handler
+
+
+def _handle_ns(packageName, path_item):
+    """Ensure that named package includes a subpath of path_item (if needed)"""
+
+    importer = get_importer(path_item)
+    if importer is None:
+        return None
+
+    # use find_spec (PEP 451) and fall-back to find_module (PEP 302)
+    try:
+        spec = importer.find_spec(packageName)
+    except AttributeError:
+        # capture warnings due to #1111
+        with warnings.catch_warnings():
+            warnings.simplefilter("ignore")
+            loader = importer.find_module(packageName)
+    else:
+        loader = spec.loader if spec else None
+
+    if loader is None:
+        return None
+    module = sys.modules.get(packageName)
+    if module is None:
+        module = sys.modules[packageName] = types.ModuleType(packageName)
+        module.__path__ = []
+        _set_parent_ns(packageName)
+    elif not hasattr(module, '__path__'):
+        raise TypeError("Not a package:", packageName)
+    handler = _find_adapter(_namespace_handlers, importer)
+    subpath = handler(importer, path_item, packageName, module)
+    if subpath is not None:
+        path = module.__path__
+        path.append(subpath)
+        importlib.import_module(packageName)
+        _rebuild_mod_path(path, packageName, module)
+    return subpath
+
+
+def _rebuild_mod_path(orig_path, package_name, module: types.ModuleType) -> None:
+    """
+    Rebuild module.__path__ ensuring that all entries are ordered
+    corresponding to their sys.path order
+    """
+    sys_path = [_normalize_cached(p) for p in sys.path]
+
+    def safe_sys_path_index(entry):
+        """
+        Workaround for #520 and #513.
+        """
+        try:
+            return sys_path.index(entry)
+        except ValueError:
+            return float('inf')
+
+    def position_in_sys_path(path):
+        """
+        Return the ordinal of the path based on its position in sys.path
+        """
+        path_parts = path.split(os.sep)
+        module_parts = package_name.count('.') + 1
+        parts = path_parts[:-module_parts]
+        return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))
+
+    new_path = sorted(orig_path, key=position_in_sys_path)
+    new_path = [_normalize_cached(p) for p in new_path]
+
+    if isinstance(module.__path__, list):
+        module.__path__[:] = new_path
+    else:
+        module.__path__ = new_path
+
+
+def declare_namespace(packageName: str) -> None:
+    """Declare that package 'packageName' is a namespace package"""
+
+    msg = (
+        f"Deprecated call to `pkg_resources.declare_namespace({packageName!r})`.\n"
+        "Implementing implicit namespace packages (as specified in PEP 420) "
+        "is preferred to `pkg_resources.declare_namespace`. "
+        "See https://setuptools.pypa.io/en/latest/references/"
+        "keywords.html#keyword-namespace-packages"
+    )
+    warnings.warn(msg, DeprecationWarning, stacklevel=2)
+
+    _imp.acquire_lock()
+    try:
+        if packageName in _namespace_packages:
+            return
+
+        path: MutableSequence[str] = sys.path
+        parent, _, _ = packageName.rpartition('.')
+
+        if parent:
+            declare_namespace(parent)
+            if parent not in _namespace_packages:
+                __import__(parent)
+            try:
+                path = sys.modules[parent].__path__
+            except AttributeError as e:
+                raise TypeError("Not a package:", parent) from e
+
+        # Track what packages are namespaces, so when new path items are added,
+        # they can be updated
+        _namespace_packages.setdefault(parent or None, []).append(packageName)
+        _namespace_packages.setdefault(packageName, [])
+
+        for path_item in path:
+            # Ensure all the parent's path items are reflected in the child,
+            # if they apply
+            _handle_ns(packageName, path_item)
+
+    finally:
+        _imp.release_lock()
+
+
+def fixup_namespace_packages(path_item: str, parent: str | None = None) -> None:
+    """Ensure that previously-declared namespace packages include path_item"""
+    _imp.acquire_lock()
+    try:
+        for package in _namespace_packages.get(parent, ()):
+            subpath = _handle_ns(package, path_item)
+            if subpath:
+                fixup_namespace_packages(subpath, package)
+    finally:
+        _imp.release_lock()
+
+
+def file_ns_handler(
+    importer: object,
+    path_item: StrPath,
+    packageName: str,
+    module: types.ModuleType,
+):
+    """Compute an ns-package subpath for a filesystem or zipfile importer"""
+
+    subpath = os.path.join(path_item, packageName.split('.')[-1])
+    normalized = _normalize_cached(subpath)
+    for item in module.__path__:
+        if _normalize_cached(item) == normalized:
+            break
+    else:
+        # Only return the path if it's not already there
+        return subpath
+
+
+if hasattr(pkgutil, 'ImpImporter'):
+    register_namespace_handler(pkgutil.ImpImporter, file_ns_handler)
+
+register_namespace_handler(zipimport.zipimporter, file_ns_handler)
+register_namespace_handler(importlib.machinery.FileFinder, file_ns_handler)
+
+
+def null_ns_handler(
+    importer: object,
+    path_item: str | None,
+    packageName: str | None,
+    module: _ModuleLike | None,
+) -> None:
+    return None
+
+
+register_namespace_handler(object, null_ns_handler)
+
+
+@overload
+def normalize_path(filename: StrPath) -> str: ...
+@overload
+def normalize_path(filename: BytesPath) -> bytes: ...
+def normalize_path(filename: StrOrBytesPath) -> str | bytes:
+    """Normalize a file/dir name for comparison purposes"""
+    return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
+
+
+def _cygwin_patch(filename: StrOrBytesPath):  # pragma: nocover
+    """
+    Contrary to POSIX 2008, on Cygwin, getcwd (3) contains
+    symlink components. Using
+    os.path.abspath() works around this limitation. A fix in os.getcwd()
+    would probably better, in Cygwin even more so, except
+    that this seems to be by design...
+    """
+    return os.path.abspath(filename) if sys.platform == 'cygwin' else filename
+
+
+if TYPE_CHECKING:
+    # https://github.com/python/mypy/issues/16261
+    # https://github.com/python/typeshed/issues/6347
+    @overload
+    def _normalize_cached(filename: StrPath) -> str: ...
+    @overload
+    def _normalize_cached(filename: BytesPath) -> bytes: ...
+    def _normalize_cached(filename: StrOrBytesPath) -> str | bytes: ...
+
+else:
+
+    @functools.cache
+    def _normalize_cached(filename):
+        return normalize_path(filename)
+
+
+def _is_egg_path(path):
+    """
+    Determine if given path appears to be an egg.
+    """
+    return _is_zip_egg(path) or _is_unpacked_egg(path)
+
+
+def _is_zip_egg(path):
+    return (
+        path.lower().endswith('.egg')
+        and os.path.isfile(path)
+        and zipfile.is_zipfile(path)
+    )
+
+
+def _is_unpacked_egg(path):
+    """
+    Determine if given path appears to be an unpacked egg.
+    """
+    return path.lower().endswith('.egg') and os.path.isfile(
+        os.path.join(path, 'EGG-INFO', 'PKG-INFO')
+    )
+
+
+def _set_parent_ns(packageName) -> None:
+    parts = packageName.split('.')
+    name = parts.pop()
+    if parts:
+        parent = '.'.join(parts)
+        setattr(sys.modules[parent], name, sys.modules[packageName])
+
+
+MODULE = re.compile(r"\w+(\.\w+)*$").match
+EGG_NAME = re.compile(
+    r"""
+    (?P[^-]+) (
+        -(?P[^-]+) (
+            -py(?P[^-]+) (
+                -(?P.+)
+            )?
+        )?
+    )?
+    """,
+    re.VERBOSE | re.IGNORECASE,
+).match
+
+
+class EntryPoint:
+    """Object representing an advertised importable object"""
+
+    def __init__(
+        self,
+        name: str,
+        module_name: str,
+        attrs: Iterable[str] = (),
+        extras: Iterable[str] = (),
+        dist: Distribution | None = None,
+    ) -> None:
+        if not MODULE(module_name):
+            raise ValueError("Invalid module name", module_name)
+        self.name = name
+        self.module_name = module_name
+        self.attrs = tuple(attrs)
+        self.extras = tuple(extras)
+        self.dist = dist
+
+    def __str__(self) -> str:
+        s = f"{self.name} = {self.module_name}"
+        if self.attrs:
+            s += ':' + '.'.join(self.attrs)
+        if self.extras:
+            extras = ','.join(self.extras)
+            s += f' [{extras}]'
+        return s
+
+    def __repr__(self) -> str:
+        return f"EntryPoint.parse({str(self)!r})"
+
+    @overload
+    def load(
+        self,
+        require: Literal[True] = True,
+        env: Environment | None = None,
+        installer: _InstallerType | None = None,
+    ) -> _ResolvedEntryPoint: ...
+    @overload
+    def load(
+        self,
+        require: Literal[False],
+        *args: Any,
+        **kwargs: Any,
+    ) -> _ResolvedEntryPoint: ...
+    def load(
+        self,
+        require: bool = True,
+        *args: Environment | _InstallerType | None,
+        **kwargs: Environment | _InstallerType | None,
+    ) -> _ResolvedEntryPoint:
+        """
+        Require packages for this EntryPoint, then resolve it.
+        """
+        if not require or args or kwargs:
+            warnings.warn(
+                "Parameters to load are deprecated.  Call .resolve and "
+                ".require separately.",
+                PkgResourcesDeprecationWarning,
+                stacklevel=2,
+            )
+        if require:
+            # We could pass `env` and `installer` directly,
+            # but keeping `*args` and `**kwargs` for backwards compatibility
+            self.require(*args, **kwargs)  # type: ignore[arg-type]
+        return self.resolve()
+
+    def resolve(self) -> _ResolvedEntryPoint:
+        """
+        Resolve the entry point from its module and attrs.
+        """
+        module = __import__(self.module_name, fromlist=['__name__'], level=0)
+        try:
+            return functools.reduce(getattr, self.attrs, module)
+        except AttributeError as exc:
+            raise ImportError(str(exc)) from exc
+
+    def require(
+        self,
+        env: Environment | None = None,
+        installer: _InstallerType | None = None,
+    ) -> None:
+        if not self.dist:
+            error_cls = UnknownExtra if self.extras else AttributeError
+            raise error_cls("Can't require() without a distribution", self)
+
+        # Get the requirements for this entry point with all its extras and
+        # then resolve them. We have to pass `extras` along when resolving so
+        # that the working set knows what extras we want. Otherwise, for
+        # dist-info distributions, the working set will assume that the
+        # requirements for that extra are purely optional and skip over them.
+        reqs = self.dist.requires(self.extras)
+        items = working_set.resolve(reqs, env, installer, extras=self.extras)
+        list(map(working_set.add, items))
+
+    pattern = re.compile(
+        r'\s*'
+        r'(?P.+?)\s*'
+        r'=\s*'
+        r'(?P[\w.]+)\s*'
+        r'(:\s*(?P[\w.]+))?\s*'
+        r'(?P\[.*\])?\s*$'
+    )
+
+    @classmethod
+    def parse(cls, src: str, dist: Distribution | None = None) -> Self:
+        """Parse a single entry point from string `src`
+
+        Entry point syntax follows the form::
+
+            name = some.module:some.attr [extra1, extra2]
+
+        The entry name and module name are required, but the ``:attrs`` and
+        ``[extras]`` parts are optional
+        """
+        m = cls.pattern.match(src)
+        if not m:
+            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
+            raise ValueError(msg, src)
+        res = m.groupdict()
+        extras = cls._parse_extras(res['extras'])
+        attrs = res['attr'].split('.') if res['attr'] else ()
+        return cls(res['name'], res['module'], attrs, extras, dist)
+
+    @classmethod
+    def _parse_extras(cls, extras_spec):
+        if not extras_spec:
+            return ()
+        req = Requirement.parse('x' + extras_spec)
+        if req.specs:
+            raise ValueError
+        return req.extras
+
+    @classmethod
+    def parse_group(
+        cls,
+        group: str,
+        lines: _NestedStr,
+        dist: Distribution | None = None,
+    ) -> dict[str, Self]:
+        """Parse an entry point group"""
+        if not MODULE(group):
+            raise ValueError("Invalid group name", group)
+        this: dict[str, Self] = {}
+        for line in yield_lines(lines):
+            ep = cls.parse(line, dist)
+            if ep.name in this:
+                raise ValueError("Duplicate entry point", group, ep.name)
+            this[ep.name] = ep
+        return this
+
+    @classmethod
+    def parse_map(
+        cls,
+        data: str | Iterable[str] | dict[str, str | Iterable[str]],
+        dist: Distribution | None = None,
+    ) -> dict[str, dict[str, Self]]:
+        """Parse a map of entry point groups"""
+        _data: Iterable[tuple[str | None, str | Iterable[str]]]
+        if isinstance(data, dict):
+            _data = data.items()
+        else:
+            _data = split_sections(data)
+        maps: dict[str, dict[str, Self]] = {}
+        for group, lines in _data:
+            if group is None:
+                if not lines:
+                    continue
+                raise ValueError("Entry points must be listed in groups")
+            group = group.strip()
+            if group in maps:
+                raise ValueError("Duplicate group name", group)
+            maps[group] = cls.parse_group(group, lines, dist)
+        return maps
+
+
+def _version_from_file(lines):
+    """
+    Given an iterable of lines from a Metadata file, return
+    the value of the Version field, if present, or None otherwise.
+    """
+
+    def is_version_line(line):
+        return line.lower().startswith('version:')
+
+    version_lines = filter(is_version_line, lines)
+    line = next(iter(version_lines), '')
+    _, _, value = line.partition(':')
+    return safe_version(value.strip()) or None
+
+
+class Distribution:
+    """Wrap an actual or potential sys.path entry w/metadata"""
+
+    PKG_INFO = 'PKG-INFO'
+
+    def __init__(
+        self,
+        location: str | None = None,
+        metadata: _MetadataType = None,
+        project_name: str | None = None,
+        version: str | None = None,
+        py_version: str | None = PY_MAJOR,
+        platform: str | None = None,
+        precedence: int = EGG_DIST,
+    ) -> None:
+        self.project_name = safe_name(project_name or 'Unknown')
+        if version is not None:
+            self._version = safe_version(version)
+        self.py_version = py_version
+        self.platform = platform
+        self.location = location
+        self.precedence = precedence
+        self._provider = metadata or empty_provider
+
+    @classmethod
+    def from_location(
+        cls,
+        location: str,
+        basename: StrPath,
+        metadata: _MetadataType = None,
+        **kw: int,  # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility
+    ) -> Distribution:
+        project_name, version, py_version, platform = [None] * 4
+        basename, ext = os.path.splitext(basename)
+        if ext.lower() in _distributionImpl:
+            cls = _distributionImpl[ext.lower()]
+
+            match = EGG_NAME(basename)
+            if match:
+                project_name, version, py_version, platform = match.group(
+                    'name', 'ver', 'pyver', 'plat'
+                )
+        return cls(
+            location,
+            metadata,
+            project_name=project_name,
+            version=version,
+            py_version=py_version,
+            platform=platform,
+            **kw,
+        )._reload_version()
+
+    def _reload_version(self):
+        return self
+
+    @property
+    def hashcmp(self):
+        return (
+            self._forgiving_parsed_version,
+            self.precedence,
+            self.key,
+            self.location,
+            self.py_version or '',
+            self.platform or '',
+        )
+
+    def __hash__(self) -> int:
+        return hash(self.hashcmp)
+
+    def __lt__(self, other: Distribution) -> bool:
+        return self.hashcmp < other.hashcmp
+
+    def __le__(self, other: Distribution) -> bool:
+        return self.hashcmp <= other.hashcmp
+
+    def __gt__(self, other: Distribution) -> bool:
+        return self.hashcmp > other.hashcmp
+
+    def __ge__(self, other: Distribution) -> bool:
+        return self.hashcmp >= other.hashcmp
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, self.__class__):
+            # It's not a Distribution, so they are not equal
+            return False
+        return self.hashcmp == other.hashcmp
+
+    def __ne__(self, other: object) -> bool:
+        return not self == other
+
+    # These properties have to be lazy so that we don't have to load any
+    # metadata until/unless it's actually needed.  (i.e., some distributions
+    # may not know their name or version without loading PKG-INFO)
+
+    @property
+    def key(self):
+        try:
+            return self._key
+        except AttributeError:
+            self._key = key = self.project_name.lower()
+            return key
+
+    @property
+    def parsed_version(self):
+        if not hasattr(self, "_parsed_version"):
+            try:
+                self._parsed_version = parse_version(self.version)
+            except packaging.version.InvalidVersion as ex:
+                info = f"(package: {self.project_name})"
+                if hasattr(ex, "add_note"):
+                    ex.add_note(info)  # PEP 678
+                    raise
+                raise packaging.version.InvalidVersion(f"{str(ex)} {info}") from None
+
+        return self._parsed_version
+
+    @property
+    def _forgiving_parsed_version(self):
+        try:
+            return self.parsed_version
+        except packaging.version.InvalidVersion as ex:
+            self._parsed_version = parse_version(_forgiving_version(self.version))
+
+            notes = "\n".join(getattr(ex, "__notes__", []))  # PEP 678
+            msg = f"""!!\n\n
+            *************************************************************************
+            {str(ex)}\n{notes}
+
+            This is a long overdue deprecation.
+            For the time being, `pkg_resources` will use `{self._parsed_version}`
+            as a replacement to avoid breaking existing environments,
+            but no future compatibility is guaranteed.
+
+            If you maintain package {self.project_name} you should implement
+            the relevant changes to adequate the project to PEP 440 immediately.
+            *************************************************************************
+            \n\n!!
+            """
+            warnings.warn(msg, DeprecationWarning)
+
+            return self._parsed_version
+
+    @property
+    def version(self):
+        try:
+            return self._version
+        except AttributeError as e:
+            version = self._get_version()
+            if version is None:
+                path = self._get_metadata_path_for_display(self.PKG_INFO)
+                msg = f"Missing 'Version:' header and/or {self.PKG_INFO} file at path: {path}"
+                raise ValueError(msg, self) from e
+
+            return version
+
+    @property
+    def _dep_map(self):
+        """
+        A map of extra to its list of (direct) requirements
+        for this distribution, including the null extra.
+        """
+        try:
+            return self.__dep_map
+        except AttributeError:
+            self.__dep_map = self._filter_extras(self._build_dep_map())
+        return self.__dep_map
+
+    @staticmethod
+    def _filter_extras(
+        dm: dict[str | None, list[Requirement]],
+    ) -> dict[str | None, list[Requirement]]:
+        """
+        Given a mapping of extras to dependencies, strip off
+        environment markers and filter out any dependencies
+        not matching the markers.
+        """
+        for extra in list(filter(None, dm)):
+            new_extra: str | None = extra
+            reqs = dm.pop(extra)
+            new_extra, _, marker = extra.partition(':')
+            fails_marker = marker and (
+                invalid_marker(marker) or not evaluate_marker(marker)
+            )
+            if fails_marker:
+                reqs = []
+            new_extra = safe_extra(new_extra) or None
+
+            dm.setdefault(new_extra, []).extend(reqs)
+        return dm
+
+    def _build_dep_map(self):
+        dm = {}
+        for name in 'requires.txt', 'depends.txt':
+            for extra, reqs in split_sections(self._get_metadata(name)):
+                dm.setdefault(extra, []).extend(parse_requirements(reqs))
+        return dm
+
+    def requires(self, extras: Iterable[str] = ()) -> list[Requirement]:
+        """List of Requirements needed for this distro if `extras` are used"""
+        dm = self._dep_map
+        deps: list[Requirement] = []
+        deps.extend(dm.get(None, ()))
+        for ext in extras:
+            try:
+                deps.extend(dm[safe_extra(ext)])
+            except KeyError as e:
+                raise UnknownExtra(f"{self} has no such extra feature {ext!r}") from e
+        return deps
+
+    def _get_metadata_path_for_display(self, name):
+        """
+        Return the path to the given metadata file, if available.
+        """
+        try:
+            # We need to access _get_metadata_path() on the provider object
+            # directly rather than through this class's __getattr__()
+            # since _get_metadata_path() is marked private.
+            path = self._provider._get_metadata_path(name)
+
+        # Handle exceptions e.g. in case the distribution's metadata
+        # provider doesn't support _get_metadata_path().
+        except Exception:
+            return '[could not detect]'
+
+        return path
+
+    def _get_metadata(self, name):
+        if self.has_metadata(name):
+            yield from self.get_metadata_lines(name)
+
+    def _get_version(self):
+        lines = self._get_metadata(self.PKG_INFO)
+        return _version_from_file(lines)
+
+    def activate(self, path: list[str] | None = None, replace: bool = False) -> None:
+        """Ensure distribution is importable on `path` (default=sys.path)"""
+        if path is None:
+            path = sys.path
+        self.insert_on(path, replace=replace)
+        if path is sys.path and self.location is not None:
+            fixup_namespace_packages(self.location)
+            for pkg in self._get_metadata('namespace_packages.txt'):
+                if pkg in sys.modules:
+                    declare_namespace(pkg)
+
+    def egg_name(self):
+        """Return what this distribution's standard .egg filename should be"""
+        filename = f"{to_filename(self.project_name)}-{to_filename(self.version)}-py{self.py_version or PY_MAJOR}"
+
+        if self.platform:
+            filename += '-' + self.platform
+        return filename
+
+    def __repr__(self) -> str:
+        if self.location:
+            return f"{self} ({self.location})"
+        else:
+            return str(self)
+
+    def __str__(self) -> str:
+        try:
+            version = getattr(self, 'version', None)
+        except ValueError:
+            version = None
+        version = version or "[unknown version]"
+        return f"{self.project_name} {version}"
+
+    def __getattr__(self, attr: str):
+        """Delegate all unrecognized public attributes to .metadata provider"""
+        if attr.startswith('_'):
+            raise AttributeError(attr)
+        return getattr(self._provider, attr)
+
+    def __dir__(self):
+        return list(
+            set(super().__dir__())
+            | set(attr for attr in self._provider.__dir__() if not attr.startswith('_'))
+        )
+
+    @classmethod
+    def from_filename(
+        cls,
+        filename: StrPath,
+        metadata: _MetadataType = None,
+        **kw: int,  # We could set `precedence` explicitly, but keeping this as `**kw` for full backwards and subclassing compatibility
+    ) -> Distribution:
+        return cls.from_location(
+            _normalize_cached(filename), os.path.basename(filename), metadata, **kw
+        )
+
+    def as_requirement(self):
+        """Return a ``Requirement`` that matches this distribution exactly"""
+        if isinstance(self.parsed_version, packaging.version.Version):
+            spec = f"{self.project_name}=={self.parsed_version}"
+        else:
+            spec = f"{self.project_name}==={self.parsed_version}"
+
+        return Requirement.parse(spec)
+
+    def load_entry_point(self, group: str, name: str) -> _ResolvedEntryPoint:
+        """Return the `name` entry point of `group` or raise ImportError"""
+        ep = self.get_entry_info(group, name)
+        if ep is None:
+            raise ImportError(f"Entry point {(group, name)!r} not found")
+        return ep.load()
+
+    @overload
+    def get_entry_map(self, group: None = None) -> dict[str, dict[str, EntryPoint]]: ...
+    @overload
+    def get_entry_map(self, group: str) -> dict[str, EntryPoint]: ...
+    def get_entry_map(self, group: str | None = None):
+        """Return the entry point map for `group`, or the full entry map"""
+        if not hasattr(self, "_ep_map"):
+            self._ep_map = EntryPoint.parse_map(
+                self._get_metadata('entry_points.txt'), self
+            )
+        if group is not None:
+            return self._ep_map.get(group, {})
+        return self._ep_map
+
+    def get_entry_info(self, group: str, name: str) -> EntryPoint | None:
+        """Return the EntryPoint object for `group`+`name`, or ``None``"""
+        return self.get_entry_map(group).get(name)
+
+    # FIXME: 'Distribution.insert_on' is too complex (13)
+    def insert_on(  # noqa: C901
+        self,
+        path: list[str],
+        loc=None,
+        replace: bool = False,
+    ) -> None:
+        """Ensure self.location is on path
+
+        If replace=False (default):
+            - If location is already in path anywhere, do nothing.
+            - Else:
+              - If it's an egg and its parent directory is on path,
+                insert just ahead of the parent.
+              - Else: add to the end of path.
+        If replace=True:
+            - If location is already on path anywhere (not eggs)
+              or higher priority than its parent (eggs)
+              do nothing.
+            - Else:
+              - If it's an egg and its parent directory is on path,
+                insert just ahead of the parent,
+                removing any lower-priority entries.
+              - Else: add it to the front of path.
+        """
+
+        loc = loc or self.location
+        if not loc:
+            return
+
+        nloc = _normalize_cached(loc)
+        bdir = os.path.dirname(nloc)
+        npath = [(p and _normalize_cached(p) or p) for p in path]
+
+        for p, item in enumerate(npath):
+            if item == nloc:
+                if replace:
+                    break
+                else:
+                    # don't modify path (even removing duplicates) if
+                    # found and not replace
+                    return
+            elif item == bdir and self.precedence == EGG_DIST:
+                # if it's an .egg, give it precedence over its directory
+                # UNLESS it's already been added to sys.path and replace=False
+                if (not replace) and nloc in npath[p:]:
+                    return
+                if path is sys.path:
+                    self.check_version_conflict()
+                path.insert(p, loc)
+                npath.insert(p, nloc)
+                break
+        else:
+            if path is sys.path:
+                self.check_version_conflict()
+            if replace:
+                path.insert(0, loc)
+            else:
+                path.append(loc)
+            return
+
+        # p is the spot where we found or inserted loc; now remove duplicates
+        while True:
+            try:
+                np = npath.index(nloc, p + 1)
+            except ValueError:
+                break
+            else:
+                del npath[np], path[np]
+                # ha!
+                p = np
+
+        return
+
+    def check_version_conflict(self):
+        if self.key == 'setuptools':
+            # ignore the inevitable setuptools self-conflicts  :(
+            return
+
+        nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
+        loc = normalize_path(self.location)
+        for modname in self._get_metadata('top_level.txt'):
+            if (
+                modname not in sys.modules
+                or modname in nsp
+                or modname in _namespace_packages
+            ):
+                continue
+            if modname in ('pkg_resources', 'setuptools', 'site'):
+                continue
+            fn = getattr(sys.modules[modname], '__file__', None)
+            if fn and (
+                normalize_path(fn).startswith(loc) or fn.startswith(self.location)
+            ):
+                continue
+            issue_warning(
+                f"Module {modname} was already imported from {fn}, "
+                f"but {self.location} is being added to sys.path",
+            )
+
+    def has_version(self) -> bool:
+        try:
+            self.version
+        except ValueError:
+            issue_warning("Unbuilt egg for " + repr(self))
+            return False
+        except SystemError:
+            # TODO: remove this except clause when python/cpython#103632 is fixed.
+            return False
+        return True
+
+    def clone(self, **kw: str | int | IResourceProvider | None) -> Self:
+        """Copy this distribution, substituting in any changed keyword args"""
+        names = 'project_name version py_version platform location precedence'
+        for attr in names.split():
+            kw.setdefault(attr, getattr(self, attr, None))
+        kw.setdefault('metadata', self._provider)
+        # Unsafely unpacking. But keeping **kw for backwards and subclassing compatibility
+        return self.__class__(**kw)  # type:ignore[arg-type]
+
+    @property
+    def extras(self):
+        return [dep for dep in self._dep_map if dep]
+
+
+class EggInfoDistribution(Distribution):
+    def _reload_version(self):
+        """
+        Packages installed by distutils (e.g. numpy or scipy),
+        which uses an old safe_version, and so
+        their version numbers can get mangled when
+        converted to filenames (e.g., 1.11.0.dev0+2329eae to
+        1.11.0.dev0_2329eae). These distributions will not be
+        parsed properly
+        downstream by Distribution and safe_version, so
+        take an extra step and try to get the version number from
+        the metadata file itself instead of the filename.
+        """
+        md_version = self._get_version()
+        if md_version:
+            self._version = md_version
+        return self
+
+
+class DistInfoDistribution(Distribution):
+    """
+    Wrap an actual or potential sys.path entry
+    w/metadata, .dist-info style.
+    """
+
+    PKG_INFO = 'METADATA'
+    EQEQ = re.compile(r"([\(,])\s*(\d.*?)\s*([,\)])")
+
+    @property
+    def _parsed_pkg_info(self):
+        """Parse and cache metadata"""
+        try:
+            return self._pkg_info
+        except AttributeError:
+            metadata = self.get_metadata(self.PKG_INFO)
+            self._pkg_info = email.parser.Parser().parsestr(metadata)
+            return self._pkg_info
+
+    @property
+    def _dep_map(self):
+        try:
+            return self.__dep_map
+        except AttributeError:
+            self.__dep_map = self._compute_dependencies()
+            return self.__dep_map
+
+    def _compute_dependencies(self) -> dict[str | None, list[Requirement]]:
+        """Recompute this distribution's dependencies."""
+        self.__dep_map: dict[str | None, list[Requirement]] = {None: []}
+
+        reqs: list[Requirement] = []
+        # Including any condition expressions
+        for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
+            reqs.extend(parse_requirements(req))
+
+        def reqs_for_extra(extra):
+            for req in reqs:
+                if not req.marker or req.marker.evaluate({'extra': extra}):
+                    yield req
+
+        common = types.MappingProxyType(dict.fromkeys(reqs_for_extra(None)))
+        self.__dep_map[None].extend(common)
+
+        for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:
+            s_extra = safe_extra(extra.strip())
+            self.__dep_map[s_extra] = [
+                r for r in reqs_for_extra(extra) if r not in common
+            ]
+
+        return self.__dep_map
+
+
+_distributionImpl = {
+    '.egg': Distribution,
+    '.egg-info': EggInfoDistribution,
+    '.dist-info': DistInfoDistribution,
+}
+
+
+def issue_warning(*args, **kw):
+    level = 1
+    g = globals()
+    try:
+        # find the first stack frame that is *not* code in
+        # the pkg_resources module, to use for the warning
+        while sys._getframe(level).f_globals is g:
+            level += 1
+    except ValueError:
+        pass
+    warnings.warn(stacklevel=level + 1, *args, **kw)
+
+
+def parse_requirements(strs: _NestedStr) -> map[Requirement]:
+    """
+    Yield ``Requirement`` objects for each specification in `strs`.
+
+    `strs` must be a string, or a (possibly-nested) iterable thereof.
+    """
+    return map(Requirement, join_continuation(map(drop_comment, yield_lines(strs))))
+
+
+class RequirementParseError(packaging.requirements.InvalidRequirement):
+    "Compatibility wrapper for InvalidRequirement"
+
+
+class Requirement(packaging.requirements.Requirement):
+    # prefer variable length tuple to set (as found in
+    # packaging.requirements.Requirement)
+    extras: tuple[str, ...]  # type: ignore[assignment]
+
+    def __init__(self, requirement_string: str) -> None:
+        """DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
+        super().__init__(requirement_string)
+        self.unsafe_name = self.name
+        project_name = safe_name(self.name)
+        self.project_name, self.key = project_name, project_name.lower()
+        self.specs = [(spec.operator, spec.version) for spec in self.specifier]
+        self.extras = tuple(map(safe_extra, self.extras))
+        self.hashCmp = (
+            self.key,
+            self.url,
+            self.specifier,
+            frozenset(self.extras),
+            str(self.marker) if self.marker else None,
+        )
+        self.__hash = hash(self.hashCmp)
+
+    def __eq__(self, other: object) -> bool:
+        return isinstance(other, Requirement) and self.hashCmp == other.hashCmp
+
+    def __ne__(self, other: object) -> bool:
+        return not self == other
+
+    def __contains__(
+        self, item: Distribution | packaging.specifiers.UnparsedVersion
+    ) -> bool:
+        if isinstance(item, Distribution):
+            if item.key != self.key:
+                return False
+
+            version = item.version
+        else:
+            version = item
+
+        # Allow prereleases always in order to match the previous behavior of
+        # this method. In the future this should be smarter and follow PEP 440
+        # more accurately.
+        return self.specifier.contains(
+            version,
+            prereleases=True,
+        )
+
+    def __hash__(self) -> int:
+        return self.__hash
+
+    def __repr__(self) -> str:
+        return f"Requirement.parse({str(self)!r})"
+
+    @staticmethod
+    def parse(s: str | Iterable[str]) -> Requirement:
+        (req,) = parse_requirements(s)
+        return req
+
+
+def _always_object(classes):
+    """
+    Ensure object appears in the mro even
+    for old-style classes.
+    """
+    if object not in classes:
+        return classes + (object,)
+    return classes
+
+
+def _find_adapter(registry: Mapping[type, _AdapterT], ob: object) -> _AdapterT:
+    """Return an adapter factory for `ob` from `registry`"""
+    types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
+    for t in types:
+        if t in registry:
+            return registry[t]
+    # _find_adapter would previously return None, and immediately be called.
+    # So we're raising a TypeError to keep backward compatibility if anyone depended on that behaviour.
+    raise TypeError(f"Could not find adapter for {registry} and {ob}")
+
+
+def ensure_directory(path: StrOrBytesPath) -> None:
+    """Ensure that the parent directory of `path` exists"""
+    dirname = os.path.dirname(path)
+    os.makedirs(dirname, exist_ok=True)
+
+
+def _bypass_ensure_directory(path) -> None:
+    """Sandbox-bypassing version of ensure_directory()"""
+    if not WRITE_SUPPORT:
+        raise OSError('"os.mkdir" not supported on this platform.')
+    dirname, filename = split(path)
+    if dirname and filename and not isdir(dirname):
+        _bypass_ensure_directory(dirname)
+        try:
+            mkdir(dirname, 0o755)
+        except FileExistsError:
+            pass
+
+
+def split_sections(s: _NestedStr) -> Iterator[tuple[str | None, list[str]]]:
+    """Split a string or iterable thereof into (section, content) pairs
+
+    Each ``section`` is a stripped version of the section header ("[section]")
+    and each ``content`` is a list of stripped lines excluding blank lines and
+    comment-only lines.  If there are any such lines before the first section
+    header, they're returned in a first ``section`` of ``None``.
+    """
+    section = None
+    content: list[str] = []
+    for line in yield_lines(s):
+        if line.startswith("["):
+            if line.endswith("]"):
+                if section or content:
+                    yield section, content
+                section = line[1:-1].strip()
+                content = []
+            else:
+                raise ValueError("Invalid section heading", line)
+        else:
+            content.append(line)
+
+    # wrap up last segment
+    yield section, content
+
+
+def _mkstemp(*args, **kw):
+    old_open = os.open
+    try:
+        # temporarily bypass sandboxing
+        os.open = os_open
+        return tempfile.mkstemp(*args, **kw)
+    finally:
+        # and then put it back
+        os.open = old_open
+
+
+# Silence the PEP440Warning by default, so that end users don't get hit by it
+# randomly just because they use pkg_resources. We want to append the rule
+# because we want earlier uses of filterwarnings to take precedence over this
+# one.
+warnings.filterwarnings("ignore", category=PEP440Warning, append=True)
+
+
+class PkgResourcesDeprecationWarning(Warning):
+    """
+    Base class for warning about deprecations in ``pkg_resources``
+
+    This class is not derived from ``DeprecationWarning``, and as such is
+    visible by default.
+    """
+
+
+# Ported from ``setuptools`` to avoid introducing an import inter-dependency:
+_LOCALE_ENCODING = "locale" if sys.version_info >= (3, 10) else None
+
+
+# This must go before calls to `_call_aside`. See https://github.com/pypa/setuptools/pull/4422
+def _read_utf8_with_fallback(file: str, fallback_encoding=_LOCALE_ENCODING) -> str:
+    """See setuptools.unicode_utils._read_utf8_with_fallback"""
+    try:
+        with open(file, "r", encoding="utf-8") as f:
+            return f.read()
+    except UnicodeDecodeError:  # pragma: no cover
+        msg = f"""\
+        ********************************************************************************
+        `encoding="utf-8"` fails with {file!r}, trying `encoding={fallback_encoding!r}`.
+
+        This fallback behaviour is considered **deprecated** and future versions of
+        `setuptools/pkg_resources` may not implement it.
+
+        Please encode {file!r} with "utf-8" to ensure future builds will succeed.
+
+        If this file was produced by `setuptools` itself, cleaning up the cached files
+        and re-building/re-installing the package with a newer version of `setuptools`
+        (e.g. by updating `build-system.requires` in its `pyproject.toml`)
+        might solve the problem.
+        ********************************************************************************
+        """
+        # TODO: Add a deadline?
+        #       See comment in setuptools.unicode_utils._Utf8EncodingNeeded
+        warnings.warn(msg, PkgResourcesDeprecationWarning, stacklevel=2)
+        with open(file, "r", encoding=fallback_encoding) as f:
+            return f.read()
+
+
+# from jaraco.functools 1.3
+def _call_aside(f, *args, **kwargs):
+    f(*args, **kwargs)
+    return f
+
+
+@_call_aside
+def _initialize(g=globals()) -> None:
+    "Set up global resource manager (deliberately not state-saved)"
+    manager = ResourceManager()
+    g['_manager'] = manager
+    g.update(
+        (name, getattr(manager, name))
+        for name in dir(manager)
+        if not name.startswith('_')
+    )
+
+
+@_call_aside
+def _initialize_master_working_set() -> None:
+    """
+    Prepare the master working set and make the ``require()``
+    API available.
+
+    This function has explicit effects on the global state
+    of pkg_resources. It is intended to be invoked once at
+    the initialization of this module.
+
+    Invocation by other packages is unsupported and done
+    at their own risk.
+    """
+    working_set = _declare_state('object', 'working_set', WorkingSet._build_master())
+
+    require = working_set.require
+    iter_entry_points = working_set.iter_entry_points
+    add_activation_listener = working_set.subscribe
+    run_script = working_set.run_script
+    # backward compatibility
+    run_main = run_script
+    # Activate all distributions already on sys.path with replace=False and
+    # ensure that all distributions added to the working set in the future
+    # (e.g. by calling ``require()``) will get activated as well,
+    # with higher priority (replace=True).
+    tuple(dist.activate(replace=False) for dist in working_set)
+    add_activation_listener(
+        lambda dist: dist.activate(replace=True),
+        existing=False,
+    )
+    working_set.entries = []
+    # match order
+    list(map(working_set.add_entry, sys.path))
+    globals().update(locals())
+
+
+if TYPE_CHECKING:
+    # All of these are set by the @_call_aside methods above
+    __resource_manager = ResourceManager()  # Won't exist at runtime
+    resource_exists = __resource_manager.resource_exists
+    resource_isdir = __resource_manager.resource_isdir
+    resource_filename = __resource_manager.resource_filename
+    resource_stream = __resource_manager.resource_stream
+    resource_string = __resource_manager.resource_string
+    resource_listdir = __resource_manager.resource_listdir
+    set_extraction_path = __resource_manager.set_extraction_path
+    cleanup_resources = __resource_manager.cleanup_resources
+
+    working_set = WorkingSet()
+    require = working_set.require
+    iter_entry_points = working_set.iter_entry_points
+    add_activation_listener = working_set.subscribe
+    run_script = working_set.run_script
+    run_main = run_script
diff --git a/data/miniconda3/lib/python3.13/site-packages/pkg_resources/api_tests.txt b/data/miniconda3/lib/python3.13/site-packages/pkg_resources/api_tests.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d72b85aa375b3a19cb3d36ccb1dd8d205c425938
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pkg_resources/api_tests.txt
@@ -0,0 +1,424 @@
+Pluggable Distributions of Python Software
+==========================================
+
+Distributions
+-------------
+
+A "Distribution" is a collection of files that represent a "Release" of a
+"Project" as of a particular point in time, denoted by a
+"Version"::
+
+    >>> import sys, pkg_resources
+    >>> from pkg_resources import Distribution
+    >>> Distribution(project_name="Foo", version="1.2")
+    Foo 1.2
+
+Distributions have a location, which can be a filename, URL, or really anything
+else you care to use::
+
+    >>> dist = Distribution(
+    ...     location="http://example.com/something",
+    ...     project_name="Bar", version="0.9"
+    ... )
+
+    >>> dist
+    Bar 0.9 (http://example.com/something)
+
+
+Distributions have various introspectable attributes::
+
+    >>> dist.location
+    'http://example.com/something'
+
+    >>> dist.project_name
+    'Bar'
+
+    >>> dist.version
+    '0.9'
+
+    >>> dist.py_version == '{}.{}'.format(*sys.version_info)
+    True
+
+    >>> print(dist.platform)
+    None
+
+Including various computed attributes::
+
+    >>> from pkg_resources import parse_version
+    >>> dist.parsed_version == parse_version(dist.version)
+    True
+
+    >>> dist.key    # case-insensitive form of the project name
+    'bar'
+
+Distributions are compared (and hashed) by version first::
+
+    >>> Distribution(version='1.0') == Distribution(version='1.0')
+    True
+    >>> Distribution(version='1.0') == Distribution(version='1.1')
+    False
+    >>> Distribution(version='1.0') <  Distribution(version='1.1')
+    True
+
+but also by project name (case-insensitive), platform, Python version,
+location, etc.::
+
+    >>> Distribution(project_name="Foo",version="1.0") == \
+    ... Distribution(project_name="Foo",version="1.0")
+    True
+
+    >>> Distribution(project_name="Foo",version="1.0") == \
+    ... Distribution(project_name="foo",version="1.0")
+    True
+
+    >>> Distribution(project_name="Foo",version="1.0") == \
+    ... Distribution(project_name="Foo",version="1.1")
+    False
+
+    >>> Distribution(project_name="Foo",py_version="2.3",version="1.0") == \
+    ... Distribution(project_name="Foo",py_version="2.4",version="1.0")
+    False
+
+    >>> Distribution(location="spam",version="1.0") == \
+    ... Distribution(location="spam",version="1.0")
+    True
+
+    >>> Distribution(location="spam",version="1.0") == \
+    ... Distribution(location="baz",version="1.0")
+    False
+
+
+
+Hash and compare distribution by prio/plat
+
+Get version from metadata
+provider capabilities
+egg_name()
+as_requirement()
+from_location, from_filename (w/path normalization)
+
+Releases may have zero or more "Requirements", which indicate
+what releases of another project the release requires in order to
+function.  A Requirement names the other project, expresses some criteria
+as to what releases of that project are acceptable, and lists any "Extras"
+that the requiring release may need from that project.  (An Extra is an
+optional feature of a Release, that can only be used if its additional
+Requirements are satisfied.)
+
+
+
+The Working Set
+---------------
+
+A collection of active distributions is called a Working Set.  Note that a
+Working Set can contain any importable distribution, not just pluggable ones.
+For example, the Python standard library is an importable distribution that
+will usually be part of the Working Set, even though it is not pluggable.
+Similarly, when you are doing development work on a project, the files you are
+editing are also a Distribution.  (And, with a little attention to the
+directory names used,  and including some additional metadata, such a
+"development distribution" can be made pluggable as well.)
+
+    >>> from pkg_resources import WorkingSet
+
+A working set's entries are the sys.path entries that correspond to the active
+distributions.  By default, the working set's entries are the items on
+``sys.path``::
+
+    >>> ws = WorkingSet()
+    >>> ws.entries == sys.path
+    True
+
+But you can also create an empty working set explicitly, and add distributions
+to it::
+
+    >>> ws = WorkingSet([])
+    >>> ws.add(dist)
+    >>> ws.entries
+    ['http://example.com/something']
+    >>> dist in ws
+    True
+    >>> Distribution('foo',version="") in ws
+    False
+
+And you can iterate over its distributions::
+
+    >>> list(ws)
+    [Bar 0.9 (http://example.com/something)]
+
+Adding the same distribution more than once is a no-op::
+
+    >>> ws.add(dist)
+    >>> list(ws)
+    [Bar 0.9 (http://example.com/something)]
+
+For that matter, adding multiple distributions for the same project also does
+nothing, because a working set can only hold one active distribution per
+project -- the first one added to it::
+
+    >>> ws.add(
+    ...     Distribution(
+    ...         'http://example.com/something', project_name="Bar",
+    ...         version="7.2"
+    ...     )
+    ... )
+    >>> list(ws)
+    [Bar 0.9 (http://example.com/something)]
+
+You can append a path entry to a working set using ``add_entry()``::
+
+    >>> ws.entries
+    ['http://example.com/something']
+    >>> ws.add_entry(pkg_resources.__file__)
+    >>> ws.entries
+    ['http://example.com/something', '...pkg_resources...']
+
+Multiple additions result in multiple entries, even if the entry is already in
+the working set (because ``sys.path`` can contain the same entry more than
+once)::
+
+    >>> ws.add_entry(pkg_resources.__file__)
+    >>> ws.entries
+    ['...example.com...', '...pkg_resources...', '...pkg_resources...']
+
+And you can specify the path entry a distribution was found under, using the
+optional second parameter to ``add()``::
+
+    >>> ws = WorkingSet([])
+    >>> ws.add(dist,"foo")
+    >>> ws.entries
+    ['foo']
+
+But even if a distribution is found under multiple path entries, it still only
+shows up once when iterating the working set:
+
+    >>> ws.add_entry(ws.entries[0])
+    >>> list(ws)
+    [Bar 0.9 (http://example.com/something)]
+
+You can ask a WorkingSet to ``find()`` a distribution matching a requirement::
+
+    >>> from pkg_resources import Requirement
+    >>> print(ws.find(Requirement.parse("Foo==1.0")))   # no match, return None
+    None
+
+    >>> ws.find(Requirement.parse("Bar==0.9"))  # match, return distribution
+    Bar 0.9 (http://example.com/something)
+
+Note that asking for a conflicting version of a distribution already in a
+working set triggers a ``pkg_resources.VersionConflict`` error:
+
+    >>> try:
+    ...     ws.find(Requirement.parse("Bar==1.0"))
+    ... except pkg_resources.VersionConflict as exc:
+    ...     print(str(exc))
+    ... else:
+    ...     raise AssertionError("VersionConflict was not raised")
+    (Bar 0.9 (http://example.com/something), Requirement.parse('Bar==1.0'))
+
+You can subscribe a callback function to receive notifications whenever a new
+distribution is added to a working set.  The callback is immediately invoked
+once for each existing distribution in the working set, and then is called
+again for new distributions added thereafter::
+
+    >>> def added(dist): print("Added %s" % dist)
+    >>> ws.subscribe(added)
+    Added Bar 0.9
+    >>> foo12 = Distribution(project_name="Foo", version="1.2", location="f12")
+    >>> ws.add(foo12)
+    Added Foo 1.2
+
+Note, however, that only the first distribution added for a given project name
+will trigger a callback, even during the initial ``subscribe()`` callback::
+
+    >>> foo14 = Distribution(project_name="Foo", version="1.4", location="f14")
+    >>> ws.add(foo14)   # no callback, because Foo 1.2 is already active
+
+    >>> ws = WorkingSet([])
+    >>> ws.add(foo12)
+    >>> ws.add(foo14)
+    >>> ws.subscribe(added)
+    Added Foo 1.2
+
+And adding a callback more than once has no effect, either::
+
+    >>> ws.subscribe(added)     # no callbacks
+
+    # and no double-callbacks on subsequent additions, either
+    >>> just_a_test = Distribution(project_name="JustATest", version="0.99")
+    >>> ws.add(just_a_test)
+    Added JustATest 0.99
+
+
+Finding Plugins
+---------------
+
+``WorkingSet`` objects can be used to figure out what plugins in an
+``Environment`` can be loaded without any resolution errors::
+
+    >>> from pkg_resources import Environment
+
+    >>> plugins = Environment([])   # normally, a list of plugin directories
+    >>> plugins.add(foo12)
+    >>> plugins.add(foo14)
+    >>> plugins.add(just_a_test)
+
+In the simplest case, we just get the newest version of each distribution in
+the plugin environment::
+
+    >>> ws = WorkingSet([])
+    >>> ws.find_plugins(plugins)
+    ([JustATest 0.99, Foo 1.4 (f14)], {})
+
+But if there's a problem with a version conflict or missing requirements, the
+method falls back to older versions, and the error info dict will contain an
+exception instance for each unloadable plugin::
+
+    >>> ws.add(foo12)   # this will conflict with Foo 1.4
+    >>> ws.find_plugins(plugins)
+    ([JustATest 0.99, Foo 1.2 (f12)], {Foo 1.4 (f14): VersionConflict(...)})
+
+But if you disallow fallbacks, the failed plugin will be skipped instead of
+trying older versions::
+
+    >>> ws.find_plugins(plugins, fallback=False)
+    ([JustATest 0.99], {Foo 1.4 (f14): VersionConflict(...)})
+
+
+
+Platform Compatibility Rules
+----------------------------
+
+On the Mac, there are potential compatibility issues for modules compiled
+on newer versions of macOS than what the user is running. Additionally,
+macOS will soon have two platforms to contend with: Intel and PowerPC.
+
+Basic equality works as on other platforms::
+
+    >>> from pkg_resources import compatible_platforms as cp
+    >>> reqd = 'macosx-10.4-ppc'
+    >>> cp(reqd, reqd)
+    True
+    >>> cp("win32", reqd)
+    False
+
+Distributions made on other machine types are not compatible::
+
+    >>> cp("macosx-10.4-i386", reqd)
+    False
+
+Distributions made on earlier versions of the OS are compatible, as
+long as they are from the same top-level version. The patchlevel version
+number does not matter::
+
+    >>> cp("macosx-10.4-ppc", reqd)
+    True
+    >>> cp("macosx-10.3-ppc", reqd)
+    True
+    >>> cp("macosx-10.5-ppc", reqd)
+    False
+    >>> cp("macosx-9.5-ppc", reqd)
+    False
+
+Backwards compatibility for packages made via earlier versions of
+setuptools is provided as well::
+
+    >>> cp("darwin-8.2.0-Power_Macintosh", reqd)
+    True
+    >>> cp("darwin-7.2.0-Power_Macintosh", reqd)
+    True
+    >>> cp("darwin-8.2.0-Power_Macintosh", "macosx-10.3-ppc")
+    False
+
+
+Environment Markers
+-------------------
+
+    >>> from pkg_resources import invalid_marker as im, evaluate_marker as em
+    >>> import os
+
+    >>> print(im("sys_platform"))
+    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
+        sys_platform
+                    ^
+
+    >>> print(im("sys_platform=="))
+    Expected a marker variable or quoted string
+        sys_platform==
+                      ^
+
+    >>> print(im("sys_platform=='win32'"))
+    False
+
+    >>> print(im("sys=='x'"))
+    Expected a marker variable or quoted string
+        sys=='x'
+        ^
+
+    >>> print(im("(extra)"))
+    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
+        (extra)
+              ^
+
+    >>> print(im("(extra"))
+    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
+        (extra
+              ^
+
+    >>> print(im("os.open('foo')=='y'"))
+    Expected a marker variable or quoted string
+        os.open('foo')=='y'
+        ^
+
+    >>> print(im("'x'=='y' and os.open('foo')=='y'"))   # no short-circuit!
+    Expected a marker variable or quoted string
+        'x'=='y' and os.open('foo')=='y'
+                     ^
+
+    >>> print(im("'x'=='x' or os.open('foo')=='y'"))   # no short-circuit!
+    Expected a marker variable or quoted string
+        'x'=='x' or os.open('foo')=='y'
+                    ^
+
+    >>> print(im("r'x'=='x'"))
+    Expected a marker variable or quoted string
+        r'x'=='x'
+        ^
+
+    >>> print(im("'''x'''=='x'"))
+    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
+        '''x'''=='x'
+          ^
+
+    >>> print(im('"""x"""=="x"'))
+    Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in
+        """x"""=="x"
+          ^
+
+    >>> print(im(r"x\n=='x'"))
+    Expected a marker variable or quoted string
+        x\n=='x'
+        ^
+
+    >>> print(im("os.open=='y'"))
+    Expected a marker variable or quoted string
+        os.open=='y'
+        ^
+
+    >>> em("sys_platform=='win32'") == (sys.platform=='win32')
+    True
+
+    >>> em("python_version >= '2.7'")
+    True
+
+    >>> em("python_version > '2.6'")
+    True
+
+    >>> im("implementation_name=='cpython'")
+    False
+
+    >>> im("platform_python_implementation=='CPython'")
+    False
+
+    >>> im("implementation_version=='3.5.1'")
+    False
diff --git a/data/miniconda3/lib/python3.13/site-packages/pkg_resources/py.typed b/data/miniconda3/lib/python3.13/site-packages/pkg_resources/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
\ No newline at end of file
diff --git a/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..f39386dd1c34e037d0a4db5ca252b71cb16468a5
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/METADATA
@@ -0,0 +1,350 @@
+Metadata-Version: 2.4
+Name: platformdirs
+Version: 4.5.0
+Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`.
+Project-URL: Changelog, https://github.com/tox-dev/platformdirs/releases
+Project-URL: Documentation, https://platformdirs.readthedocs.io
+Project-URL: Homepage, https://github.com/tox-dev/platformdirs
+Project-URL: Source, https://github.com/tox-dev/platformdirs
+Project-URL: Tracker, https://github.com/tox-dev/platformdirs/issues
+Maintainer-email: Bernát Gábor , Julian Berman , Ofek Lev , Ronny Pfannschmidt 
+License-Expression: MIT
+License-File: LICENSE
+Keywords: appdirs,application,cache,directory,log,user
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.10
+Provides-Extra: docs
+Requires-Dist: furo>=2025.9.25; extra == 'docs'
+Requires-Dist: proselint>=0.14; extra == 'docs'
+Requires-Dist: sphinx-autodoc-typehints>=3.2; extra == 'docs'
+Requires-Dist: sphinx>=8.2.3; extra == 'docs'
+Provides-Extra: test
+Requires-Dist: appdirs==1.4.4; extra == 'test'
+Requires-Dist: covdefaults>=2.3; extra == 'test'
+Requires-Dist: pytest-cov>=7; extra == 'test'
+Requires-Dist: pytest-mock>=3.15.1; extra == 'test'
+Requires-Dist: pytest>=8.4.2; extra == 'test'
+Provides-Extra: type
+Requires-Dist: mypy>=1.18.2; extra == 'type'
+Description-Content-Type: text/x-rst
+
+The problem
+===========
+
+.. image:: https://badge.fury.io/py/platformdirs.svg
+   :target: https://badge.fury.io/py/platformdirs
+.. image:: https://img.shields.io/pypi/pyversions/platformdirs.svg
+   :target: https://pypi.python.org/pypi/platformdirs/
+.. image:: https://github.com/tox-dev/platformdirs/actions/workflows/check.yaml/badge.svg
+   :target: https://github.com/platformdirs/platformdirs/actions
+.. image:: https://static.pepy.tech/badge/platformdirs/month
+   :target: https://pepy.tech/project/platformdirs
+
+When writing desktop application, finding the right location to store user data
+and configuration varies per platform. Even for single-platform apps, there
+may by plenty of nuances in figuring out the right location.
+
+For example, if running on macOS, you should use::
+
+    ~/Library/Application Support/
+
+If on Windows (at least English Win) that should be::
+
+    C:\Users\\Application Data\Local Settings\\
+
+or possibly::
+
+    C:\Users\\Application Data\\
+
+for `roaming profiles `_ but that is another story.
+
+On Linux (and other Unices), according to the `XDG Basedir Spec`_, it should be::
+
+    ~/.local/share/
+
+.. _XDG Basedir Spec: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+
+``platformdirs`` to the rescue
+==============================
+
+This kind of thing is what the ``platformdirs`` package is for.
+``platformdirs`` will help you choose an appropriate:
+
+- user data dir (``user_data_dir``)
+- user config dir (``user_config_dir``)
+- user cache dir (``user_cache_dir``)
+- site data dir (``site_data_dir``)
+- site config dir (``site_config_dir``)
+- user log dir (``user_log_dir``)
+- user documents dir (``user_documents_dir``)
+- user downloads dir (``user_downloads_dir``)
+- user pictures dir (``user_pictures_dir``)
+- user videos dir (``user_videos_dir``)
+- user music dir (``user_music_dir``)
+- user desktop dir (``user_desktop_dir``)
+- user runtime dir (``user_runtime_dir``)
+
+And also:
+
+- Is slightly opinionated on the directory names used. Look for "OPINION" in
+  documentation and code for when an opinion is being applied.
+
+Example output
+==============
+
+On macOS:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> user_config_dir(appname, appauthor)
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/Library/Application Support/SuperApp'
+    >>> site_config_dir(appname, appauthor)
+    '/Library/Application Support/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/Users/trentm/Library/Logs/SuperApp'
+    >>> user_documents_dir()
+    '/Users/trentm/Documents'
+    >>> user_downloads_dir()
+    '/Users/trentm/Downloads'
+    >>> user_pictures_dir()
+    '/Users/trentm/Pictures'
+    >>> user_videos_dir()
+    '/Users/trentm/Movies'
+    >>> user_music_dir()
+    '/Users/trentm/Music'
+    >>> user_desktop_dir()
+    '/Users/trentm/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
+
+On Windows:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
+    >>> user_data_dir(appname, appauthor, roaming=True)
+    'C:\\Users\\trentm\\AppData\\Roaming\\Acme\\SuperApp'
+    >>> user_config_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache'
+    >>> site_data_dir(appname, appauthor)
+    'C:\\ProgramData\\Acme\\SuperApp'
+    >>> site_config_dir(appname, appauthor)
+    'C:\\ProgramData\\Acme\\SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Logs'
+    >>> user_documents_dir()
+    'C:\\Users\\trentm\\Documents'
+    >>> user_downloads_dir()
+    'C:\\Users\\trentm\\Downloads'
+    >>> user_pictures_dir()
+    'C:\\Users\\trentm\\Pictures'
+    >>> user_videos_dir()
+    'C:\\Users\\trentm\\Videos'
+    >>> user_music_dir()
+    'C:\\Users\\trentm\\Music'
+    >>> user_desktop_dir()
+    'C:\\Users\\trentm\\Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    'C:\\Users\\trentm\\AppData\\Local\\Temp\\Acme\\SuperApp'
+
+On Linux:
+
+.. code-block:: pycon
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/home/trentm/.local/share/SuperApp'
+    >>> user_config_dir(appname)
+    '/home/trentm/.config/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/home/trentm/.cache/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/usr/local/share/SuperApp'
+    >>> site_data_dir(appname, appauthor, multipath=True)
+    '/usr/local/share/SuperApp:/usr/share/SuperApp'
+    >>> site_config_dir(appname)
+    '/etc/xdg/SuperApp'
+    >>> os.environ["XDG_CONFIG_DIRS"] = "/etc:/usr/local/etc"
+    >>> site_config_dir(appname, multipath=True)
+    '/etc/SuperApp:/usr/local/etc/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/home/trentm/.local/state/SuperApp/log'
+    >>> user_documents_dir()
+    '/home/trentm/Documents'
+    >>> user_downloads_dir()
+    '/home/trentm/Downloads'
+    >>> user_pictures_dir()
+    '/home/trentm/Pictures'
+    >>> user_videos_dir()
+    '/home/trentm/Videos'
+    >>> user_music_dir()
+    '/home/trentm/Music'
+    >>> user_desktop_dir()
+    '/home/trentm/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/run/user/{os.getuid()}/SuperApp'
+
+On Android::
+
+    >>> from platformdirs import *
+    >>> appname = "SuperApp"
+    >>> appauthor = "Acme"
+    >>> user_data_dir(appname, appauthor)
+    '/data/data/com.myApp/files/SuperApp'
+    >>> user_config_dir(appname)
+    '/data/data/com.myApp/shared_prefs/SuperApp'
+    >>> user_cache_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp'
+    >>> site_data_dir(appname, appauthor)
+    '/data/data/com.myApp/files/SuperApp'
+    >>> site_config_dir(appname)
+    '/data/data/com.myApp/shared_prefs/SuperApp'
+    >>> user_log_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp/log'
+    >>> user_documents_dir()
+    '/storage/emulated/0/Documents'
+    >>> user_downloads_dir()
+    '/storage/emulated/0/Downloads'
+    >>> user_pictures_dir()
+    '/storage/emulated/0/Pictures'
+    >>> user_videos_dir()
+    '/storage/emulated/0/DCIM/Camera'
+    >>> user_music_dir()
+    '/storage/emulated/0/Music'
+    >>> user_desktop_dir()
+    '/storage/emulated/0/Desktop'
+    >>> user_runtime_dir(appname, appauthor)
+    '/data/data/com.myApp/cache/SuperApp/tmp'
+
+Note: Some android apps like Termux and Pydroid are used as shells. These
+apps are used by the end user to emulate Linux environment. Presence of
+``SHELL`` environment variable is used by Platformdirs to differentiate
+between general android apps and android apps used as shells. Shell android
+apps also support ``XDG_*`` environment variables.
+
+
+``PlatformDirs`` for convenience
+================================
+
+.. code-block:: pycon
+
+    >>> from platformdirs import PlatformDirs
+    >>> dirs = PlatformDirs("SuperApp", "Acme")
+    >>> dirs.user_data_dir
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> dirs.user_config_dir
+    '/Users/trentm/Library/Application Support/SuperApp'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp'
+    >>> dirs.site_config_dir
+    '/Library/Application Support/SuperApp'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp'
+    >>> dirs.user_log_dir
+    '/Users/trentm/Library/Logs/SuperApp'
+    >>> dirs.user_documents_dir
+    '/Users/trentm/Documents'
+    >>> dirs.user_downloads_dir
+    '/Users/trentm/Downloads'
+    >>> dirs.user_pictures_dir
+    '/Users/trentm/Pictures'
+    >>> dirs.user_videos_dir
+    '/Users/trentm/Movies'
+    >>> dirs.user_music_dir
+    '/Users/trentm/Music'
+    >>> dirs.user_desktop_dir
+    '/Users/trentm/Desktop'
+    >>> dirs.user_runtime_dir
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'
+
+Per-version isolation
+=====================
+
+If you have multiple versions of your app in use that you want to be
+able to run side-by-side, then you may want version-isolation for these
+dirs::
+
+    >>> from platformdirs import PlatformDirs
+    >>> dirs = PlatformDirs("SuperApp", "Acme", version="1.0")
+    >>> dirs.user_data_dir
+    '/Users/trentm/Library/Application Support/SuperApp/1.0'
+    >>> dirs.user_config_dir
+    '/Users/trentm/Library/Application Support/SuperApp/1.0'
+    >>> dirs.user_cache_dir
+    '/Users/trentm/Library/Caches/SuperApp/1.0'
+    >>> dirs.site_data_dir
+    '/Library/Application Support/SuperApp/1.0'
+    >>> dirs.site_config_dir
+    '/Library/Application Support/SuperApp/1.0'
+    >>> dirs.user_log_dir
+    '/Users/trentm/Library/Logs/SuperApp/1.0'
+    >>> dirs.user_documents_dir
+    '/Users/trentm/Documents'
+    >>> dirs.user_downloads_dir
+    '/Users/trentm/Downloads'
+    >>> dirs.user_pictures_dir
+    '/Users/trentm/Pictures'
+    >>> dirs.user_videos_dir
+    '/Users/trentm/Movies'
+    >>> dirs.user_music_dir
+    '/Users/trentm/Music'
+    >>> dirs.user_desktop_dir
+    '/Users/trentm/Desktop'
+    >>> dirs.user_runtime_dir
+    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp/1.0'
+
+Be wary of using this for configuration files though; you'll need to handle
+migrating configuration files manually.
+
+Why this Fork?
+==============
+
+This repository is a friendly fork of the wonderful work started by
+`ActiveState `_ who created
+``appdirs``, this package's ancestor.
+
+Maintaining an open source project is no easy task, particularly
+from within an organization, and the Python community is indebted
+to ``appdirs`` (and to Trent Mick and Jeff Rouse in particular) for
+creating an incredibly useful simple module, as evidenced by the wide
+number of users it has attracted over the years.
+
+Nonetheless, given the number of long-standing open issues
+and pull requests, and no clear path towards `ensuring
+that maintenance of the package would continue or grow
+`_, this fork was
+created.
+
+Contributions are most welcome.
diff --git a/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..467d2560dcfe0bd1adb58b617712d3bd6b55015f
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/RECORD
@@ -0,0 +1,24 @@
+platformdirs-4.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+platformdirs-4.5.0.dist-info/METADATA,sha256=mFxZl6Q-fO2nCdWWCJT4WOr4p7U12jZX4lk26MqGy1o,12804
+platformdirs-4.5.0.dist-info/RECORD,,
+platformdirs-4.5.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs-4.5.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
+platformdirs-4.5.0.dist-info/direct_url.json,sha256=lQH-GplgUjaVTxy8DMxY3ERjzo9R5XJoFS0LVVsIgGw,102
+platformdirs-4.5.0.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+platformdirs/__init__.py,sha256=iORRy6_lZ9tXLvO0W6fJPn8QV7F532ivl-f2WGmabBc,22284
+platformdirs/__main__.py,sha256=HnsUQHpiBaiTxwcmwVw-nFaPdVNZtQIdi1eWDtI-MzI,1493
+platformdirs/__pycache__/__init__.cpython-313.pyc,,
+platformdirs/__pycache__/__main__.cpython-313.pyc,,
+platformdirs/__pycache__/android.cpython-313.pyc,,
+platformdirs/__pycache__/api.cpython-313.pyc,,
+platformdirs/__pycache__/macos.cpython-313.pyc,,
+platformdirs/__pycache__/unix.cpython-313.pyc,,
+platformdirs/__pycache__/version.cpython-313.pyc,,
+platformdirs/__pycache__/windows.cpython-313.pyc,,
+platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013
+platformdirs/api.py,sha256=wPHOlwOsfz2oqQZ6A2FcCu5kEAj-JondzoNOHYFQ0h8,9281
+platformdirs/macos.py,sha256=0XoOgin1NK7Qki7iskD-oS8xKxw6bXgoKEgdqpCRAFQ,6322
+platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458
+platformdirs/version.py,sha256=ghBiiwST_TekbxAaCoGDq-02Sb8IhzrkJl3n7HTe4dc,511
+platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125
diff --git a/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.27.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..d4e9bc5d309f820832c0c961513fb1c2e98c6702
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/platformdirs-4.5.0.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///home/task_176235602006708/conda-bld/platformdirs_1762356487962/work"}
\ No newline at end of file
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..b55dfbe1e5db5c11a4cf4ba91c687ae9b26584d8
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/METADATA
@@ -0,0 +1,43 @@
+Metadata-Version: 2.4
+Name: pycollada
+Version: 0.9.3
+Summary: python library for reading and writing collada documents
+Author-email: Jeff Terrace and contributors 
+License: BSD
+Project-URL: Homepage, http://pycollada.readthedocs.org/
+Platform: any
+Description-Content-Type: text/markdown
+License-File: COPYING
+License-File: AUTHORS.md
+Requires-Dist: python-dateutil
+Requires-Dist: numpy
+Provides-Extra: prettyprint
+Requires-Dist: lxml; extra == "prettyprint"
+Provides-Extra: validation
+Requires-Dist: lxml; extra == "validation"
+Dynamic: license-file
+
+# pycollada
+
+pycollada is a python module for creating, editing and loading
+[COLLADA](https://www.khronos.org/collada/), which is a COLLAborative Design Activity
+for establishing an interchange file format for interactive 3D applications.
+
+The library allows you to load a COLLADA file and interact with it as a python
+object. In addition, it supports creating a collada python object from scratch,
+as well as in-place editing.
+
+You can get help at the [pycollada mailing list](https://groups.google.com/d/forum/pycollada).
+
+See the [pycollada Documentation](http://pycollada.readthedocs.org/) for more
+information.
+
+![Build Status](https://github.com/pycollada/pycollada/actions/workflows/python-package.yml/badge.svg)
+
+## Projects using pycollada
+
+* [FreeCAD COLLADA Import/Export](https://freecad.org)
+* [Blender COLLADA Importer](https://github.com/skrat/bpycollada)
+* [Meshtool](https://github.com/pycollada/meshtool)
+* [SceneJS COLLADA Import](https://github.com/xeolabs/scenejs-pycollada)
+* [Faces in Relief](https://itunes.apple.com/us/app/faces-in-relief/id571820477?ls=1&mt=8)
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..3eaa462c46cd38bbc182104bb67b89b4f5985e6f
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/RECORD
@@ -0,0 +1,76 @@
+collada/__init__.py,sha256=S46tiCK6kgslY_46WHdQXbV1rMC8AeIR7UfarpZPNwE,24539
+collada/__main__.py,sha256=jF3bjMkU7XIb5TYREujpflYx6tIrEzZpYC6KBm0SN30,1074
+collada/__pycache__/__init__.cpython-313.pyc,,
+collada/__pycache__/__main__.cpython-313.pyc,,
+collada/__pycache__/animation.cpython-313.pyc,,
+collada/__pycache__/asset.cpython-313.pyc,,
+collada/__pycache__/camera.cpython-313.pyc,,
+collada/__pycache__/common.cpython-313.pyc,,
+collada/__pycache__/controller.cpython-313.pyc,,
+collada/__pycache__/geometry.cpython-313.pyc,,
+collada/__pycache__/light.cpython-313.pyc,,
+collada/__pycache__/lineset.cpython-313.pyc,,
+collada/__pycache__/material.cpython-313.pyc,,
+collada/__pycache__/polygons.cpython-313.pyc,,
+collada/__pycache__/polylist.cpython-313.pyc,,
+collada/__pycache__/primitive.cpython-313.pyc,,
+collada/__pycache__/scene.cpython-313.pyc,,
+collada/__pycache__/schema.cpython-313.pyc,,
+collada/__pycache__/source.cpython-313.pyc,,
+collada/__pycache__/triangleset.cpython-313.pyc,,
+collada/__pycache__/util.cpython-313.pyc,,
+collada/__pycache__/xmlutil.cpython-313.pyc,,
+collada/animation.py,sha256=qjBtzSyY8fWM7lqtYh1tA5qciNaJNateDbjaoBwxCPM,2207
+collada/asset.py,sha256=LTvykmCULvUC_M8iDnehJ4RNi9kuE55ARSwVe9Z3CKo,10742
+collada/camera.py,sha256=bbi0ybqNCULVEDztt_CZ6wCCUMZ11ALm5hENdBvZpxI,15308
+collada/common.py,sha256=SQPLXyGklJteJpqDf-cRbyIdcB4Z_OJ_uLPcYP9iawo,3216
+collada/controller.py,sha256=GWm6GiCobr1Hjz9xgPLvuva91hRWnuq8wtXaKcNSoZo,16691
+collada/geometry.py,sha256=lOmwCR6ykiUCsGIKHjAKghUenXX3xK13PTIttfN7UYw,16651
+collada/light.py,sha256=IPxnT1HsWsgSL7yD86f-tDD-PxRs9AAVP9bVLCGnKXI,22075
+collada/lineset.py,sha256=w140Tw7lUyvxPQzaQ6Ozs9H7w5JacV7nrXMtUEN6QR0,10940
+collada/material.py,sha256=FALdpNPbqA08qxHvRjkX_Ljld3YEuYrgCtJpff6HUfI,36384
+collada/polygons.py,sha256=VsoCIiA3JuhlJgGDWOZC-FHTKUVWb9sXsLS4bQkPeP0,4747
+collada/polylist.py,sha256=0nAp8wtCGAL-NIKyCzEAD6zogZ__43I_iLNLJA0kpHs,16598
+collada/primitive.py,sha256=rgpuQSTlc0-FE-DNbJfq7rd88w7xBKcLIUWb8E6qpp0,9958
+collada/resources/__init__.py,sha256=6mb6xzzpaEaCX_f1ooSzb_O3tHU6bGI_PKOkts8WM0I,435
+collada/resources/__pycache__/__init__.cpython-313.pyc,,
+collada/resources/schema-1.4.1.xml,sha256=MCFtnDognOe5Owkd7cbMPQY13HXaJwiiAsQhVMj0UQ4,573663
+collada/resources/xsd.xml,sha256=MOCOA9m2OAHTvygdePXRnyUqAVWTj4hdMPOzHnI1vCQ,4779
+collada/scene.py,sha256=N_7FyhWKNx1vkzEV1xaYoWS3pAC1yWZLjsGLTCSqC5A,39764
+collada/schema.py,sha256=6DW2xrlHadc9ZE2X9eusJ9xmRpmr1NJ1ZH_hA_PfTE0,2682
+collada/source.py,sha256=iNZ3F3UY47Rz3pENNtR9mRbLCzyrjBn8JmfjnrzWqu4,18329
+collada/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+collada/tests/__pycache__/__init__.cpython-313.pyc,,
+collada/tests/__pycache__/test_asset.cpython-313.pyc,,
+collada/tests/__pycache__/test_camera.cpython-313.pyc,,
+collada/tests/__pycache__/test_collada.cpython-313.pyc,,
+collada/tests/__pycache__/test_geometry.cpython-313.pyc,,
+collada/tests/__pycache__/test_ignore.cpython-313.pyc,,
+collada/tests/__pycache__/test_iteration.cpython-313.pyc,,
+collada/tests/__pycache__/test_light.cpython-313.pyc,,
+collada/tests/__pycache__/test_lineset.cpython-313.pyc,,
+collada/tests/__pycache__/test_material.cpython-313.pyc,,
+collada/tests/__pycache__/test_scene.cpython-313.pyc,,
+collada/tests/__pycache__/test_source.cpython-313.pyc,,
+collada/tests/test_asset.py,sha256=PbPAjn7qzoRd7_ZSHZe8izjpWNNgbA0B8enLYz7294o,4085
+collada/tests/test_camera.py,sha256=HMO9Ajtmr3MwyYEuWTzi_5cKnZK4_a3BemPZcgZGpd8,7269
+collada/tests/test_collada.py,sha256=8jVFSlbTJFGykWwaqU-y2ZGxp33doXx4N-ZV_JIoPVw,17841
+collada/tests/test_geometry.py,sha256=g4R5G8FaK4f6XBDKYoJ3YT7vmKGvKOXr_V8PZxjUSus,11339
+collada/tests/test_ignore.py,sha256=vKbZbDUU49pfJnZ_UrowEUdfbUrCC2qmo98pHIi1QRo,2823
+collada/tests/test_iteration.py,sha256=6xg5v06E3kZMDWFFEgFVI5pbDVm1G6W4A6z4CdYu-QA,6474
+collada/tests/test_light.py,sha256=QloM7VWwDnpas2ffiwuALDchvT3Zkyay_XOE0ccIpv4,5022
+collada/tests/test_lineset.py,sha256=KtYpFz-m5eH2kULNyqiKLzZcy3AXcPChPDfUigNCBBg,2728
+collada/tests/test_material.py,sha256=sODpuY5Bvf2m_n9QTsqyb3rm1PgDRPhx_aM4XtxOAgg,14225
+collada/tests/test_scene.py,sha256=zLbA6ZG7rpy2JuSlK48Z_x3Yjn5gbxIh-AyZHjGn0Cs,17068
+collada/tests/test_source.py,sha256=zlLrEelfaCGCmZrG59brSYVnwbk6aY-iQQV4YH8qMas,3508
+collada/triangleset.py,sha256=nlf96gd1AWR4jKUFovV-r6PUxnnYzn5IFuaaJwvsTmM,19043
+collada/util.py,sha256=uPuoF0PA5d9CdPd_9hs4_OwM2m67bCxLwUIjD8Ud0nI,8018
+collada/xmlutil.py,sha256=zL-wY7DHSuMtf-2ScWL01ilLlkM_hdcAh5JJ3zcJ_7Y,4005
+pycollada-0.9.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pycollada-0.9.3.dist-info/METADATA,sha256=fMNjCIYoPNZhC3E9kGR7Nnnjh5i20voTakmg4QTE-vs,1659
+pycollada-0.9.3.dist-info/RECORD,,
+pycollada-0.9.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pycollada-0.9.3.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92
+pycollada-0.9.3.dist-info/licenses/AUTHORS.md,sha256=Ha_Dgo7ybAptZ7pj2tkc6qHuLPlUV1CtRLLlFYnn_5c,428
+pycollada-0.9.3.dist-info/licenses/COPYING,sha256=EBmC2X2buBkRGRt22OLJn0m8HE7kPFlt2gMiWqc0a4k,1628
+pycollada-0.9.3.dist-info/top_level.txt,sha256=7y5AmSmRri6si8lRD708EnVWuqkVtHyR49USu9CgsC4,8
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..fbbd86cb272bc6e329803bf67f442f2a124caa95
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.10.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..377afd1468c58f0ec18b3cd01206d53633def2c6
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycollada-0.9.3.dist-info/top_level.txt
@@ -0,0 +1 @@
+collada
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
\ No newline at end of file
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..6a8fb36e6aa42373cc739de5a6d451c2fc301a6d
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/RECORD
@@ -0,0 +1,43 @@
+pycparser-2.23.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pycparser-2.23.dist-info/METADATA,sha256=5fb53n_0XoR9_Ddek-LMiJPKpEAY6247CHz9MMzi2F0,1210
+pycparser-2.23.dist-info/RECORD,,
+pycparser-2.23.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pycparser-2.23.dist-info/WHEEL,sha256=lTU6B6eIfYoiQJTZNc-fyaR6BpL6ehTzU3xGYxn2n8k,91
+pycparser-2.23.dist-info/direct_url.json,sha256=WY4-hl51f7oMIAnkgwV2p5hVRTZIZ2R46isFZd8c3AU,99
+pycparser-2.23.dist-info/licenses/LICENSE,sha256=DIRjmTaep23de1xE_m0WSXQV_PAV9cu1CMJL-YuBxbE,1543
+pycparser-2.23.dist-info/top_level.txt,sha256=c-lPcS74L_8KoH7IE6PQF5ofyirRQNV4VhkbSFIPeWM,10
+pycparser/__init__.py,sha256=FQFl5XuxXZiYHrBuN1EElN1COlR8k4aCSdG7h7a7zLw,2918
+pycparser/__pycache__/__init__.cpython-313.pyc,,
+pycparser/__pycache__/_ast_gen.cpython-313.pyc,,
+pycparser/__pycache__/_build_tables.cpython-313.pyc,,
+pycparser/__pycache__/ast_transforms.cpython-313.pyc,,
+pycparser/__pycache__/c_ast.cpython-313.pyc,,
+pycparser/__pycache__/c_generator.cpython-313.pyc,,
+pycparser/__pycache__/c_lexer.cpython-313.pyc,,
+pycparser/__pycache__/c_parser.cpython-313.pyc,,
+pycparser/__pycache__/lextab.cpython-313.pyc,,
+pycparser/__pycache__/plyparser.cpython-313.pyc,,
+pycparser/__pycache__/yacctab.cpython-313.pyc,,
+pycparser/_ast_gen.py,sha256=0JRVnDW-Jw-3IjVlo8je9rbAcp6Ko7toHAnB5zi7h0Q,10555
+pycparser/_build_tables.py,sha256=4d_UkIxJ4YfHTVn6xBzBA52wDo7qxg1B6aZAJYJas9Q,1087
+pycparser/_c_ast.cfg,sha256=ld5ezE9yzIJFIVAUfw7ezJSlMi4nXKNCzfmqjOyQTNo,4255
+pycparser/ast_transforms.py,sha256=GTMYlUgWmXd5wJVyovXY1qzzAqjxzCpVVg0664dKGBs,5691
+pycparser/c_ast.py,sha256=HWeOrfYdCY0u5XaYhE1i60uVyE3yMWdcxzECUX-DqJw,31445
+pycparser/c_generator.py,sha256=XWK3oGM_eVD5d_JfgJxFO95Y6vUMfRi8pov5FQjHH2s,17790
+pycparser/c_lexer.py,sha256=bq7LALBDUw452KT3J7QzHj2qMoCugGWjITNPWD7yiOE,17728
+pycparser/c_parser.py,sha256=ujQZ7y6Qded9h5SDrhtgSlHw0vSYVa_yiMtW9ZnsezY,75462
+pycparser/lextab.py,sha256=eLh3spnPArpAKCVAEK1JCOgUX0L9wrJdfOTLyw8sLRE,8776
+pycparser/ply/__init__.py,sha256=q4s86QwRsYRa20L9ueSxfh-hPihpftBjDOvYa2_SS2Y,102
+pycparser/ply/__pycache__/__init__.cpython-313.pyc,,
+pycparser/ply/__pycache__/cpp.cpython-313.pyc,,
+pycparser/ply/__pycache__/ctokens.cpython-313.pyc,,
+pycparser/ply/__pycache__/lex.cpython-313.pyc,,
+pycparser/ply/__pycache__/yacc.cpython-313.pyc,,
+pycparser/ply/__pycache__/ygen.cpython-313.pyc,,
+pycparser/ply/cpp.py,sha256=UtC3ylTWp5_1MKA-PLCuwKQR8zSOnlGuGGIdzj8xS98,33282
+pycparser/ply/ctokens.py,sha256=MKksnN40TehPhgVfxCJhjj_BjL943apreABKYz-bl0Y,3177
+pycparser/ply/lex.py,sha256=rCMi0yjlZmjH5SNXj_Yds1VxSDkaG2thS7351YvfN-I,42926
+pycparser/ply/yacc.py,sha256=eatSDkRLgRr6X3-hoDk_SQQv065R0BdL2K7fQ54CgVM,137323
+pycparser/ply/ygen.py,sha256=2JYNeYtrPz1JzLSLO3d4GsS8zJU8jY_I_CR1VI9gWrA,2251
+pycparser/plyparser.py,sha256=8tLOoEytcapvWrr1JfCf7Dog-wulBtS1YrDs8S7JfMo,4875
+pycparser/yacctab.py,sha256=ovX4pQW7sjbRf8c-GxpU6J65pqVGAgbU_G_YuW5NPHM,213007
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..370ec5f1aa3524bfd31a19fd21e907335f48a7f6
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (78.1.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..4232c04dcccb7ee31ce66bd86d23b6970b71e3aa
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///home/task_175749564936714/conda-bld/pycparser_1757496040682/work"}
\ No newline at end of file
diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..dc1c9e101ad9ccd943b359338ef42c342ebc84a1
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pycparser-2.23.dist-info/top_level.txt
@@ -0,0 +1 @@
+pycparser
diff --git a/data/miniconda3/lib/python3.13/site-packages/pydantic_core/__init__.py b/data/miniconda3/lib/python3.13/site-packages/pydantic_core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5facd16196818c1cc9a4cf78e4fae6efb273b40
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pydantic_core/__init__.py
@@ -0,0 +1,171 @@
+from __future__ import annotations
+
+import sys as _sys
+from typing import Any as _Any
+
+from typing_extensions import Sentinel
+
+from ._pydantic_core import (
+    ArgsKwargs,
+    MultiHostUrl,
+    PydanticCustomError,
+    PydanticKnownError,
+    PydanticOmit,
+    PydanticSerializationError,
+    PydanticSerializationUnexpectedValue,
+    PydanticUndefined,
+    PydanticUndefinedType,
+    PydanticUseDefault,
+    SchemaError,
+    SchemaSerializer,
+    SchemaValidator,
+    Some,
+    TzInfo,
+    Url,
+    ValidationError,
+    __version__,
+    from_json,
+    to_json,
+    to_jsonable_python,
+)
+from .core_schema import CoreConfig, CoreSchema, CoreSchemaType, ErrorType
+
+if _sys.version_info < (3, 11):
+    from typing_extensions import NotRequired as _NotRequired
+else:
+    from typing import NotRequired as _NotRequired
+
+if _sys.version_info < (3, 12):
+    from typing_extensions import TypedDict as _TypedDict
+else:
+    from typing import TypedDict as _TypedDict
+
+__all__ = [
+    '__version__',
+    'UNSET',
+    'CoreConfig',
+    'CoreSchema',
+    'CoreSchemaType',
+    'SchemaValidator',
+    'SchemaSerializer',
+    'Some',
+    'Url',
+    'MultiHostUrl',
+    'ArgsKwargs',
+    'PydanticUndefined',
+    'PydanticUndefinedType',
+    'SchemaError',
+    'ErrorDetails',
+    'InitErrorDetails',
+    'ValidationError',
+    'PydanticCustomError',
+    'PydanticKnownError',
+    'PydanticOmit',
+    'PydanticUseDefault',
+    'PydanticSerializationError',
+    'PydanticSerializationUnexpectedValue',
+    'TzInfo',
+    'to_json',
+    'from_json',
+    'to_jsonable_python',
+]
+
+
+class ErrorDetails(_TypedDict):
+    type: str
+    """
+    The type of error that occurred, this is an identifier designed for
+    programmatic use that will change rarely or never.
+
+    `type` is unique for each error message, and can hence be used as an identifier to build custom error messages.
+    """
+    loc: tuple[int | str, ...]
+    """Tuple of strings and ints identifying where in the schema the error occurred."""
+    msg: str
+    """A human readable error message."""
+    input: _Any
+    """The input data at this `loc` that caused the error."""
+    ctx: _NotRequired[dict[str, _Any]]
+    """
+    Values which are required to render the error message, and could hence be useful in rendering custom error messages.
+    Also useful for passing custom error data forward.
+    """
+    url: _NotRequired[str]
+    """
+    The documentation URL giving information about the error. No URL is available if
+    a [`PydanticCustomError`][pydantic_core.PydanticCustomError] is used.
+    """
+
+
+class InitErrorDetails(_TypedDict):
+    type: str | PydanticCustomError
+    """The type of error that occurred, this should be a "slug" identifier that changes rarely or never."""
+    loc: _NotRequired[tuple[int | str, ...]]
+    """Tuple of strings and ints identifying where in the schema the error occurred."""
+    input: _Any
+    """The input data at this `loc` that caused the error."""
+    ctx: _NotRequired[dict[str, _Any]]
+    """
+    Values which are required to render the error message, and could hence be useful in rendering custom error messages.
+    Also useful for passing custom error data forward.
+    """
+
+
+class ErrorTypeInfo(_TypedDict):
+    """
+    Gives information about errors.
+    """
+
+    type: ErrorType
+    """The type of error that occurred, this should be a "slug" identifier that changes rarely or never."""
+    message_template_python: str
+    """String template to render a human readable error message from using context, when the input is Python."""
+    example_message_python: str
+    """Example of a human readable error message, when the input is Python."""
+    message_template_json: _NotRequired[str]
+    """String template to render a human readable error message from using context, when the input is JSON data."""
+    example_message_json: _NotRequired[str]
+    """Example of a human readable error message, when the input is JSON data."""
+    example_context: dict[str, _Any] | None
+    """Example of context values."""
+
+
+class MultiHostHost(_TypedDict):
+    """
+    A host part of a multi-host URL.
+    """
+
+    username: str | None
+    """The username part of this host, or `None`."""
+    password: str | None
+    """The password part of this host, or `None`."""
+    host: str | None
+    """The host part of this host, or `None`."""
+    port: int | None
+    """The port part of this host, or `None`."""
+
+
+MISSING = Sentinel('MISSING')
+"""A singleton indicating a field value was not provided during validation.
+
+This singleton can be used a default value, as an alternative to `None` when it has
+an explicit meaning. During serialization, any field with `MISSING` as a value is excluded
+from the output.
+
+Example:
+    ```python
+    from pydantic import BaseModel
+
+    from pydantic_core import MISSING
+
+
+    class Configuration(BaseModel):
+        timeout: int | None | MISSING = MISSING
+
+
+    # configuration defaults, stored somewhere else:
+    defaults = {'timeout': 200}
+
+    conf = Configuration.model_validate({...})
+    timeout = conf.timeout if timeout.timeout is not MISSING else defaults['timeout']
+"""
diff --git a/data/miniconda3/lib/python3.13/site-packages/pydantic_core/_pydantic_core.pyi b/data/miniconda3/lib/python3.13/site-packages/pydantic_core/_pydantic_core.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..8ae631ab55f648f2b910f3d6299457a168cee13d
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pydantic_core/_pydantic_core.pyi
@@ -0,0 +1,1046 @@
+import datetime
+from collections.abc import Mapping
+from typing import Any, Callable, Generic, Literal, TypeVar, final
+
+from _typeshed import SupportsAllComparisons
+from typing_extensions import LiteralString, Self, TypeAlias
+
+from pydantic_core import ErrorDetails, ErrorTypeInfo, InitErrorDetails, MultiHostHost
+from pydantic_core.core_schema import CoreConfig, CoreSchema, ErrorType, ExtraBehavior
+
+__all__ = [
+    '__version__',
+    'build_profile',
+    'build_info',
+    '_recursion_limit',
+    'ArgsKwargs',
+    'SchemaValidator',
+    'SchemaSerializer',
+    'Url',
+    'MultiHostUrl',
+    'SchemaError',
+    'ValidationError',
+    'PydanticCustomError',
+    'PydanticKnownError',
+    'PydanticOmit',
+    'PydanticUseDefault',
+    'PydanticSerializationError',
+    'PydanticSerializationUnexpectedValue',
+    'PydanticUndefined',
+    'PydanticUndefinedType',
+    'Some',
+    'to_json',
+    'from_json',
+    'to_jsonable_python',
+    'list_all_errors',
+    'TzInfo',
+]
+__version__: str
+build_profile: str
+build_info: str
+_recursion_limit: int
+
+_T = TypeVar('_T', default=Any, covariant=True)
+
+_StringInput: TypeAlias = 'dict[str, _StringInput]'
+
+@final
+class Some(Generic[_T]):
+    """
+    Similar to Rust's [`Option::Some`](https://doc.rust-lang.org/std/option/enum.Option.html) type, this
+    identifies a value as being present, and provides a way to access it.
+
+    Generally used in a union with `None` to different between "some value which could be None" and no value.
+    """
+
+    __match_args__ = ('value',)
+
+    @property
+    def value(self) -> _T:
+        """
+        Returns the value wrapped by `Some`.
+        """
+    @classmethod
+    def __class_getitem__(cls, item: Any, /) -> type[Self]: ...
+
+@final
+class SchemaValidator:
+    """
+    `SchemaValidator` is the Python wrapper for `pydantic-core`'s Rust validation logic, internally it owns one
+    `CombinedValidator` which may in turn own more `CombinedValidator`s which make up the full schema validator.
+    """
+
+    # note: pyo3 currently supports __new__, but not __init__, though we include __init__ stubs
+    # and docstrings here (and in the following classes) for documentation purposes
+
+    def __init__(self, schema: CoreSchema, config: CoreConfig | None = None) -> None:
+        """Initializes the `SchemaValidator`.
+
+        Arguments:
+            schema: The `CoreSchema` to use for validation.
+            config: Optionally a [`CoreConfig`][pydantic_core.core_schema.CoreConfig] to configure validation.
+        """
+
+    def __new__(cls, schema: CoreSchema, config: CoreConfig | None = None) -> Self: ...
+    @property
+    def title(self) -> str:
+        """
+        The title of the schema, as used in the heading of [`ValidationError.__str__()`][pydantic_core.ValidationError].
+        """
+    def validate_python(
+        self,
+        input: Any,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        from_attributes: bool | None = None,
+        context: Any | None = None,
+        self_instance: Any | None = None,
+        allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Any:
+        """
+        Validate a Python object against the schema and return the validated object.
+
+        Arguments:
+            input: The Python object to validate.
+            strict: Whether to validate the object in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                If `None`, the value of [`CoreConfig.extra_fields_behavior`][pydantic_core.core_schema.CoreConfig] is used.
+            from_attributes: Whether to validate objects as inputs to models by extracting attributes.
+                If `None`, the value of [`CoreConfig.from_attributes`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+            self_instance: An instance of a model set attributes on from validation, this is used when running
+                validation from the `__init__` method of a model.
+            allow_partial: Whether to allow partial validation; if `True` errors in the last element of sequences
+                and mappings are ignored.
+                `'trailing-strings'` means any final unfinished JSON string is included in the result.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If validation fails.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            The validated object.
+        """
+    def isinstance_python(
+        self,
+        input: Any,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        from_attributes: bool | None = None,
+        context: Any | None = None,
+        self_instance: Any | None = None,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> bool:
+        """
+        Similar to [`validate_python()`][pydantic_core.SchemaValidator.validate_python] but returns a boolean.
+
+        Arguments match `validate_python()`. This method will not raise `ValidationError`s but will raise internal
+        errors.
+
+        Returns:
+            `True` if validation succeeds, `False` if validation fails.
+        """
+    def validate_json(
+        self,
+        input: str | bytes | bytearray,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        context: Any | None = None,
+        self_instance: Any | None = None,
+        allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Any:
+        """
+        Validate JSON data directly against the schema and return the validated Python object.
+
+        This method should be significantly faster than `validate_python(json.loads(json_data))` as it avoids the
+        need to create intermediate Python objects
+
+        It also handles constructing the correct Python type even in strict mode, where
+        `validate_python(json.loads(json_data))` would fail validation.
+
+        Arguments:
+            input: The JSON data to validate.
+            strict: Whether to validate the object in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                If `None`, the value of [`CoreConfig.extra_fields_behavior`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+            self_instance: An instance of a model set attributes on from validation.
+            allow_partial: Whether to allow partial validation; if `True` incomplete JSON will be parsed successfully
+                and errors in the last element of sequences and mappings are ignored.
+                `'trailing-strings'` means any final unfinished JSON string is included in the result.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If validation fails or if the JSON data is invalid.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            The validated Python object.
+        """
+    def validate_strings(
+        self,
+        input: _StringInput,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        context: Any | None = None,
+        allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> Any:
+        """
+        Validate a string against the schema and return the validated Python object.
+
+        This is similar to `validate_json` but applies to scenarios where the input will be a string but not
+        JSON data, e.g. URL fragments, query parameters, etc.
+
+        Arguments:
+            input: The input as a string, or bytes/bytearray if `strict=False`.
+            strict: Whether to validate the object in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                If `None`, the value of [`CoreConfig.extra_fields_behavior`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+            allow_partial: Whether to allow partial validation; if `True` errors in the last element of sequences
+                and mappings are ignored.
+                `'trailing-strings'` means any final unfinished JSON string is included in the result.
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If validation fails or if the JSON data is invalid.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            The validated Python object.
+        """
+    def validate_assignment(
+        self,
+        obj: Any,
+        field_name: str,
+        field_value: Any,
+        *,
+        strict: bool | None = None,
+        extra: ExtraBehavior | None = None,
+        from_attributes: bool | None = None,
+        context: Any | None = None,
+        by_alias: bool | None = None,
+        by_name: bool | None = None,
+    ) -> dict[str, Any] | tuple[dict[str, Any], dict[str, Any] | None, set[str]]:
+        """
+        Validate an assignment to a field on a model.
+
+        Arguments:
+            obj: The model instance being assigned to.
+            field_name: The name of the field to validate assignment for.
+            field_value: The value to assign to the field.
+            strict: Whether to validate the object in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            extra: Whether to ignore, allow, or forbid extra data during model validation.
+                If `None`, the value of [`CoreConfig.extra_fields_behavior`][pydantic_core.core_schema.CoreConfig] is used.
+            from_attributes: Whether to validate objects as inputs to models by extracting attributes.
+                If `None`, the value of [`CoreConfig.from_attributes`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+            by_alias: Whether to use the field's alias when validating against the provided input data.
+            by_name: Whether to use the field's name when validating against the provided input data.
+
+        Raises:
+            ValidationError: If validation fails.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            Either the model dict or a tuple of `(model_data, model_extra, fields_set)`
+        """
+    def get_default_value(self, *, strict: bool | None = None, context: Any = None) -> Some | None:
+        """
+        Get the default value for the schema, including running default value validation.
+
+        Arguments:
+            strict: Whether to validate the default value in strict mode.
+                If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used.
+            context: The context to use for validation, this is passed to functional validators as
+                [`info.context`][pydantic_core.core_schema.ValidationInfo.context].
+
+        Raises:
+            ValidationError: If validation fails.
+            Exception: Other error types maybe raised if internal errors occur.
+
+        Returns:
+            `None` if the schema has no default value, otherwise a [`Some`][pydantic_core.Some] containing the default.
+        """
+
+# In reality, `bool` should be replaced by `Literal[True]` but mypy fails to correctly apply bidirectional type inference
+# (e.g. when using `{'a': {'b': True}}`).
+_IncEx: TypeAlias = set[int] | set[str] | Mapping[int, _IncEx | bool] | Mapping[str, _IncEx | bool]
+
+@final
+class SchemaSerializer:
+    """
+    `SchemaSerializer` is the Python wrapper for `pydantic-core`'s Rust serialization logic, internally it owns one
+    `CombinedSerializer` which may in turn own more `CombinedSerializer`s which make up the full schema serializer.
+    """
+
+    def __init__(self, schema: CoreSchema, config: CoreConfig | None = None) -> None:
+        """Initializes the `SchemaSerializer`.
+
+        Arguments:
+            schema: The `CoreSchema` to use for serialization.
+            config: Optionally a [`CoreConfig`][pydantic_core.core_schema.CoreConfig] to to configure serialization.
+        """
+
+    def __new__(cls, schema: CoreSchema, config: CoreConfig | None = None) -> Self: ...
+    def to_python(
+        self,
+        value: Any,
+        *,
+        mode: str | None = None,
+        include: _IncEx | None = None,
+        exclude: _IncEx | None = None,
+        by_alias: bool | None = None,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        exclude_computed_fields: bool = False,
+        round_trip: bool = False,
+        warnings: bool | Literal['none', 'warn', 'error'] = True,
+        fallback: Callable[[Any], Any] | None = None,
+        serialize_as_any: bool = False,
+        context: Any | None = None,
+    ) -> Any:
+        """
+        Serialize/marshal a Python object to a Python object including transforming and filtering data.
+
+        Arguments:
+            value: The Python object to serialize.
+            mode: The serialization mode to use, either `'python'` or `'json'`, defaults to `'python'`. In JSON mode,
+                all values are converted to JSON compatible types, e.g. `None`, `int`, `float`, `str`, `list`, `dict`.
+            include: A set of fields to include, if `None` all fields are included.
+            exclude: A set of fields to exclude, if `None` no fields are excluded.
+            by_alias: Whether to use the alias names of fields.
+            exclude_unset: Whether to exclude fields that are not set,
+                e.g. are not included in `__pydantic_fields_set__`.
+            exclude_defaults: Whether to exclude fields that are equal to their default value.
+            exclude_none: Whether to exclude fields that have a value of `None`.
+            exclude_computed_fields: Whether to exclude computed fields.
+            round_trip: Whether to enable serialization and validation round-trip support.
+            warnings: How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors,
+                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+            fallback: A function to call when an unknown value is encountered,
+                if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+            context: The context to use for serialization, this is passed to functional serializers as
+                [`info.context`][pydantic_core.core_schema.SerializationInfo.context].
+
+        Raises:
+            PydanticSerializationError: If serialization fails and no `fallback` function is provided.
+
+        Returns:
+            The serialized Python object.
+        """
+    def to_json(
+        self,
+        value: Any,
+        *,
+        indent: int | None = None,
+        ensure_ascii: bool = False,
+        include: _IncEx | None = None,
+        exclude: _IncEx | None = None,
+        by_alias: bool | None = None,
+        exclude_unset: bool = False,
+        exclude_defaults: bool = False,
+        exclude_none: bool = False,
+        exclude_computed_fields: bool = False,
+        round_trip: bool = False,
+        warnings: bool | Literal['none', 'warn', 'error'] = True,
+        fallback: Callable[[Any], Any] | None = None,
+        serialize_as_any: bool = False,
+        context: Any | None = None,
+    ) -> bytes:
+        """
+        Serialize a Python object to JSON including transforming and filtering data.
+
+        Arguments:
+            value: The Python object to serialize.
+            indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
+            ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
+                If `False` (the default), these characters will be output as-is.
+            include: A set of fields to include, if `None` all fields are included.
+            exclude: A set of fields to exclude, if `None` no fields are excluded.
+            by_alias: Whether to use the alias names of fields.
+            exclude_unset: Whether to exclude fields that are not set,
+                e.g. are not included in `__pydantic_fields_set__`.
+            exclude_defaults: Whether to exclude fields that are equal to their default value.
+            exclude_none: Whether to exclude fields that have a value of `None`.
+            exclude_computed_fields: Whether to exclude computed fields.
+            round_trip: Whether to enable serialization and validation round-trip support.
+            warnings: How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors,
+                "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
+            fallback: A function to call when an unknown value is encountered,
+                if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+            serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+            context: The context to use for serialization, this is passed to functional serializers as
+                [`info.context`][pydantic_core.core_schema.SerializationInfo.context].
+
+        Raises:
+            PydanticSerializationError: If serialization fails and no `fallback` function is provided.
+
+        Returns:
+           JSON bytes.
+        """
+
+def to_json(
+    value: Any,
+    *,
+    indent: int | None = None,
+    ensure_ascii: bool = False,
+    include: _IncEx | None = None,
+    exclude: _IncEx | None = None,
+    # Note: In Pydantic 2.11, the default value of `by_alias` on `SchemaSerializer` was changed from `True` to `None`,
+    # to be consistent with the Pydantic "dump" methods. However, the default of `True` was kept here for
+    # backwards compatibility. In Pydantic V3, `by_alias` is expected to default to `True` everywhere:
+    by_alias: bool = True,
+    exclude_none: bool = False,
+    round_trip: bool = False,
+    timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
+    temporal_mode: Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601',
+    bytes_mode: Literal['utf8', 'base64', 'hex'] = 'utf8',
+    inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants',
+    serialize_unknown: bool = False,
+    fallback: Callable[[Any], Any] | None = None,
+    serialize_as_any: bool = False,
+    context: Any | None = None,
+) -> bytes:
+    """
+    Serialize a Python object to JSON including transforming and filtering data.
+
+    This is effectively a standalone version of [`SchemaSerializer.to_json`][pydantic_core.SchemaSerializer.to_json].
+
+    Arguments:
+        value: The Python object to serialize.
+        indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
+        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
+            If `False` (the default), these characters will be output as-is.
+        include: A set of fields to include, if `None` all fields are included.
+        exclude: A set of fields to exclude, if `None` no fields are excluded.
+        by_alias: Whether to use the alias names of fields.
+        exclude_none: Whether to exclude fields that have a value of `None`.
+        round_trip: Whether to enable serialization and validation round-trip support.
+        timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.
+        temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.
+            `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.
+
+        bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.
+        inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.
+        serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails
+            `""` will be used.
+        fallback: A function to call when an unknown value is encountered,
+            if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+        context: The context to use for serialization, this is passed to functional serializers as
+            [`info.context`][pydantic_core.core_schema.SerializationInfo.context].
+
+    Raises:
+        PydanticSerializationError: If serialization fails and no `fallback` function is provided.
+
+    Returns:
+       JSON bytes.
+    """
+
+def from_json(
+    data: str | bytes | bytearray,
+    *,
+    allow_inf_nan: bool = True,
+    cache_strings: bool | Literal['all', 'keys', 'none'] = True,
+    allow_partial: bool | Literal['off', 'on', 'trailing-strings'] = False,
+) -> Any:
+    """
+    Deserialize JSON data to a Python object.
+
+    This is effectively a faster version of `json.loads()`, with some extra functionality.
+
+    Arguments:
+        data: The JSON data to deserialize.
+        allow_inf_nan: Whether to allow `Infinity`, `-Infinity` and `NaN` values as `json.loads()` does by default.
+        cache_strings: Whether to cache strings to avoid constructing new Python objects,
+            this should have a significant impact on performance while increasing memory usage slightly,
+            `all/True` means cache all strings, `keys` means cache only dict keys, `none/False` means no caching.
+        allow_partial: Whether to allow partial deserialization, if `True` JSON data is returned if the end of the
+            input is reached before the full object is deserialized, e.g. `["aa", "bb", "c` would return `['aa', 'bb']`.
+            `'trailing-strings'` means any final unfinished JSON string is included in the result.
+
+    Raises:
+        ValueError: If deserialization fails.
+
+    Returns:
+        The deserialized Python object.
+    """
+
+def to_jsonable_python(
+    value: Any,
+    *,
+    include: _IncEx | None = None,
+    exclude: _IncEx | None = None,
+    # Note: In Pydantic 2.11, the default value of `by_alias` on `SchemaSerializer` was changed from `True` to `None`,
+    # to be consistent with the Pydantic "dump" methods. However, the default of `True` was kept here for
+    # backwards compatibility. In Pydantic V3, `by_alias` is expected to default to `True` everywhere:
+    by_alias: bool = True,
+    exclude_none: bool = False,
+    round_trip: bool = False,
+    timedelta_mode: Literal['iso8601', 'float'] = 'iso8601',
+    temporal_mode: Literal['iso8601', 'seconds', 'milliseconds'] = 'iso8601',
+    bytes_mode: Literal['utf8', 'base64', 'hex'] = 'utf8',
+    inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants',
+    serialize_unknown: bool = False,
+    fallback: Callable[[Any], Any] | None = None,
+    serialize_as_any: bool = False,
+    context: Any | None = None,
+) -> Any:
+    """
+    Serialize/marshal a Python object to a JSON-serializable Python object including transforming and filtering data.
+
+    This is effectively a standalone version of
+    [`SchemaSerializer.to_python(mode='json')`][pydantic_core.SchemaSerializer.to_python].
+
+    Args:
+        value: The Python object to serialize.
+        include: A set of fields to include, if `None` all fields are included.
+        exclude: A set of fields to exclude, if `None` no fields are excluded.
+        by_alias: Whether to use the alias names of fields.
+        exclude_none: Whether to exclude fields that have a value of `None`.
+        round_trip: Whether to enable serialization and validation round-trip support.
+        timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.
+        temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.
+            `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.
+
+        bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.
+        inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.
+        serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails
+            `""` will be used.
+        fallback: A function to call when an unknown value is encountered,
+            if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
+        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
+        context: The context to use for serialization, this is passed to functional serializers as
+            [`info.context`][pydantic_core.core_schema.SerializationInfo.context].
+
+    Raises:
+        PydanticSerializationError: If serialization fails and no `fallback` function is provided.
+
+    Returns:
+        The serialized Python object.
+    """
+
+class Url(SupportsAllComparisons):
+    """
+    A URL type, internal logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed
+    by Mozilla.
+    """
+
+    def __init__(self, url: str) -> None: ...
+    def __new__(cls, url: str) -> Self: ...
+    @property
+    def scheme(self) -> str: ...
+    @property
+    def username(self) -> str | None: ...
+    @property
+    def password(self) -> str | None: ...
+    @property
+    def host(self) -> str | None: ...
+    def unicode_host(self) -> str | None: ...
+    @property
+    def port(self) -> int | None: ...
+    @property
+    def path(self) -> str | None: ...
+    @property
+    def query(self) -> str | None: ...
+    def query_params(self) -> list[tuple[str, str]]: ...
+    @property
+    def fragment(self) -> str | None: ...
+    def unicode_string(self) -> str: ...
+    def __repr__(self) -> str: ...
+    def __str__(self) -> str: ...
+    def __deepcopy__(self, memo: dict) -> str: ...
+    @classmethod
+    def build(
+        cls,
+        *,
+        scheme: str,
+        username: str | None = None,
+        password: str | None = None,
+        host: str,
+        port: int | None = None,
+        path: str | None = None,
+        query: str | None = None,
+        fragment: str | None = None,
+    ) -> Self: ...
+
+class MultiHostUrl(SupportsAllComparisons):
+    """
+    A URL type with support for multiple hosts, as used by some databases for DSNs, e.g. `https://foo.com,bar.com/path`.
+
+    Internal URL logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed
+    by Mozilla.
+    """
+
+    def __init__(self, url: str) -> None: ...
+    def __new__(cls, url: str) -> Self: ...
+    @property
+    def scheme(self) -> str: ...
+    @property
+    def path(self) -> str | None: ...
+    @property
+    def query(self) -> str | None: ...
+    def query_params(self) -> list[tuple[str, str]]: ...
+    @property
+    def fragment(self) -> str | None: ...
+    def hosts(self) -> list[MultiHostHost]: ...
+    def unicode_string(self) -> str: ...
+    def __repr__(self) -> str: ...
+    def __str__(self) -> str: ...
+    def __deepcopy__(self, memo: dict) -> Self: ...
+    @classmethod
+    def build(
+        cls,
+        *,
+        scheme: str,
+        hosts: list[MultiHostHost] | None = None,
+        username: str | None = None,
+        password: str | None = None,
+        host: str | None = None,
+        port: int | None = None,
+        path: str | None = None,
+        query: str | None = None,
+        fragment: str | None = None,
+    ) -> Self: ...
+
+@final
+class SchemaError(Exception):
+    """
+    Information about errors that occur while building a [`SchemaValidator`][pydantic_core.SchemaValidator]
+    or [`SchemaSerializer`][pydantic_core.SchemaSerializer].
+    """
+
+    def error_count(self) -> int:
+        """
+        Returns:
+            The number of errors in the schema.
+        """
+    def errors(self) -> list[ErrorDetails]:
+        """
+        Returns:
+            A list of [`ErrorDetails`][pydantic_core.ErrorDetails] for each error in the schema.
+        """
+
+class ValidationError(ValueError):
+    """
+    `ValidationError` is the exception raised by `pydantic-core` when validation fails, it contains a list of errors
+    which detail why validation failed.
+    """
+    @classmethod
+    def from_exception_data(
+        cls,
+        title: str,
+        line_errors: list[InitErrorDetails],
+        input_type: Literal['python', 'json'] = 'python',
+        hide_input: bool = False,
+    ) -> Self:
+        """
+        Python constructor for a Validation Error.
+
+        Arguments:
+            title: The title of the error, as used in the heading of `str(validation_error)`
+            line_errors: A list of [`InitErrorDetails`][pydantic_core.InitErrorDetails] which contain information
+                about errors that occurred during validation.
+            input_type: Whether the error is for a Python object or JSON.
+            hide_input: Whether to hide the input value in the error message.
+        """
+    @property
+    def title(self) -> str:
+        """
+        The title of the error, as used in the heading of `str(validation_error)`.
+        """
+    def error_count(self) -> int:
+        """
+        Returns:
+            The number of errors in the validation error.
+        """
+    def errors(
+        self, *, include_url: bool = True, include_context: bool = True, include_input: bool = True
+    ) -> list[ErrorDetails]:
+        """
+        Details about each error in the validation error.
+
+        Args:
+            include_url: Whether to include a URL to documentation on the error each error.
+            include_context: Whether to include the context of each error.
+            include_input: Whether to include the input value of each error.
+
+        Returns:
+            A list of [`ErrorDetails`][pydantic_core.ErrorDetails] for each error in the validation error.
+        """
+    def json(
+        self,
+        *,
+        indent: int | None = None,
+        include_url: bool = True,
+        include_context: bool = True,
+        include_input: bool = True,
+    ) -> str:
+        """
+        Same as [`errors()`][pydantic_core.ValidationError.errors] but returns a JSON string.
+
+        Args:
+            indent: The number of spaces to indent the JSON by, or `None` for no indentation - compact JSON.
+            include_url: Whether to include a URL to documentation on the error each error.
+            include_context: Whether to include the context of each error.
+            include_input: Whether to include the input value of each error.
+
+        Returns:
+            a JSON string.
+        """
+
+    def __repr__(self) -> str:
+        """
+        A string representation of the validation error.
+
+        Whether or not documentation URLs are included in the repr is controlled by the
+        environment variable `PYDANTIC_ERRORS_INCLUDE_URL` being set to `1` or
+        `true`; by default, URLs are shown.
+
+        Due to implementation details, this environment variable can only be set once,
+        before the first validation error is created.
+        """
+
+class PydanticCustomError(ValueError):
+    """A custom exception providing flexible error handling for Pydantic validators.
+
+    You can raise this error in custom validators when you'd like flexibility in regards to the error type, message, and context.
+
+    Example:
+        ```py
+        from pydantic_core import PydanticCustomError
+
+        def custom_validator(v) -> None:
+            if v <= 10:
+                raise PydanticCustomError('custom_value_error', 'Value must be greater than {value}', {'value': 10, 'extra_context': 'extra_data'})
+            return v
+        ```
+
+    Arguments:
+        error_type: The error type.
+        message_template: The message template.
+        context: The data to inject into the message template.
+    """
+
+    def __init__(
+        self, error_type: LiteralString, message_template: LiteralString, context: dict[str, Any] | None = None, /
+    ) -> None: ...
+    @property
+    def context(self) -> dict[str, Any] | None:
+        """Values which are required to render the error message, and could hence be useful in passing error data forward."""
+
+    @property
+    def type(self) -> str:
+        """The error type associated with the error. For consistency with Pydantic, this is typically a snake_case string."""
+
+    @property
+    def message_template(self) -> str:
+        """The message template associated with the error. This is a string that can be formatted with context variables in `{curly_braces}`."""
+
+    def message(self) -> str:
+        """The formatted message associated with the error. This presents as the message template with context variables appropriately injected."""
+
+@final
+class PydanticKnownError(ValueError):
+    """A helper class for raising exceptions that mimic Pydantic's built-in exceptions, with more flexibility in regards to context.
+
+    Unlike [`PydanticCustomError`][pydantic_core.PydanticCustomError], the `error_type` argument must be a known `ErrorType`.
+
+    Example:
+        ```py
+        from pydantic_core import PydanticKnownError
+
+        def custom_validator(v) -> None:
+            if v <= 10:
+                raise PydanticKnownError('greater_than', {'gt': 10})
+            return v
+        ```
+
+    Arguments:
+        error_type: The error type.
+        context: The data to inject into the message template.
+    """
+
+    def __init__(self, error_type: ErrorType, context: dict[str, Any] | None = None, /) -> None: ...
+    @property
+    def context(self) -> dict[str, Any] | None:
+        """Values which are required to render the error message, and could hence be useful in passing error data forward."""
+
+    @property
+    def type(self) -> ErrorType:
+        """The type of the error."""
+
+    @property
+    def message_template(self) -> str:
+        """The message template associated with the provided error type. This is a string that can be formatted with context variables in `{curly_braces}`."""
+
+    def message(self) -> str:
+        """The formatted message associated with the error. This presents as the message template with context variables appropriately injected."""
+
+@final
+class PydanticOmit(Exception):
+    """An exception to signal that a field should be omitted from a generated result.
+
+    This could span from omitting a field from a JSON Schema to omitting a field from a serialized result.
+    Upcoming: more robust support for using PydanticOmit in custom serializers is still in development.
+    Right now, this is primarily used in the JSON Schema generation process.
+
+    Example:
+        ```py
+        from typing import Callable
+
+        from pydantic_core import PydanticOmit
+
+        from pydantic import BaseModel
+        from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
+
+
+        class MyGenerateJsonSchema(GenerateJsonSchema):
+            def handle_invalid_for_json_schema(self, schema, error_info) -> JsonSchemaValue:
+                raise PydanticOmit
+
+
+        class Predicate(BaseModel):
+            name: str = 'no-op'
+            func: Callable = lambda x: x
+
+
+        instance_example = Predicate()
+
+        validation_schema = instance_example.model_json_schema(schema_generator=MyGenerateJsonSchema, mode='validation')
+        print(validation_schema)
+        '''
+        {'properties': {'name': {'default': 'no-op', 'title': 'Name', 'type': 'string'}}, 'title': 'Predicate', 'type': 'object'}
+        '''
+        ```
+
+    For a more in depth example / explanation, see the [customizing JSON schema](../concepts/json_schema.md#customizing-the-json-schema-generation-process) docs.
+    """
+
+    def __new__(cls) -> Self: ...
+
+@final
+class PydanticUseDefault(Exception):
+    """An exception to signal that standard validation either failed or should be skipped, and the default value should be used instead.
+
+    This warning can be raised in custom valiation functions to redirect the flow of validation.
+
+    Example:
+        ```py
+        from pydantic_core import PydanticUseDefault
+        from datetime import datetime
+        from pydantic import BaseModel, field_validator
+
+
+        class Event(BaseModel):
+            name: str = 'meeting'
+            time: datetime
+
+            @field_validator('name', mode='plain')
+            def name_must_be_present(cls, v) -> str:
+                if not v or not isinstance(v, str):
+                    raise PydanticUseDefault()
+                return v
+
+
+        event1 = Event(name='party', time=datetime(2024, 1, 1, 12, 0, 0))
+        print(repr(event1))
+        # > Event(name='party', time=datetime.datetime(2024, 1, 1, 12, 0))
+        event2 = Event(time=datetime(2024, 1, 1, 12, 0, 0))
+        print(repr(event2))
+        # > Event(name='meeting', time=datetime.datetime(2024, 1, 1, 12, 0))
+        ```
+
+    For an additional example, see the [validating partial json data](../concepts/json.md#partial-json-parsing) section of the Pydantic documentation.
+    """
+
+    def __new__(cls) -> Self: ...
+
+@final
+class PydanticSerializationError(ValueError):
+    """An error raised when an issue occurs during serialization.
+
+    In custom serializers, this error can be used to indicate that serialization has failed.
+
+    Arguments:
+        message: The message associated with the error.
+    """
+
+    def __init__(self, message: str, /) -> None: ...
+
+@final
+class PydanticSerializationUnexpectedValue(ValueError):
+    """An error raised when an unexpected value is encountered during serialization.
+
+    This error is often caught and coerced into a warning, as `pydantic-core` generally makes a best attempt
+    at serializing values, in contrast with validation where errors are eagerly raised.
+
+    Example:
+        ```py
+        from pydantic import BaseModel, field_serializer
+        from pydantic_core import PydanticSerializationUnexpectedValue
+
+        class BasicPoint(BaseModel):
+            x: int
+            y: int
+
+            @field_serializer('*')
+            def serialize(self, v):
+                if not isinstance(v, int):
+                    raise PydanticSerializationUnexpectedValue(f'Expected type `int`, got {type(v)} with value {v}')
+                return v
+
+        point = BasicPoint(x=1, y=2)
+        # some sort of mutation
+        point.x = 'a'
+
+        print(point.model_dump())
+        '''
+        UserWarning: Pydantic serializer warnings:
+        PydanticSerializationUnexpectedValue(Expected type `int`, got  with value a)
+        return self.__pydantic_serializer__.to_python(
+        {'x': 'a', 'y': 2}
+        '''
+        ```
+
+    This is often used internally in `pydantic-core` when unexpected types are encountered during serialization,
+    but it can also be used by users in custom serializers, as seen above.
+
+    Arguments:
+        message: The message associated with the unexpected value.
+    """
+
+    def __init__(self, message: str, /) -> None: ...
+
+@final
+class ArgsKwargs:
+    """A construct used to store arguments and keyword arguments for a function call.
+
+    This data structure is generally used to store information for core schemas associated with functions (like in an arguments schema).
+    This data structure is also currently used for some validation against dataclasses.
+
+    Example:
+        ```py
+        from pydantic.dataclasses import dataclass
+        from pydantic import model_validator
+
+
+        @dataclass
+        class Model:
+            a: int
+            b: int
+
+            @model_validator(mode="before")
+            @classmethod
+            def no_op_validator(cls, values):
+                print(values)
+                return values
+
+        Model(1, b=2)
+        #> ArgsKwargs((1,), {"b": 2})
+
+        Model(1, 2)
+        #> ArgsKwargs((1, 2), {})
+
+        Model(a=1, b=2)
+        #> ArgsKwargs((), {"a": 1, "b": 2})
+        ```
+    """
+
+    def __init__(self, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None) -> None:
+        """Initializes the `ArgsKwargs`.
+
+        Arguments:
+            args: The arguments (inherently ordered) for a function call.
+            kwargs: The keyword arguments for a function call
+        """
+
+    def __new__(cls, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None) -> Self: ...
+    @property
+    def args(self) -> tuple[Any, ...]:
+        """The arguments (inherently ordered) for a function call."""
+
+    @property
+    def kwargs(self) -> dict[str, Any] | None:
+        """The keyword arguments for a function call."""
+
+@final
+class PydanticUndefinedType:
+    """A type used as a sentinel for undefined values."""
+
+    def __copy__(self) -> Self: ...
+    def __deepcopy__(self, memo: Any) -> Self: ...
+
+PydanticUndefined: PydanticUndefinedType
+
+def list_all_errors() -> list[ErrorTypeInfo]:
+    """
+    Get information about all built-in errors.
+
+    Returns:
+        A list of `ErrorTypeInfo` typed dicts.
+    """
+@final
+class TzInfo(datetime.tzinfo):
+    """An `pydantic-core` implementation of the abstract [`datetime.tzinfo`][] class."""
+
+    def __init__(self, seconds: float = 0.0) -> None:
+        """Initializes the `TzInfo`.
+
+        Arguments:
+            seconds: The offset from UTC in seconds. Defaults to 0.0 (UTC).
+        """
+
+    def __new__(cls, seconds: float = 0.0) -> Self: ...
+
+    # Docstrings for attributes sourced from the abstract base class, [`datetime.tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo).
+
+    def tzname(self, dt: datetime.datetime | None) -> str | None:
+        """Return the time zone name corresponding to the [`datetime`][datetime.datetime] object _dt_, as a string.
+
+        For more info, see [`tzinfo.tzname`][datetime.tzinfo.tzname].
+        """
+
+    def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta | None:
+        """Return offset of local time from UTC, as a [`timedelta`][datetime.timedelta] object that is positive east of UTC. If local time is west of UTC, this should be negative.
+
+        More info can be found at [`tzinfo.utcoffset`][datetime.tzinfo.utcoffset].
+        """
+
+    def dst(self, dt: datetime.datetime | None) -> datetime.timedelta | None:
+        """Return the daylight saving time (DST) adjustment, as a [`timedelta`][datetime.timedelta] object or `None` if DST information isn’t known.
+
+        More info can be found at[`tzinfo.dst`][datetime.tzinfo.dst]."""
+
+    def fromutc(self, dt: datetime.datetime) -> datetime.datetime:
+        """Adjust the date and time data associated datetime object _dt_, returning an equivalent datetime in self’s local time.
+
+        More info can be found at [`tzinfo.fromutc`][datetime.tzinfo.fromutc]."""
+
+    def __deepcopy__(self, _memo: dict[Any, Any]) -> TzInfo: ...
diff --git a/data/miniconda3/lib/python3.13/site-packages/pydantic_core/core_schema.py b/data/miniconda3/lib/python3.13/site-packages/pydantic_core/core_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8a3b6da6f9fadcc6e7b67742dab32ac7f029a3e
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pydantic_core/core_schema.py
@@ -0,0 +1,4435 @@
+"""
+This module contains definitions to build schemas which `pydantic_core` can
+validate and serialize.
+"""
+
+from __future__ import annotations as _annotations
+
+import sys
+import warnings
+from collections.abc import Hashable, Mapping
+from datetime import date, datetime, time, timedelta
+from decimal import Decimal
+from re import Pattern
+from typing import TYPE_CHECKING, Any, Callable, Literal, Union
+
+from typing_extensions import TypeVar, deprecated
+
+if sys.version_info < (3, 12):
+    from typing_extensions import TypedDict
+else:
+    from typing import TypedDict
+
+if sys.version_info < (3, 11):
+    from typing_extensions import Protocol, Required, TypeAlias
+else:
+    from typing import Protocol, Required, TypeAlias
+
+if TYPE_CHECKING:
+    from pydantic_core import PydanticUndefined
+else:
+    # The initial build of pydantic_core requires PydanticUndefined to generate
+    # the core schema; so we need to conditionally skip it. mypy doesn't like
+    # this at all, hence the TYPE_CHECKING branch above.
+    try:
+        from pydantic_core import PydanticUndefined
+    except ImportError:
+        PydanticUndefined = object()
+
+
+ExtraBehavior = Literal['allow', 'forbid', 'ignore']
+
+
+class CoreConfig(TypedDict, total=False):
+    """
+    Base class for schema configuration options.
+
+    Attributes:
+        title: The name of the configuration.
+        strict: Whether the configuration should strictly adhere to specified rules.
+        extra_fields_behavior: The behavior for handling extra fields.
+        typed_dict_total: Whether the TypedDict should be considered total. Default is `True`.
+        from_attributes: Whether to use attributes for models, dataclasses, and tagged union keys.
+        loc_by_alias: Whether to use the used alias (or first alias for "field required" errors) instead of
+            `field_names` to construct error `loc`s. Default is `True`.
+        revalidate_instances: Whether instances of models and dataclasses should re-validate. Default is 'never'.
+        validate_default: Whether to validate default values during validation. Default is `False`.
+        str_max_length: The maximum length for string fields.
+        str_min_length: The minimum length for string fields.
+        str_strip_whitespace: Whether to strip whitespace from string fields.
+        str_to_lower: Whether to convert string fields to lowercase.
+        str_to_upper: Whether to convert string fields to uppercase.
+        allow_inf_nan: Whether to allow infinity and NaN values for float fields. Default is `True`.
+        ser_json_timedelta: The serialization option for `timedelta` values. Default is 'iso8601'.
+            Note that if ser_json_temporal is set, then this param will be ignored.
+        ser_json_temporal: The serialization option for datetime like values. Default is 'iso8601'.
+            The types this covers are datetime, date, time and timedelta.
+            If this is set, it will take precedence over ser_json_timedelta
+        ser_json_bytes: The serialization option for `bytes` values. Default is 'utf8'.
+        ser_json_inf_nan: The serialization option for infinity and NaN values
+            in float fields. Default is 'null'.
+        val_json_bytes: The validation option for `bytes` values, complementing ser_json_bytes. Default is 'utf8'.
+        hide_input_in_errors: Whether to hide input data from `ValidationError` representation.
+        validation_error_cause: Whether to add user-python excs to the __cause__ of a ValidationError.
+            Requires exceptiongroup backport pre Python 3.11.
+        coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
+        regex_engine: The regex engine to use for regex pattern validation. Default is 'rust-regex'. See `StringSchema`.
+        cache_strings: Whether to cache strings. Default is `True`, `True` or `'all'` is required to cache strings
+            during general validation since validators don't know if they're in a key or a value.
+        validate_by_alias: Whether to use the field's alias when validating against the provided input data. Default is `True`.
+        validate_by_name: Whether to use the field's name when validating against the provided input data. Default is `False`. Replacement for `populate_by_name`.
+        serialize_by_alias: Whether to serialize by alias. Default is `False`, expected to change to `True` in V3.
+        url_preserve_empty_path: Whether to preserve empty URL paths when validating values for a URL type. Defaults to `False`.
+    """
+
+    title: str
+    strict: bool
+    # settings related to typed dicts, model fields, dataclass fields
+    extra_fields_behavior: ExtraBehavior
+    typed_dict_total: bool  # default: True
+    # used for models, dataclasses, and tagged union keys
+    from_attributes: bool
+    # whether to use the used alias (or first alias for "field required" errors) instead of field_names
+    # to construct error `loc`s, default True
+    loc_by_alias: bool
+    # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never'
+    revalidate_instances: Literal['always', 'never', 'subclass-instances']
+    # whether to validate default values during validation, default False
+    validate_default: bool
+    # used on typed-dicts and arguments
+    # fields related to string fields only
+    str_max_length: int
+    str_min_length: int
+    str_strip_whitespace: bool
+    str_to_lower: bool
+    str_to_upper: bool
+    # fields related to float fields only
+    allow_inf_nan: bool  # default: True
+    # the config options are used to customise serialization to JSON
+    ser_json_timedelta: Literal['iso8601', 'float']  # default: 'iso8601'
+    ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']  # default: 'iso8601'
+    ser_json_bytes: Literal['utf8', 'base64', 'hex']  # default: 'utf8'
+    ser_json_inf_nan: Literal['null', 'constants', 'strings']  # default: 'null'
+    val_json_bytes: Literal['utf8', 'base64', 'hex']  # default: 'utf8'
+    # used to hide input data from ValidationError repr
+    hide_input_in_errors: bool
+    validation_error_cause: bool  # default: False
+    coerce_numbers_to_str: bool  # default: False
+    regex_engine: Literal['rust-regex', 'python-re']  # default: 'rust-regex'
+    cache_strings: Union[bool, Literal['all', 'keys', 'none']]  # default: 'True'
+    validate_by_alias: bool  # default: True
+    validate_by_name: bool  # default: False
+    serialize_by_alias: bool  # default: False
+    url_preserve_empty_path: bool  # default: False
+
+
+IncExCall: TypeAlias = 'set[int | str] | dict[int | str, IncExCall] | None'
+
+ContextT = TypeVar('ContextT', covariant=True, default='Any | None')
+
+
+class SerializationInfo(Protocol[ContextT]):
+    """Extra data used during serialization."""
+
+    @property
+    def include(self) -> IncExCall:
+        """The `include` argument set during serialization."""
+        ...
+
+    @property
+    def exclude(self) -> IncExCall:
+        """The `exclude` argument set during serialization."""
+        ...
+
+    @property
+    def context(self) -> ContextT:
+        """The current serialization context."""
+        ...
+
+    @property
+    def mode(self) -> Literal['python', 'json'] | str:
+        """The serialization mode set during serialization."""
+        ...
+
+    @property
+    def by_alias(self) -> bool:
+        """The `by_alias` argument set during serialization."""
+        ...
+
+    @property
+    def exclude_unset(self) -> bool:
+        """The `exclude_unset` argument set during serialization."""
+        ...
+
+    @property
+    def exclude_defaults(self) -> bool:
+        """The `exclude_defaults` argument set during serialization."""
+        ...
+
+    @property
+    def exclude_none(self) -> bool:
+        """The `exclude_none` argument set during serialization."""
+        ...
+
+    @property
+    def exclude_computed_fields(self) -> bool:
+        """The `exclude_computed_fields` argument set during serialization."""
+        ...
+
+    @property
+    def serialize_as_any(self) -> bool:
+        """The `serialize_as_any` argument set during serialization."""
+        ...
+
+    @property
+    def round_trip(self) -> bool:
+        """The `round_trip` argument set during serialization."""
+        ...
+
+    def mode_is_json(self) -> bool: ...
+
+    def __str__(self) -> str: ...
+
+    def __repr__(self) -> str: ...
+
+
+class FieldSerializationInfo(SerializationInfo[ContextT], Protocol):
+    """Extra data used during field serialization."""
+
+    @property
+    def field_name(self) -> str:
+        """The name of the current field being serialized."""
+        ...
+
+
+class ValidationInfo(Protocol[ContextT]):
+    """Extra data used during validation."""
+
+    @property
+    def context(self) -> ContextT:
+        """The current validation context."""
+        ...
+
+    @property
+    def config(self) -> CoreConfig | None:
+        """The CoreConfig that applies to this validation."""
+        ...
+
+    @property
+    def mode(self) -> Literal['python', 'json']:
+        """The type of input data we are currently validating."""
+        ...
+
+    @property
+    def data(self) -> dict[str, Any]:
+        """The data being validated for this model."""
+        ...
+
+    @property
+    def field_name(self) -> str | None:
+        """
+        The name of the current field being validated if this validator is
+        attached to a model field.
+        """
+        ...
+
+
+ExpectedSerializationTypes = Literal[
+    'none',
+    'int',
+    'bool',
+    'float',
+    'str',
+    'bytes',
+    'bytearray',
+    'list',
+    'tuple',
+    'set',
+    'frozenset',
+    'generator',
+    'dict',
+    'datetime',
+    'date',
+    'time',
+    'timedelta',
+    'url',
+    'multi-host-url',
+    'json',
+    'uuid',
+    'any',
+]
+
+
+class SimpleSerSchema(TypedDict, total=False):
+    type: Required[ExpectedSerializationTypes]
+
+
+def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema:
+    """
+    Returns a schema for serialization with a custom type.
+
+    Args:
+        type: The type to use for serialization
+    """
+    return SimpleSerSchema(type=type)
+
+
+# (input_value: Any, /) -> Any
+GeneralPlainNoInfoSerializerFunction = Callable[[Any], Any]
+# (input_value: Any, info: FieldSerializationInfo, /) -> Any
+GeneralPlainInfoSerializerFunction = Callable[[Any, SerializationInfo[Any]], Any]
+# (model: Any, input_value: Any, /) -> Any
+FieldPlainNoInfoSerializerFunction = Callable[[Any, Any], Any]
+# (model: Any, input_value: Any, info: FieldSerializationInfo, /) -> Any
+FieldPlainInfoSerializerFunction = Callable[[Any, Any, FieldSerializationInfo[Any]], Any]
+SerializerFunction = Union[
+    GeneralPlainNoInfoSerializerFunction,
+    GeneralPlainInfoSerializerFunction,
+    FieldPlainNoInfoSerializerFunction,
+    FieldPlainInfoSerializerFunction,
+]
+
+WhenUsed = Literal['always', 'unless-none', 'json', 'json-unless-none']
+"""
+Values have the following meanings:
+
+* `'always'` means always use
+* `'unless-none'` means use unless the value is `None`
+* `'json'` means use when serializing to JSON
+* `'json-unless-none'` means use when serializing to JSON and the value is not `None`
+"""
+
+
+class PlainSerializerFunctionSerSchema(TypedDict, total=False):
+    type: Required[Literal['function-plain']]
+    function: Required[SerializerFunction]
+    is_field_serializer: bool  # default False
+    info_arg: bool  # default False
+    return_schema: CoreSchema  # if omitted, AnySchema is used
+    when_used: WhenUsed  # default: 'always'
+
+
+def plain_serializer_function_ser_schema(
+    function: SerializerFunction,
+    *,
+    is_field_serializer: bool | None = None,
+    info_arg: bool | None = None,
+    return_schema: CoreSchema | None = None,
+    when_used: WhenUsed = 'always',
+) -> PlainSerializerFunctionSerSchema:
+    """
+    Returns a schema for serialization with a function, can be either a "general" or "field" function.
+
+    Args:
+        function: The function to use for serialization
+        is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
+            and `info` includes `field_name`
+        info_arg: Whether the function takes an `info` argument
+        return_schema: Schema to use for serializing return value
+        when_used: When the function should be called
+    """
+    if when_used == 'always':
+        # just to avoid extra elements in schema, and to use the actual default defined in rust
+        when_used = None  # type: ignore
+    return _dict_not_none(
+        type='function-plain',
+        function=function,
+        is_field_serializer=is_field_serializer,
+        info_arg=info_arg,
+        return_schema=return_schema,
+        when_used=when_used,
+    )
+
+
+class SerializerFunctionWrapHandler(Protocol):  # pragma: no cover
+    def __call__(self, input_value: Any, index_key: int | str | None = None, /) -> Any: ...
+
+
+# (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
+GeneralWrapNoInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler], Any]
+# (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any
+GeneralWrapInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler, SerializationInfo[Any]], Any]
+# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
+FieldWrapNoInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler], Any]
+# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, info: FieldSerializationInfo, /) -> Any
+FieldWrapInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler, FieldSerializationInfo[Any]], Any]
+WrapSerializerFunction = Union[
+    GeneralWrapNoInfoSerializerFunction,
+    GeneralWrapInfoSerializerFunction,
+    FieldWrapNoInfoSerializerFunction,
+    FieldWrapInfoSerializerFunction,
+]
+
+
+class WrapSerializerFunctionSerSchema(TypedDict, total=False):
+    type: Required[Literal['function-wrap']]
+    function: Required[WrapSerializerFunction]
+    is_field_serializer: bool  # default False
+    info_arg: bool  # default False
+    schema: CoreSchema  # if omitted, the schema on which this serializer is defined is used
+    return_schema: CoreSchema  # if omitted, AnySchema is used
+    when_used: WhenUsed  # default: 'always'
+
+
+def wrap_serializer_function_ser_schema(
+    function: WrapSerializerFunction,
+    *,
+    is_field_serializer: bool | None = None,
+    info_arg: bool | None = None,
+    schema: CoreSchema | None = None,
+    return_schema: CoreSchema | None = None,
+    when_used: WhenUsed = 'always',
+) -> WrapSerializerFunctionSerSchema:
+    """
+    Returns a schema for serialization with a wrap function, can be either a "general" or "field" function.
+
+    Args:
+        function: The function to use for serialization
+        is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument,
+            and `info` includes `field_name`
+        info_arg: Whether the function takes an `info` argument
+        schema: The schema to use for the inner serialization
+        return_schema: Schema to use for serializing return value
+        when_used: When the function should be called
+    """
+    if when_used == 'always':
+        # just to avoid extra elements in schema, and to use the actual default defined in rust
+        when_used = None  # type: ignore
+    return _dict_not_none(
+        type='function-wrap',
+        function=function,
+        is_field_serializer=is_field_serializer,
+        info_arg=info_arg,
+        schema=schema,
+        return_schema=return_schema,
+        when_used=when_used,
+    )
+
+
+class FormatSerSchema(TypedDict, total=False):
+    type: Required[Literal['format']]
+    formatting_string: Required[str]
+    when_used: WhenUsed  # default: 'json-unless-none'
+
+
+def format_ser_schema(formatting_string: str, *, when_used: WhenUsed = 'json-unless-none') -> FormatSerSchema:
+    """
+    Returns a schema for serialization using python's `format` method.
+
+    Args:
+        formatting_string: String defining the format to use
+        when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
+    """
+    if when_used == 'json-unless-none':
+        # just to avoid extra elements in schema, and to use the actual default defined in rust
+        when_used = None  # type: ignore
+    return _dict_not_none(type='format', formatting_string=formatting_string, when_used=when_used)
+
+
+class ToStringSerSchema(TypedDict, total=False):
+    type: Required[Literal['to-string']]
+    when_used: WhenUsed  # default: 'json-unless-none'
+
+
+def to_string_ser_schema(*, when_used: WhenUsed = 'json-unless-none') -> ToStringSerSchema:
+    """
+    Returns a schema for serialization using python's `str()` / `__str__` method.
+
+    Args:
+        when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default
+    """
+    s = dict(type='to-string')
+    if when_used != 'json-unless-none':
+        # just to avoid extra elements in schema, and to use the actual default defined in rust
+        s['when_used'] = when_used
+    return s  # type: ignore
+
+
+class ModelSerSchema(TypedDict, total=False):
+    type: Required[Literal['model']]
+    cls: Required[type[Any]]
+    schema: Required[CoreSchema]
+
+
+def model_ser_schema(cls: type[Any], schema: CoreSchema) -> ModelSerSchema:
+    """
+    Returns a schema for serialization using a model.
+
+    Args:
+        cls: The expected class type, used to generate warnings if the wrong type is passed
+        schema: Internal schema to use to serialize the model dict
+    """
+    return ModelSerSchema(type='model', cls=cls, schema=schema)
+
+
+SerSchema = Union[
+    SimpleSerSchema,
+    PlainSerializerFunctionSerSchema,
+    WrapSerializerFunctionSerSchema,
+    FormatSerSchema,
+    ToStringSerSchema,
+    ModelSerSchema,
+]
+
+
+class InvalidSchema(TypedDict, total=False):
+    type: Required[Literal['invalid']]
+    ref: str
+    metadata: dict[str, Any]
+    # note, we never plan to use this, but include it for type checking purposes to match
+    # all other CoreSchema union members
+    serialization: SerSchema
+
+
+def invalid_schema(ref: str | None = None, metadata: dict[str, Any] | None = None) -> InvalidSchema:
+    """
+    Returns an invalid schema, used to indicate that a schema is invalid.
+
+        Returns a schema that matches any value, e.g.:
+
+    Args:
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+    """
+
+    return _dict_not_none(type='invalid', ref=ref, metadata=metadata)
+
+
+class ComputedField(TypedDict, total=False):
+    type: Required[Literal['computed-field']]
+    property_name: Required[str]
+    return_schema: Required[CoreSchema]
+    alias: str
+    metadata: dict[str, Any]
+
+
+def computed_field(
+    property_name: str, return_schema: CoreSchema, *, alias: str | None = None, metadata: dict[str, Any] | None = None
+) -> ComputedField:
+    """
+    ComputedFields are properties of a model or dataclass that are included in serialization.
+
+    Args:
+        property_name: The name of the property on the model or dataclass
+        return_schema: The schema used for the type returned by the computed field
+        alias: The name to use in the serialized output
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+    """
+    return _dict_not_none(
+        type='computed-field', property_name=property_name, return_schema=return_schema, alias=alias, metadata=metadata
+    )
+
+
+class AnySchema(TypedDict, total=False):
+    type: Required[Literal['any']]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def any_schema(
+    *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
+) -> AnySchema:
+    """
+    Returns a schema that matches any value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.any_schema()
+    v = SchemaValidator(schema)
+    assert v.validate_python(1) == 1
+    ```
+
+    Args:
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='any', ref=ref, metadata=metadata, serialization=serialization)
+
+
+class NoneSchema(TypedDict, total=False):
+    type: Required[Literal['none']]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def none_schema(
+    *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
+) -> NoneSchema:
+    """
+    Returns a schema that matches a None value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.none_schema()
+    v = SchemaValidator(schema)
+    assert v.validate_python(None) is None
+    ```
+
+    Args:
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='none', ref=ref, metadata=metadata, serialization=serialization)
+
+
+class BoolSchema(TypedDict, total=False):
+    type: Required[Literal['bool']]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def bool_schema(
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> BoolSchema:
+    """
+    Returns a schema that matches a bool value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.bool_schema()
+    v = SchemaValidator(schema)
+    assert v.validate_python('True') is True
+    ```
+
+    Args:
+        strict: Whether the value should be a bool or a value that can be converted to a bool
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='bool', strict=strict, ref=ref, metadata=metadata, serialization=serialization)
+
+
+class IntSchema(TypedDict, total=False):
+    type: Required[Literal['int']]
+    multiple_of: int
+    le: int
+    ge: int
+    lt: int
+    gt: int
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def int_schema(
+    *,
+    multiple_of: int | None = None,
+    le: int | None = None,
+    ge: int | None = None,
+    lt: int | None = None,
+    gt: int | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> IntSchema:
+    """
+    Returns a schema that matches a int value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.int_schema(multiple_of=2, le=6, ge=2)
+    v = SchemaValidator(schema)
+    assert v.validate_python('4') == 4
+    ```
+
+    Args:
+        multiple_of: The value must be a multiple of this number
+        le: The value must be less than or equal to this number
+        ge: The value must be greater than or equal to this number
+        lt: The value must be strictly less than this number
+        gt: The value must be strictly greater than this number
+        strict: Whether the value should be a int or a value that can be converted to a int
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='int',
+        multiple_of=multiple_of,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class FloatSchema(TypedDict, total=False):
+    type: Required[Literal['float']]
+    allow_inf_nan: bool  # whether 'NaN', '+inf', '-inf' should be forbidden. default: True
+    multiple_of: float
+    le: float
+    ge: float
+    lt: float
+    gt: float
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def float_schema(
+    *,
+    allow_inf_nan: bool | None = None,
+    multiple_of: float | None = None,
+    le: float | None = None,
+    ge: float | None = None,
+    lt: float | None = None,
+    gt: float | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> FloatSchema:
+    """
+    Returns a schema that matches a float value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.float_schema(le=0.8, ge=0.2)
+    v = SchemaValidator(schema)
+    assert v.validate_python('0.5') == 0.5
+    ```
+
+    Args:
+        allow_inf_nan: Whether to allow inf and nan values
+        multiple_of: The value must be a multiple of this number
+        le: The value must be less than or equal to this number
+        ge: The value must be greater than or equal to this number
+        lt: The value must be strictly less than this number
+        gt: The value must be strictly greater than this number
+        strict: Whether the value should be a float or a value that can be converted to a float
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='float',
+        allow_inf_nan=allow_inf_nan,
+        multiple_of=multiple_of,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DecimalSchema(TypedDict, total=False):
+    type: Required[Literal['decimal']]
+    allow_inf_nan: bool  # whether 'NaN', '+inf', '-inf' should be forbidden. default: False
+    multiple_of: Decimal
+    le: Decimal
+    ge: Decimal
+    lt: Decimal
+    gt: Decimal
+    max_digits: int
+    decimal_places: int
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def decimal_schema(
+    *,
+    allow_inf_nan: bool | None = None,
+    multiple_of: Decimal | None = None,
+    le: Decimal | None = None,
+    ge: Decimal | None = None,
+    lt: Decimal | None = None,
+    gt: Decimal | None = None,
+    max_digits: int | None = None,
+    decimal_places: int | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DecimalSchema:
+    """
+    Returns a schema that matches a decimal value, e.g.:
+
+    ```py
+    from decimal import Decimal
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.decimal_schema(le=0.8, ge=0.2)
+    v = SchemaValidator(schema)
+    assert v.validate_python('0.5') == Decimal('0.5')
+    ```
+
+    Args:
+        allow_inf_nan: Whether to allow inf and nan values
+        multiple_of: The value must be a multiple of this number
+        le: The value must be less than or equal to this number
+        ge: The value must be greater than or equal to this number
+        lt: The value must be strictly less than this number
+        gt: The value must be strictly greater than this number
+        max_digits: The maximum number of decimal digits allowed
+        decimal_places: The maximum number of decimal places allowed
+        strict: Whether the value should be a float or a value that can be converted to a float
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='decimal',
+        gt=gt,
+        ge=ge,
+        lt=lt,
+        le=le,
+        max_digits=max_digits,
+        decimal_places=decimal_places,
+        multiple_of=multiple_of,
+        allow_inf_nan=allow_inf_nan,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ComplexSchema(TypedDict, total=False):
+    type: Required[Literal['complex']]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def complex_schema(
+    *,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ComplexSchema:
+    """
+    Returns a schema that matches a complex value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.complex_schema()
+    v = SchemaValidator(schema)
+    assert v.validate_python('1+2j') == complex(1, 2)
+    assert v.validate_python(complex(1, 2)) == complex(1, 2)
+    ```
+
+    Args:
+        strict: Whether the value should be a complex object instance or a value that can be converted to a complex object
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='complex',
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class StringSchema(TypedDict, total=False):
+    type: Required[Literal['str']]
+    pattern: Union[str, Pattern[str]]
+    max_length: int
+    min_length: int
+    strip_whitespace: bool
+    to_lower: bool
+    to_upper: bool
+    regex_engine: Literal['rust-regex', 'python-re']  # default: 'rust-regex'
+    strict: bool
+    coerce_numbers_to_str: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def str_schema(
+    *,
+    pattern: str | Pattern[str] | None = None,
+    max_length: int | None = None,
+    min_length: int | None = None,
+    strip_whitespace: bool | None = None,
+    to_lower: bool | None = None,
+    to_upper: bool | None = None,
+    regex_engine: Literal['rust-regex', 'python-re'] | None = None,
+    strict: bool | None = None,
+    coerce_numbers_to_str: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> StringSchema:
+    """
+    Returns a schema that matches a string value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.str_schema(max_length=10, min_length=2)
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello') == 'hello'
+    ```
+
+    Args:
+        pattern: A regex pattern that the value must match
+        max_length: The value must be at most this length
+        min_length: The value must be at least this length
+        strip_whitespace: Whether to strip whitespace from the value
+        to_lower: Whether to convert the value to lowercase
+        to_upper: Whether to convert the value to uppercase
+        regex_engine: The regex engine to use for pattern validation. Default is 'rust-regex'.
+            - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust
+              crate, which is non-backtracking and therefore more DDoS
+              resistant, but does not support all regex features.
+            - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
+              which supports all regex features, but may be slower.
+        strict: Whether the value should be a string or a value that can be converted to a string
+        coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode).
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='str',
+        pattern=pattern,
+        max_length=max_length,
+        min_length=min_length,
+        strip_whitespace=strip_whitespace,
+        to_lower=to_lower,
+        to_upper=to_upper,
+        regex_engine=regex_engine,
+        strict=strict,
+        coerce_numbers_to_str=coerce_numbers_to_str,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class BytesSchema(TypedDict, total=False):
+    type: Required[Literal['bytes']]
+    max_length: int
+    min_length: int
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def bytes_schema(
+    *,
+    max_length: int | None = None,
+    min_length: int | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> BytesSchema:
+    """
+    Returns a schema that matches a bytes value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.bytes_schema(max_length=10, min_length=2)
+    v = SchemaValidator(schema)
+    assert v.validate_python(b'hello') == b'hello'
+    ```
+
+    Args:
+        max_length: The value must be at most this length
+        min_length: The value must be at least this length
+        strict: Whether the value should be a bytes or a value that can be converted to a bytes
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='bytes',
+        max_length=max_length,
+        min_length=min_length,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DateSchema(TypedDict, total=False):
+    type: Required[Literal['date']]
+    strict: bool
+    le: date
+    ge: date
+    lt: date
+    gt: date
+    now_op: Literal['past', 'future']
+    # defaults to current local utc offset from `time.localtime().tm_gmtoff`
+    # value is restricted to -86_400 < offset < 86_400:
+    now_utc_offset: int
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def date_schema(
+    *,
+    strict: bool | None = None,
+    le: date | None = None,
+    ge: date | None = None,
+    lt: date | None = None,
+    gt: date | None = None,
+    now_op: Literal['past', 'future'] | None = None,
+    now_utc_offset: int | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DateSchema:
+    """
+    Returns a schema that matches a date value, e.g.:
+
+    ```py
+    from datetime import date
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1))
+    v = SchemaValidator(schema)
+    assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1)
+    ```
+
+    Args:
+        strict: Whether the value should be a date or a value that can be converted to a date
+        le: The value must be less than or equal to this date
+        ge: The value must be greater than or equal to this date
+        lt: The value must be strictly less than this date
+        gt: The value must be strictly greater than this date
+        now_op: The value must be in the past or future relative to the current date
+        now_utc_offset: The value must be in the past or future relative to the current date with this utc offset
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='date',
+        strict=strict,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        now_op=now_op,
+        now_utc_offset=now_utc_offset,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TimeSchema(TypedDict, total=False):
+    type: Required[Literal['time']]
+    strict: bool
+    le: time
+    ge: time
+    lt: time
+    gt: time
+    tz_constraint: Union[Literal['aware', 'naive'], int]
+    microseconds_precision: Literal['truncate', 'error']
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def time_schema(
+    *,
+    strict: bool | None = None,
+    le: time | None = None,
+    ge: time | None = None,
+    lt: time | None = None,
+    gt: time | None = None,
+    tz_constraint: Literal['aware', 'naive'] | int | None = None,
+    microseconds_precision: Literal['truncate', 'error'] = 'truncate',
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> TimeSchema:
+    """
+    Returns a schema that matches a time value, e.g.:
+
+    ```py
+    from datetime import time
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.time_schema(le=time(12, 0, 0), ge=time(6, 0, 0))
+    v = SchemaValidator(schema)
+    assert v.validate_python(time(9, 0, 0)) == time(9, 0, 0)
+    ```
+
+    Args:
+        strict: Whether the value should be a time or a value that can be converted to a time
+        le: The value must be less than or equal to this time
+        ge: The value must be greater than or equal to this time
+        lt: The value must be strictly less than this time
+        gt: The value must be strictly greater than this time
+        tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset
+        microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='time',
+        strict=strict,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        tz_constraint=tz_constraint,
+        microseconds_precision=microseconds_precision,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DatetimeSchema(TypedDict, total=False):
+    type: Required[Literal['datetime']]
+    strict: bool
+    le: datetime
+    ge: datetime
+    lt: datetime
+    gt: datetime
+    now_op: Literal['past', 'future']
+    tz_constraint: Union[Literal['aware', 'naive'], int]
+    # defaults to current local utc offset from `time.localtime().tm_gmtoff`
+    # value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py
+    now_utc_offset: int
+    microseconds_precision: Literal['truncate', 'error']  # default: 'truncate'
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def datetime_schema(
+    *,
+    strict: bool | None = None,
+    le: datetime | None = None,
+    ge: datetime | None = None,
+    lt: datetime | None = None,
+    gt: datetime | None = None,
+    now_op: Literal['past', 'future'] | None = None,
+    tz_constraint: Literal['aware', 'naive'] | int | None = None,
+    now_utc_offset: int | None = None,
+    microseconds_precision: Literal['truncate', 'error'] = 'truncate',
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DatetimeSchema:
+    """
+    Returns a schema that matches a datetime value, e.g.:
+
+    ```py
+    from datetime import datetime
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.datetime_schema()
+    v = SchemaValidator(schema)
+    now = datetime.now()
+    assert v.validate_python(str(now)) == now
+    ```
+
+    Args:
+        strict: Whether the value should be a datetime or a value that can be converted to a datetime
+        le: The value must be less than or equal to this datetime
+        ge: The value must be greater than or equal to this datetime
+        lt: The value must be strictly less than this datetime
+        gt: The value must be strictly greater than this datetime
+        now_op: The value must be in the past or future relative to the current datetime
+        tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset
+            TODO: use of a tzinfo where offset changes based on the datetime is not yet supported
+        now_utc_offset: The value must be in the past or future relative to the current datetime with this utc offset
+        microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='datetime',
+        strict=strict,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        now_op=now_op,
+        tz_constraint=tz_constraint,
+        now_utc_offset=now_utc_offset,
+        microseconds_precision=microseconds_precision,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TimedeltaSchema(TypedDict, total=False):
+    type: Required[Literal['timedelta']]
+    strict: bool
+    le: timedelta
+    ge: timedelta
+    lt: timedelta
+    gt: timedelta
+    microseconds_precision: Literal['truncate', 'error']
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def timedelta_schema(
+    *,
+    strict: bool | None = None,
+    le: timedelta | None = None,
+    ge: timedelta | None = None,
+    lt: timedelta | None = None,
+    gt: timedelta | None = None,
+    microseconds_precision: Literal['truncate', 'error'] = 'truncate',
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> TimedeltaSchema:
+    """
+    Returns a schema that matches a timedelta value, e.g.:
+
+    ```py
+    from datetime import timedelta
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.timedelta_schema(le=timedelta(days=1), ge=timedelta(days=0))
+    v = SchemaValidator(schema)
+    assert v.validate_python(timedelta(hours=12)) == timedelta(hours=12)
+    ```
+
+    Args:
+        strict: Whether the value should be a timedelta or a value that can be converted to a timedelta
+        le: The value must be less than or equal to this timedelta
+        ge: The value must be greater than or equal to this timedelta
+        lt: The value must be strictly less than this timedelta
+        gt: The value must be strictly greater than this timedelta
+        microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='timedelta',
+        strict=strict,
+        le=le,
+        ge=ge,
+        lt=lt,
+        gt=gt,
+        microseconds_precision=microseconds_precision,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class LiteralSchema(TypedDict, total=False):
+    type: Required[Literal['literal']]
+    expected: Required[list[Any]]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def literal_schema(
+    expected: list[Any],
+    *,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> LiteralSchema:
+    """
+    Returns a schema that matches a literal value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.literal_schema(['hello', 'world'])
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello') == 'hello'
+    ```
+
+    Args:
+        expected: The value must be one of these values
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='literal', expected=expected, ref=ref, metadata=metadata, serialization=serialization)
+
+
+class EnumSchema(TypedDict, total=False):
+    type: Required[Literal['enum']]
+    cls: Required[Any]
+    members: Required[list[Any]]
+    sub_type: Literal['str', 'int', 'float']
+    missing: Callable[[Any], Any]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def enum_schema(
+    cls: Any,
+    members: list[Any],
+    *,
+    sub_type: Literal['str', 'int', 'float'] | None = None,
+    missing: Callable[[Any], Any] | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> EnumSchema:
+    """
+    Returns a schema that matches an enum value, e.g.:
+
+    ```py
+    from enum import Enum
+    from pydantic_core import SchemaValidator, core_schema
+
+    class Color(Enum):
+        RED = 1
+        GREEN = 2
+        BLUE = 3
+
+    schema = core_schema.enum_schema(Color, list(Color.__members__.values()))
+    v = SchemaValidator(schema)
+    assert v.validate_python(2) is Color.GREEN
+    ```
+
+    Args:
+        cls: The enum class
+        members: The members of the enum, generally `list(MyEnum.__members__.values())`
+        sub_type: The type of the enum, either 'str' or 'int' or None for plain enums
+        missing: A function to use when the value is not found in the enum, from `_missing_`
+        strict: Whether to use strict mode, defaults to False
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='enum',
+        cls=cls,
+        members=members,
+        sub_type=sub_type,
+        missing=missing,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class MissingSentinelSchema(TypedDict, total=False):
+    type: Required[Literal['missing-sentinel']]
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def missing_sentinel_schema(
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> MissingSentinelSchema:
+    """Returns a schema for the `MISSING` sentinel."""
+
+    return _dict_not_none(
+        type='missing-sentinel',
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+# must match input/parse_json.rs::JsonType::try_from
+JsonType = Literal['null', 'bool', 'int', 'float', 'str', 'list', 'dict']
+
+
+class IsInstanceSchema(TypedDict, total=False):
+    type: Required[Literal['is-instance']]
+    cls: Required[Any]
+    cls_repr: str
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def is_instance_schema(
+    cls: Any,
+    *,
+    cls_repr: str | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> IsInstanceSchema:
+    """
+    Returns a schema that checks if a value is an instance of a class, equivalent to python's `isinstance` method, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    class A:
+        pass
+
+    schema = core_schema.is_instance_schema(cls=A)
+    v = SchemaValidator(schema)
+    v.validate_python(A())
+    ```
+
+    Args:
+        cls: The value must be an instance of this class
+        cls_repr: If provided this string is used in the validator name instead of `repr(cls)`
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='is-instance', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+class IsSubclassSchema(TypedDict, total=False):
+    type: Required[Literal['is-subclass']]
+    cls: Required[type[Any]]
+    cls_repr: str
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def is_subclass_schema(
+    cls: type[Any],
+    *,
+    cls_repr: str | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> IsInstanceSchema:
+    """
+    Returns a schema that checks if a value is a subtype of a class, equivalent to python's `issubclass` method, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    class A:
+        pass
+
+    class B(A):
+        pass
+
+    schema = core_schema.is_subclass_schema(cls=A)
+    v = SchemaValidator(schema)
+    v.validate_python(B)
+    ```
+
+    Args:
+        cls: The value must be a subclass of this class
+        cls_repr: If provided this string is used in the validator name instead of `repr(cls)`
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='is-subclass', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+class CallableSchema(TypedDict, total=False):
+    type: Required[Literal['callable']]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def callable_schema(
+    *, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None
+) -> CallableSchema:
+    """
+    Returns a schema that checks if a value is callable, equivalent to python's `callable` method, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.callable_schema()
+    v = SchemaValidator(schema)
+    v.validate_python(min)
+    ```
+
+    Args:
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='callable', ref=ref, metadata=metadata, serialization=serialization)
+
+
+class UuidSchema(TypedDict, total=False):
+    type: Required[Literal['uuid']]
+    version: Literal[1, 3, 4, 5, 7]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def uuid_schema(
+    *,
+    version: Literal[1, 3, 4, 5, 6, 7, 8] | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> UuidSchema:
+    return _dict_not_none(
+        type='uuid', version=version, strict=strict, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+class IncExSeqSerSchema(TypedDict, total=False):
+    type: Required[Literal['include-exclude-sequence']]
+    include: set[int]
+    exclude: set[int]
+
+
+def filter_seq_schema(*, include: set[int] | None = None, exclude: set[int] | None = None) -> IncExSeqSerSchema:
+    return _dict_not_none(type='include-exclude-sequence', include=include, exclude=exclude)
+
+
+IncExSeqOrElseSerSchema = Union[IncExSeqSerSchema, SerSchema]
+
+
+class ListSchema(TypedDict, total=False):
+    type: Required[Literal['list']]
+    items_schema: CoreSchema
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: IncExSeqOrElseSerSchema
+
+
+def list_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> ListSchema:
+    """
+    Returns a schema that matches a list value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.list_schema(core_schema.int_schema(), min_length=0, max_length=10)
+    v = SchemaValidator(schema)
+    assert v.validate_python(['4']) == [4]
+    ```
+
+    Args:
+        items_schema: The value must be a list of items that match this schema
+        min_length: The value must be a list with at least this many items
+        max_length: The value must be a list with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: The value must be a list with exactly this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='list',
+        items_schema=items_schema,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+# @deprecated('tuple_positional_schema is deprecated. Use pydantic_core.core_schema.tuple_schema instead.')
+def tuple_positional_schema(
+    items_schema: list[CoreSchema],
+    *,
+    extras_schema: CoreSchema | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> TupleSchema:
+    """
+    Returns a schema that matches a tuple of schemas, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.tuple_positional_schema(
+        [core_schema.int_schema(), core_schema.str_schema()]
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python((1, 'hello')) == (1, 'hello')
+    ```
+
+    Args:
+        items_schema: The value must be a tuple with items that match these schemas
+        extras_schema: The value must be a tuple with items that match this schema
+            This was inspired by JSON schema's `prefixItems` and `items` fields.
+            In python's `typing.Tuple`, you can't specify a type for "extra" items -- they must all be the same type
+            if the length is variable. So this field won't be set from a `typing.Tuple` annotation on a pydantic model.
+        strict: The value must be a tuple with exactly this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if extras_schema is not None:
+        variadic_item_index = len(items_schema)
+        items_schema = items_schema + [extras_schema]
+    else:
+        variadic_item_index = None
+    return tuple_schema(
+        items_schema=items_schema,
+        variadic_item_index=variadic_item_index,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+# @deprecated('tuple_variable_schema is deprecated. Use pydantic_core.core_schema.tuple_schema instead.')
+def tuple_variable_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> TupleSchema:
+    """
+    Returns a schema that matches a tuple of a given schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.tuple_variable_schema(
+        items_schema=core_schema.int_schema(), min_length=0, max_length=10
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python(('1', 2, 3)) == (1, 2, 3)
+    ```
+
+    Args:
+        items_schema: The value must be a tuple with items that match this schema
+        min_length: The value must be a tuple with at least this many items
+        max_length: The value must be a tuple with at most this many items
+        strict: The value must be a tuple with exactly this many items
+        ref: Optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return tuple_schema(
+        items_schema=[items_schema or any_schema()],
+        variadic_item_index=0,
+        min_length=min_length,
+        max_length=max_length,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TupleSchema(TypedDict, total=False):
+    type: Required[Literal['tuple']]
+    items_schema: Required[list[CoreSchema]]
+    variadic_item_index: int
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: IncExSeqOrElseSerSchema
+
+
+def tuple_schema(
+    items_schema: list[CoreSchema],
+    *,
+    variadic_item_index: int | None = None,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> TupleSchema:
+    """
+    Returns a schema that matches a tuple of schemas, with an optional variadic item, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.tuple_schema(
+        [core_schema.int_schema(), core_schema.str_schema(), core_schema.float_schema()],
+        variadic_item_index=1,
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python((1, 'hello', 'world', 1.5)) == (1, 'hello', 'world', 1.5)
+    ```
+
+    Args:
+        items_schema: The value must be a tuple with items that match these schemas
+        variadic_item_index: The index of the schema in `items_schema` to be treated as variadic (following PEP 646)
+        min_length: The value must be a tuple with at least this many items
+        max_length: The value must be a tuple with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: The value must be a tuple with exactly this many items
+        ref: Optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='tuple',
+        items_schema=items_schema,
+        variadic_item_index=variadic_item_index,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class SetSchema(TypedDict, total=False):
+    type: Required[Literal['set']]
+    items_schema: CoreSchema
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def set_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> SetSchema:
+    """
+    Returns a schema that matches a set of a given schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.set_schema(
+        items_schema=core_schema.int_schema(), min_length=0, max_length=10
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python({1, '2', 3}) == {1, 2, 3}
+    ```
+
+    Args:
+        items_schema: The value must be a set with items that match this schema
+        min_length: The value must be a set with at least this many items
+        max_length: The value must be a set with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: The value must be a set with exactly this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='set',
+        items_schema=items_schema,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class FrozenSetSchema(TypedDict, total=False):
+    type: Required[Literal['frozenset']]
+    items_schema: CoreSchema
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def frozenset_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> FrozenSetSchema:
+    """
+    Returns a schema that matches a frozenset of a given schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.frozenset_schema(
+        items_schema=core_schema.int_schema(), min_length=0, max_length=10
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python(frozenset(range(3))) == frozenset({0, 1, 2})
+    ```
+
+    Args:
+        items_schema: The value must be a frozenset with items that match this schema
+        min_length: The value must be a frozenset with at least this many items
+        max_length: The value must be a frozenset with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: The value must be a frozenset with exactly this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='frozenset',
+        items_schema=items_schema,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class GeneratorSchema(TypedDict, total=False):
+    type: Required[Literal['generator']]
+    items_schema: CoreSchema
+    min_length: int
+    max_length: int
+    ref: str
+    metadata: dict[str, Any]
+    serialization: IncExSeqOrElseSerSchema
+
+
+def generator_schema(
+    items_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: IncExSeqOrElseSerSchema | None = None,
+) -> GeneratorSchema:
+    """
+    Returns a schema that matches a generator value, e.g.:
+
+    ```py
+    from typing import Iterator
+    from pydantic_core import SchemaValidator, core_schema
+
+    def gen() -> Iterator[int]:
+        yield 1
+
+    schema = core_schema.generator_schema(items_schema=core_schema.int_schema())
+    v = SchemaValidator(schema)
+    v.validate_python(gen())
+    ```
+
+    Unlike other types, validated generators do not raise ValidationErrors eagerly,
+    but instead will raise a ValidationError when a violating value is actually read from the generator.
+    This is to ensure that "validated" generators retain the benefit of lazy evaluation.
+
+    Args:
+        items_schema: The value must be a generator with items that match this schema
+        min_length: The value must be a generator that yields at least this many items
+        max_length: The value must be a generator that yields at most this many items
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='generator',
+        items_schema=items_schema,
+        min_length=min_length,
+        max_length=max_length,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+IncExDict = set[Union[int, str]]
+
+
+class IncExDictSerSchema(TypedDict, total=False):
+    type: Required[Literal['include-exclude-dict']]
+    include: IncExDict
+    exclude: IncExDict
+
+
+def filter_dict_schema(*, include: IncExDict | None = None, exclude: IncExDict | None = None) -> IncExDictSerSchema:
+    return _dict_not_none(type='include-exclude-dict', include=include, exclude=exclude)
+
+
+IncExDictOrElseSerSchema = Union[IncExDictSerSchema, SerSchema]
+
+
+class DictSchema(TypedDict, total=False):
+    type: Required[Literal['dict']]
+    keys_schema: CoreSchema  # default: AnySchema
+    values_schema: CoreSchema  # default: AnySchema
+    min_length: int
+    max_length: int
+    fail_fast: bool
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: IncExDictOrElseSerSchema
+
+
+def dict_schema(
+    keys_schema: CoreSchema | None = None,
+    values_schema: CoreSchema | None = None,
+    *,
+    min_length: int | None = None,
+    max_length: int | None = None,
+    fail_fast: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DictSchema:
+    """
+    Returns a schema that matches a dict value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.dict_schema(
+        keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema()
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': '1', 'b': 2}) == {'a': 1, 'b': 2}
+    ```
+
+    Args:
+        keys_schema: The value must be a dict with keys that match this schema
+        values_schema: The value must be a dict with values that match this schema
+        min_length: The value must be a dict with at least this many items
+        max_length: The value must be a dict with at most this many items
+        fail_fast: Stop validation on the first error
+        strict: Whether the keys and values should be validated with strict mode
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='dict',
+        keys_schema=keys_schema,
+        values_schema=values_schema,
+        min_length=min_length,
+        max_length=max_length,
+        fail_fast=fail_fast,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+# (input_value: Any, /) -> Any
+NoInfoValidatorFunction = Callable[[Any], Any]
+
+
+class NoInfoValidatorFunctionSchema(TypedDict):
+    type: Literal['no-info']
+    function: NoInfoValidatorFunction
+
+
+# (input_value: Any, info: ValidationInfo, /) -> Any
+WithInfoValidatorFunction = Callable[[Any, ValidationInfo[Any]], Any]
+
+
+class WithInfoValidatorFunctionSchema(TypedDict, total=False):
+    type: Required[Literal['with-info']]
+    function: Required[WithInfoValidatorFunction]
+    field_name: str  # deprecated
+
+
+ValidationFunction = Union[NoInfoValidatorFunctionSchema, WithInfoValidatorFunctionSchema]
+
+
+class _ValidatorFunctionSchema(TypedDict, total=False):
+    function: Required[ValidationFunction]
+    schema: Required[CoreSchema]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+class BeforeValidatorFunctionSchema(_ValidatorFunctionSchema, total=False):
+    type: Required[Literal['function-before']]
+    json_schema_input_schema: CoreSchema
+
+
+def no_info_before_validator_function(
+    function: NoInfoValidatorFunction,
+    schema: CoreSchema,
+    *,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> BeforeValidatorFunctionSchema:
+    """
+    Returns a schema that calls a validator function before validating, no `info` argument is provided, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: bytes) -> str:
+        return v.decode() + 'world'
+
+    func_schema = core_schema.no_info_before_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
+
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
+    ```
+
+    Args:
+        function: The validator function to call
+        schema: The schema to validate the output of the validator function
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='function-before',
+        function={'type': 'no-info', 'function': function},
+        schema=schema,
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+def with_info_before_validator_function(
+    function: WithInfoValidatorFunction,
+    schema: CoreSchema,
+    *,
+    field_name: str | None = None,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> BeforeValidatorFunctionSchema:
+    """
+    Returns a schema that calls a validator function before validation, the function is called with
+    an `info` argument, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: bytes, info: core_schema.ValidationInfo) -> str:
+        assert info.data is not None
+        assert info.field_name is not None
+        return v.decode() + 'world'
+
+    func_schema = core_schema.with_info_before_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
+
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
+    ```
+
+    Args:
+        function: The validator function to call
+        field_name: The name of the field this validator is applied to, if any (deprecated)
+        schema: The schema to validate the output of the validator function
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if field_name is not None:
+        warnings.warn(
+            'The `field_name` argument on `with_info_before_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.',
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    return _dict_not_none(
+        type='function-before',
+        function=_dict_not_none(type='with-info', function=function, field_name=field_name),
+        schema=schema,
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class AfterValidatorFunctionSchema(_ValidatorFunctionSchema, total=False):
+    type: Required[Literal['function-after']]
+
+
+def no_info_after_validator_function(
+    function: NoInfoValidatorFunction,
+    schema: CoreSchema,
+    *,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> AfterValidatorFunctionSchema:
+    """
+    Returns a schema that calls a validator function after validating, no `info` argument is provided, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str) -> str:
+        return v + 'world'
+
+    func_schema = core_schema.no_info_after_validator_function(fn, core_schema.str_schema())
+    schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
+
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
+    ```
+
+    Args:
+        function: The validator function to call after the schema is validated
+        schema: The schema to validate before the validator function
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='function-after',
+        function={'type': 'no-info', 'function': function},
+        schema=schema,
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+def with_info_after_validator_function(
+    function: WithInfoValidatorFunction,
+    schema: CoreSchema,
+    *,
+    field_name: str | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> AfterValidatorFunctionSchema:
+    """
+    Returns a schema that calls a validator function after validation, the function is called with
+    an `info` argument, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str, info: core_schema.ValidationInfo) -> str:
+        assert info.data is not None
+        assert info.field_name is not None
+        return v + 'world'
+
+    func_schema = core_schema.with_info_after_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)})
+
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'}
+    ```
+
+    Args:
+        function: The validator function to call after the schema is validated
+        schema: The schema to validate before the validator function
+        field_name: The name of the field this validator is applied to, if any (deprecated)
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if field_name is not None:
+        warnings.warn(
+            'The `field_name` argument on `with_info_after_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.',
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    return _dict_not_none(
+        type='function-after',
+        function=_dict_not_none(type='with-info', function=function, field_name=field_name),
+        schema=schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ValidatorFunctionWrapHandler(Protocol):
+    def __call__(self, input_value: Any, outer_location: str | int | None = None, /) -> Any:  # pragma: no cover
+        ...
+
+
+# (input_value: Any, validator: ValidatorFunctionWrapHandler, /) -> Any
+NoInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler], Any]
+
+
+class NoInfoWrapValidatorFunctionSchema(TypedDict):
+    type: Literal['no-info']
+    function: NoInfoWrapValidatorFunction
+
+
+# (input_value: Any, validator: ValidatorFunctionWrapHandler, info: ValidationInfo, /) -> Any
+WithInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler, ValidationInfo[Any]], Any]
+
+
+class WithInfoWrapValidatorFunctionSchema(TypedDict, total=False):
+    type: Required[Literal['with-info']]
+    function: Required[WithInfoWrapValidatorFunction]
+    field_name: str  # deprecated
+
+
+WrapValidatorFunction = Union[NoInfoWrapValidatorFunctionSchema, WithInfoWrapValidatorFunctionSchema]
+
+
+class WrapValidatorFunctionSchema(TypedDict, total=False):
+    type: Required[Literal['function-wrap']]
+    function: Required[WrapValidatorFunction]
+    schema: Required[CoreSchema]
+    ref: str
+    json_schema_input_schema: CoreSchema
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def no_info_wrap_validator_function(
+    function: NoInfoWrapValidatorFunction,
+    schema: CoreSchema,
+    *,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> WrapValidatorFunctionSchema:
+    """
+    Returns a schema which calls a function with a `validator` callable argument which can
+    optionally be used to call inner validation with the function logic, this is much like the
+    "onion" implementation of middleware in many popular web frameworks, no `info` argument is passed, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(
+        v: str,
+        validator: core_schema.ValidatorFunctionWrapHandler,
+    ) -> str:
+        return validator(input_value=v) + 'world'
+
+    schema = core_schema.no_info_wrap_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello ') == 'hello world'
+    ```
+
+    Args:
+        function: The validator function to call
+        schema: The schema to validate the output of the validator function
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='function-wrap',
+        function={'type': 'no-info', 'function': function},
+        schema=schema,
+        json_schema_input_schema=json_schema_input_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+def with_info_wrap_validator_function(
+    function: WithInfoWrapValidatorFunction,
+    schema: CoreSchema,
+    *,
+    field_name: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> WrapValidatorFunctionSchema:
+    """
+    Returns a schema which calls a function with a `validator` callable argument which can
+    optionally be used to call inner validation with the function logic, this is much like the
+    "onion" implementation of middleware in many popular web frameworks, an `info` argument is also passed, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(
+        v: str,
+        validator: core_schema.ValidatorFunctionWrapHandler,
+        info: core_schema.ValidationInfo,
+    ) -> str:
+        return validator(input_value=v) + 'world'
+
+    schema = core_schema.with_info_wrap_validator_function(
+        function=fn, schema=core_schema.str_schema()
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello ') == 'hello world'
+    ```
+
+    Args:
+        function: The validator function to call
+        schema: The schema to validate the output of the validator function
+        field_name: The name of the field this validator is applied to, if any (deprecated)
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if field_name is not None:
+        warnings.warn(
+            'The `field_name` argument on `with_info_wrap_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.',
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    return _dict_not_none(
+        type='function-wrap',
+        function=_dict_not_none(type='with-info', function=function, field_name=field_name),
+        schema=schema,
+        json_schema_input_schema=json_schema_input_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class PlainValidatorFunctionSchema(TypedDict, total=False):
+    type: Required[Literal['function-plain']]
+    function: Required[ValidationFunction]
+    ref: str
+    json_schema_input_schema: CoreSchema
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def no_info_plain_validator_function(
+    function: NoInfoValidatorFunction,
+    *,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> PlainValidatorFunctionSchema:
+    """
+    Returns a schema that uses the provided function for validation, no `info` argument is passed, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str) -> str:
+        assert 'hello' in v
+        return v + 'world'
+
+    schema = core_schema.no_info_plain_validator_function(function=fn)
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello ') == 'hello world'
+    ```
+
+    Args:
+        function: The validator function to call
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='function-plain',
+        function={'type': 'no-info', 'function': function},
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+def with_info_plain_validator_function(
+    function: WithInfoValidatorFunction,
+    *,
+    field_name: str | None = None,
+    ref: str | None = None,
+    json_schema_input_schema: CoreSchema | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> PlainValidatorFunctionSchema:
+    """
+    Returns a schema that uses the provided function for validation, an `info` argument is passed, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str, info: core_schema.ValidationInfo) -> str:
+        assert 'hello' in v
+        return v + 'world'
+
+    schema = core_schema.with_info_plain_validator_function(function=fn)
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello ') == 'hello world'
+    ```
+
+    Args:
+        function: The validator function to call
+        field_name: The name of the field this validator is applied to, if any (deprecated)
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        json_schema_input_schema: The core schema to be used to generate the corresponding JSON Schema input type
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    if field_name is not None:
+        warnings.warn(
+            'The `field_name` argument on `with_info_plain_validator_function` is deprecated, it will be passed to the function through `ValidationState` instead.',
+            DeprecationWarning,
+            stacklevel=2,
+        )
+
+    return _dict_not_none(
+        type='function-plain',
+        function=_dict_not_none(type='with-info', function=function, field_name=field_name),
+        ref=ref,
+        json_schema_input_schema=json_schema_input_schema,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class WithDefaultSchema(TypedDict, total=False):
+    type: Required[Literal['default']]
+    schema: Required[CoreSchema]
+    default: Any
+    default_factory: Union[Callable[[], Any], Callable[[dict[str, Any]], Any]]
+    default_factory_takes_data: bool
+    on_error: Literal['raise', 'omit', 'default']  # default: 'raise'
+    validate_default: bool  # default: False
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def with_default_schema(
+    schema: CoreSchema,
+    *,
+    default: Any = PydanticUndefined,
+    default_factory: Union[Callable[[], Any], Callable[[dict[str, Any]], Any], None] = None,
+    default_factory_takes_data: bool | None = None,
+    on_error: Literal['raise', 'omit', 'default'] | None = None,
+    validate_default: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> WithDefaultSchema:
+    """
+    Returns a schema that adds a default value to the given schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.with_default_schema(core_schema.str_schema(), default='hello')
+    wrapper_schema = core_schema.typed_dict_schema(
+        {'a': core_schema.typed_dict_field(schema)}
+    )
+    v = SchemaValidator(wrapper_schema)
+    assert v.validate_python({}) == v.validate_python({'a': 'hello'})
+    ```
+
+    Args:
+        schema: The schema to add a default value to
+        default: The default value to use
+        default_factory: A callable that returns the default value to use
+        default_factory_takes_data: Whether the default factory takes a validated data argument
+        on_error: What to do if the schema validation fails. One of 'raise', 'omit', 'default'
+        validate_default: Whether the default value should be validated
+        strict: Whether the underlying schema should be validated with strict mode
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    s = _dict_not_none(
+        type='default',
+        schema=schema,
+        default_factory=default_factory,
+        default_factory_takes_data=default_factory_takes_data,
+        on_error=on_error,
+        validate_default=validate_default,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+    if default is not PydanticUndefined:
+        s['default'] = default
+    return s
+
+
+class NullableSchema(TypedDict, total=False):
+    type: Required[Literal['nullable']]
+    schema: Required[CoreSchema]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def nullable_schema(
+    schema: CoreSchema,
+    *,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> NullableSchema:
+    """
+    Returns a schema that matches a nullable value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.nullable_schema(core_schema.str_schema())
+    v = SchemaValidator(schema)
+    assert v.validate_python(None) is None
+    ```
+
+    Args:
+        schema: The schema to wrap
+        strict: Whether the underlying schema should be validated with strict mode
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='nullable', schema=schema, strict=strict, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+class UnionSchema(TypedDict, total=False):
+    type: Required[Literal['union']]
+    choices: Required[list[Union[CoreSchema, tuple[CoreSchema, str]]]]
+    # default true, whether to automatically collapse unions with one element to the inner validator
+    auto_collapse: bool
+    custom_error_type: str
+    custom_error_message: str
+    custom_error_context: dict[str, Union[str, int, float]]
+    mode: Literal['smart', 'left_to_right']  # default: 'smart'
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def union_schema(
+    choices: list[CoreSchema | tuple[CoreSchema, str]],
+    *,
+    auto_collapse: bool | None = None,
+    custom_error_type: str | None = None,
+    custom_error_message: str | None = None,
+    custom_error_context: dict[str, str | int] | None = None,
+    mode: Literal['smart', 'left_to_right'] | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> UnionSchema:
+    """
+    Returns a schema that matches a union value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()])
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello') == 'hello'
+    assert v.validate_python(1) == 1
+    ```
+
+    Args:
+        choices: The schemas to match. If a tuple, the second item is used as the label for the case.
+        auto_collapse: whether to automatically collapse unions with one element to the inner validator, default true
+        custom_error_type: The custom error type to use if the validation fails
+        custom_error_message: The custom error message to use if the validation fails
+        custom_error_context: The custom error context to use if the validation fails
+        mode: How to select which choice to return
+            * `smart` (default) will try to return the choice which is the closest match to the input value
+            * `left_to_right` will return the first choice in `choices` which succeeds validation
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='union',
+        choices=choices,
+        auto_collapse=auto_collapse,
+        custom_error_type=custom_error_type,
+        custom_error_message=custom_error_message,
+        custom_error_context=custom_error_context,
+        mode=mode,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TaggedUnionSchema(TypedDict, total=False):
+    type: Required[Literal['tagged-union']]
+    choices: Required[dict[Hashable, CoreSchema]]
+    discriminator: Required[Union[str, list[Union[str, int]], list[list[Union[str, int]]], Callable[[Any], Hashable]]]
+    custom_error_type: str
+    custom_error_message: str
+    custom_error_context: dict[str, Union[str, int, float]]
+    strict: bool
+    from_attributes: bool  # default: True
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def tagged_union_schema(
+    choices: dict[Any, CoreSchema],
+    discriminator: str | list[str | int] | list[list[str | int]] | Callable[[Any], Any],
+    *,
+    custom_error_type: str | None = None,
+    custom_error_message: str | None = None,
+    custom_error_context: dict[str, int | str | float] | None = None,
+    strict: bool | None = None,
+    from_attributes: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> TaggedUnionSchema:
+    """
+    Returns a schema that matches a tagged union value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    apple_schema = core_schema.typed_dict_schema(
+        {
+            'foo': core_schema.typed_dict_field(core_schema.str_schema()),
+            'bar': core_schema.typed_dict_field(core_schema.int_schema()),
+        }
+    )
+    banana_schema = core_schema.typed_dict_schema(
+        {
+            'foo': core_schema.typed_dict_field(core_schema.str_schema()),
+            'spam': core_schema.typed_dict_field(
+                core_schema.list_schema(items_schema=core_schema.int_schema())
+            ),
+        }
+    )
+    schema = core_schema.tagged_union_schema(
+        choices={
+            'apple': apple_schema,
+            'banana': banana_schema,
+        },
+        discriminator='foo',
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python({'foo': 'apple', 'bar': '123'}) == {'foo': 'apple', 'bar': 123}
+    assert v.validate_python({'foo': 'banana', 'spam': [1, 2, 3]}) == {
+        'foo': 'banana',
+        'spam': [1, 2, 3],
+    }
+    ```
+
+    Args:
+        choices: The schemas to match
+            When retrieving a schema from `choices` using the discriminator value, if the value is a str,
+            it should be fed back into the `choices` map until a schema is obtained
+            (This approach is to prevent multiple ownership of a single schema in Rust)
+        discriminator: The discriminator to use to determine the schema to use
+            * If `discriminator` is a str, it is the name of the attribute to use as the discriminator
+            * If `discriminator` is a list of int/str, it should be used as a "path" to access the discriminator
+            * If `discriminator` is a list of lists, each inner list is a path, and the first path that exists is used
+            * If `discriminator` is a callable, it should return the discriminator when called on the value to validate;
+              the callable can return `None` to indicate that there is no matching discriminator present on the input
+        custom_error_type: The custom error type to use if the validation fails
+        custom_error_message: The custom error message to use if the validation fails
+        custom_error_context: The custom error context to use if the validation fails
+        strict: Whether the underlying schemas should be validated with strict mode
+        from_attributes: Whether to use the attributes of the object to retrieve the discriminator value
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='tagged-union',
+        choices=choices,
+        discriminator=discriminator,
+        custom_error_type=custom_error_type,
+        custom_error_message=custom_error_message,
+        custom_error_context=custom_error_context,
+        strict=strict,
+        from_attributes=from_attributes,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ChainSchema(TypedDict, total=False):
+    type: Required[Literal['chain']]
+    steps: Required[list[CoreSchema]]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def chain_schema(
+    steps: list[CoreSchema],
+    *,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ChainSchema:
+    """
+    Returns a schema that chains the provided validation schemas, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str, info: core_schema.ValidationInfo) -> str:
+        assert 'hello' in v
+        return v + ' world'
+
+    fn_schema = core_schema.with_info_plain_validator_function(function=fn)
+    schema = core_schema.chain_schema(
+        [fn_schema, fn_schema, fn_schema, core_schema.str_schema()]
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python('hello') == 'hello world world world'
+    ```
+
+    Args:
+        steps: The schemas to chain
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='chain', steps=steps, ref=ref, metadata=metadata, serialization=serialization)
+
+
+class LaxOrStrictSchema(TypedDict, total=False):
+    type: Required[Literal['lax-or-strict']]
+    lax_schema: Required[CoreSchema]
+    strict_schema: Required[CoreSchema]
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def lax_or_strict_schema(
+    lax_schema: CoreSchema,
+    strict_schema: CoreSchema,
+    *,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> LaxOrStrictSchema:
+    """
+    Returns a schema that uses the lax or strict schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    def fn(v: str, info: core_schema.ValidationInfo) -> str:
+        assert 'hello' in v
+        return v + ' world'
+
+    lax_schema = core_schema.int_schema(strict=False)
+    strict_schema = core_schema.int_schema(strict=True)
+
+    schema = core_schema.lax_or_strict_schema(
+        lax_schema=lax_schema, strict_schema=strict_schema, strict=True
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python(123) == 123
+
+    schema = core_schema.lax_or_strict_schema(
+        lax_schema=lax_schema, strict_schema=strict_schema, strict=False
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python('123') == 123
+    ```
+
+    Args:
+        lax_schema: The lax schema to use
+        strict_schema: The strict schema to use
+        strict: Whether the strict schema should be used
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='lax-or-strict',
+        lax_schema=lax_schema,
+        strict_schema=strict_schema,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class JsonOrPythonSchema(TypedDict, total=False):
+    type: Required[Literal['json-or-python']]
+    json_schema: Required[CoreSchema]
+    python_schema: Required[CoreSchema]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def json_or_python_schema(
+    json_schema: CoreSchema,
+    python_schema: CoreSchema,
+    *,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> JsonOrPythonSchema:
+    """
+    Returns a schema that uses the Json or Python schema depending on the input:
+
+    ```py
+    from pydantic_core import SchemaValidator, ValidationError, core_schema
+
+    v = SchemaValidator(
+        core_schema.json_or_python_schema(
+            json_schema=core_schema.int_schema(),
+            python_schema=core_schema.int_schema(strict=True),
+        )
+    )
+
+    assert v.validate_json('"123"') == 123
+
+    try:
+        v.validate_python('123')
+    except ValidationError:
+        pass
+    else:
+        raise AssertionError('Validation should have failed')
+    ```
+
+    Args:
+        json_schema: The schema to use for Json inputs
+        python_schema: The schema to use for Python inputs
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='json-or-python',
+        json_schema=json_schema,
+        python_schema=python_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class TypedDictField(TypedDict, total=False):
+    type: Required[Literal['typed-dict-field']]
+    schema: Required[CoreSchema]
+    required: bool
+    validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+    serialization_alias: str
+    serialization_exclude: bool  # default: False
+    metadata: dict[str, Any]
+    serialization_exclude_if: Callable[[Any], bool]  # default None
+
+
+def typed_dict_field(
+    schema: CoreSchema,
+    *,
+    required: bool | None = None,
+    validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
+    serialization_alias: str | None = None,
+    serialization_exclude: bool | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization_exclude_if: Callable[[Any], bool] | None = None,
+) -> TypedDictField:
+    """
+    Returns a schema that matches a typed dict field, e.g.:
+
+    ```py
+    from pydantic_core import core_schema
+
+    field = core_schema.typed_dict_field(schema=core_schema.int_schema(), required=True)
+    ```
+
+    Args:
+        schema: The schema to use for the field
+        required: Whether the field is required, otherwise uses the value from `total` on the typed dict
+        validation_alias: The alias(es) to use to find the field in the validation data
+        serialization_alias: The alias to use as a key when serializing
+        serialization_exclude: Whether to exclude the field when serializing
+        serialization_exclude_if: A callable that determines whether to exclude the field when serializing based on its value.
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+    """
+    return _dict_not_none(
+        type='typed-dict-field',
+        schema=schema,
+        required=required,
+        validation_alias=validation_alias,
+        serialization_alias=serialization_alias,
+        serialization_exclude=serialization_exclude,
+        serialization_exclude_if=serialization_exclude_if,
+        metadata=metadata,
+    )
+
+
+class TypedDictSchema(TypedDict, total=False):
+    type: Required[Literal['typed-dict']]
+    fields: Required[dict[str, TypedDictField]]
+    cls: type[Any]
+    cls_name: str
+    computed_fields: list[ComputedField]
+    strict: bool
+    extras_schema: CoreSchema
+    # all these values can be set via config, equivalent fields have `typed_dict_` prefix
+    extra_behavior: ExtraBehavior
+    total: bool  # default: True
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+    config: CoreConfig
+
+
+def typed_dict_schema(
+    fields: dict[str, TypedDictField],
+    *,
+    cls: type[Any] | None = None,
+    cls_name: str | None = None,
+    computed_fields: list[ComputedField] | None = None,
+    strict: bool | None = None,
+    extras_schema: CoreSchema | None = None,
+    extra_behavior: ExtraBehavior | None = None,
+    total: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+    config: CoreConfig | None = None,
+) -> TypedDictSchema:
+    """
+    Returns a schema that matches a typed dict, e.g.:
+
+    ```py
+    from typing_extensions import TypedDict
+
+    from pydantic_core import SchemaValidator, core_schema
+
+    class MyTypedDict(TypedDict):
+        a: str
+
+    wrapper_schema = core_schema.typed_dict_schema(
+        {'a': core_schema.typed_dict_field(core_schema.str_schema())}, cls=MyTypedDict
+    )
+    v = SchemaValidator(wrapper_schema)
+    assert v.validate_python({'a': 'hello'}) == {'a': 'hello'}
+    ```
+
+    Args:
+        fields: The fields to use for the typed dict
+        cls: The class to use for the typed dict
+        cls_name: The name to use in error locations. Falls back to `cls.__name__`, or the validator name if no class
+            is provided.
+        computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model
+        strict: Whether the typed dict is strict
+        extras_schema: The extra validator to use for the typed dict
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        extra_behavior: The extra behavior to use for the typed dict
+        total: Whether the typed dict is total, otherwise uses `typed_dict_total` from config
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='typed-dict',
+        fields=fields,
+        cls=cls,
+        cls_name=cls_name,
+        computed_fields=computed_fields,
+        strict=strict,
+        extras_schema=extras_schema,
+        extra_behavior=extra_behavior,
+        total=total,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+        config=config,
+    )
+
+
+class ModelField(TypedDict, total=False):
+    type: Required[Literal['model-field']]
+    schema: Required[CoreSchema]
+    validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+    serialization_alias: str
+    serialization_exclude: bool  # default: False
+    serialization_exclude_if: Callable[[Any], bool]  # default: None
+    frozen: bool
+    metadata: dict[str, Any]
+
+
+def model_field(
+    schema: CoreSchema,
+    *,
+    validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
+    serialization_alias: str | None = None,
+    serialization_exclude: bool | None = None,
+    serialization_exclude_if: Callable[[Any], bool] | None = None,
+    frozen: bool | None = None,
+    metadata: dict[str, Any] | None = None,
+) -> ModelField:
+    """
+    Returns a schema for a model field, e.g.:
+
+    ```py
+    from pydantic_core import core_schema
+
+    field = core_schema.model_field(schema=core_schema.int_schema())
+    ```
+
+    Args:
+        schema: The schema to use for the field
+        validation_alias: The alias(es) to use to find the field in the validation data
+        serialization_alias: The alias to use as a key when serializing
+        serialization_exclude: Whether to exclude the field when serializing
+        serialization_exclude_if: A Callable that determines whether to exclude a field during serialization based on its value.
+        frozen: Whether the field is frozen
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+    """
+    return _dict_not_none(
+        type='model-field',
+        schema=schema,
+        validation_alias=validation_alias,
+        serialization_alias=serialization_alias,
+        serialization_exclude=serialization_exclude,
+        serialization_exclude_if=serialization_exclude_if,
+        frozen=frozen,
+        metadata=metadata,
+    )
+
+
+class ModelFieldsSchema(TypedDict, total=False):
+    type: Required[Literal['model-fields']]
+    fields: Required[dict[str, ModelField]]
+    model_name: str
+    computed_fields: list[ComputedField]
+    strict: bool
+    extras_schema: CoreSchema
+    extras_keys_schema: CoreSchema
+    extra_behavior: ExtraBehavior
+    from_attributes: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def model_fields_schema(
+    fields: dict[str, ModelField],
+    *,
+    model_name: str | None = None,
+    computed_fields: list[ComputedField] | None = None,
+    strict: bool | None = None,
+    extras_schema: CoreSchema | None = None,
+    extras_keys_schema: CoreSchema | None = None,
+    extra_behavior: ExtraBehavior | None = None,
+    from_attributes: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ModelFieldsSchema:
+    """
+    Returns a schema that matches the fields of a Pydantic model, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    wrapper_schema = core_schema.model_fields_schema(
+        {'a': core_schema.model_field(core_schema.str_schema())}
+    )
+    v = SchemaValidator(wrapper_schema)
+    print(v.validate_python({'a': 'hello'}))
+    #> ({'a': 'hello'}, None, {'a'})
+    ```
+
+    Args:
+        fields: The fields of the model
+        model_name: The name of the model, used for error messages, defaults to "Model"
+        computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model
+        strict: Whether the model is strict
+        extras_schema: The schema to use when validating extra input data
+        extras_keys_schema: The schema to use when validating the keys of extra input data
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        extra_behavior: The extra behavior to use for the model fields
+        from_attributes: Whether the model fields should be populated from attributes
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='model-fields',
+        fields=fields,
+        model_name=model_name,
+        computed_fields=computed_fields,
+        strict=strict,
+        extras_schema=extras_schema,
+        extras_keys_schema=extras_keys_schema,
+        extra_behavior=extra_behavior,
+        from_attributes=from_attributes,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ModelSchema(TypedDict, total=False):
+    type: Required[Literal['model']]
+    cls: Required[type[Any]]
+    generic_origin: type[Any]
+    schema: Required[CoreSchema]
+    custom_init: bool
+    root_model: bool
+    post_init: str
+    revalidate_instances: Literal['always', 'never', 'subclass-instances']  # default: 'never'
+    strict: bool
+    frozen: bool
+    extra_behavior: ExtraBehavior
+    config: CoreConfig
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def model_schema(
+    cls: type[Any],
+    schema: CoreSchema,
+    *,
+    generic_origin: type[Any] | None = None,
+    custom_init: bool | None = None,
+    root_model: bool | None = None,
+    post_init: str | None = None,
+    revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
+    strict: bool | None = None,
+    frozen: bool | None = None,
+    extra_behavior: ExtraBehavior | None = None,
+    config: CoreConfig | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ModelSchema:
+    """
+    A model schema generally contains a typed-dict schema.
+    It will run the typed dict validator, then create a new class
+    and set the dict and fields set returned from the typed dict validator
+    to `__dict__` and `__pydantic_fields_set__` respectively.
+
+    Example:
+
+    ```py
+    from pydantic_core import CoreConfig, SchemaValidator, core_schema
+
+    class MyModel:
+        __slots__ = (
+            '__dict__',
+            '__pydantic_fields_set__',
+            '__pydantic_extra__',
+            '__pydantic_private__',
+        )
+
+    schema = core_schema.model_schema(
+        cls=MyModel,
+        config=CoreConfig(str_max_length=5),
+        schema=core_schema.model_fields_schema(
+            fields={'a': core_schema.model_field(core_schema.str_schema())},
+        ),
+    )
+    v = SchemaValidator(schema)
+    assert v.isinstance_python({'a': 'hello'}) is True
+    assert v.isinstance_python({'a': 'too long'}) is False
+    ```
+
+    Args:
+        cls: The class to use for the model
+        schema: The schema to use for the model
+        generic_origin: The origin type used for this model, if it's a parametrized generic. Ex,
+            if this model schema represents `SomeModel[int]`, generic_origin is `SomeModel`
+        custom_init: Whether the model has a custom init method
+        root_model: Whether the model is a `RootModel`
+        post_init: The call after init to use for the model
+        revalidate_instances: whether instances of models and dataclasses (including subclass instances)
+            should re-validate defaults to config.revalidate_instances, else 'never'
+        strict: Whether the model is strict
+        frozen: Whether the model is frozen
+        extra_behavior: The extra behavior to use for the model, used in serialization
+        config: The config to use for the model
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='model',
+        cls=cls,
+        generic_origin=generic_origin,
+        schema=schema,
+        custom_init=custom_init,
+        root_model=root_model,
+        post_init=post_init,
+        revalidate_instances=revalidate_instances,
+        strict=strict,
+        frozen=frozen,
+        extra_behavior=extra_behavior,
+        config=config,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DataclassField(TypedDict, total=False):
+    type: Required[Literal['dataclass-field']]
+    name: Required[str]
+    schema: Required[CoreSchema]
+    kw_only: bool  # default: True
+    init: bool  # default: True
+    init_only: bool  # default: False
+    frozen: bool  # default: False
+    validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+    serialization_alias: str
+    serialization_exclude: bool  # default: False
+    metadata: dict[str, Any]
+    serialization_exclude_if: Callable[[Any], bool]  # default: None
+
+
+def dataclass_field(
+    name: str,
+    schema: CoreSchema,
+    *,
+    kw_only: bool | None = None,
+    init: bool | None = None,
+    init_only: bool | None = None,
+    validation_alias: str | list[str | int] | list[list[str | int]] | None = None,
+    serialization_alias: str | None = None,
+    serialization_exclude: bool | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization_exclude_if: Callable[[Any], bool] | None = None,
+    frozen: bool | None = None,
+) -> DataclassField:
+    """
+    Returns a schema for a dataclass field, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    field = core_schema.dataclass_field(
+        name='a', schema=core_schema.str_schema(), kw_only=False
+    )
+    schema = core_schema.dataclass_args_schema('Foobar', [field])
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': 'hello'}) == ({'a': 'hello'}, None)
+    ```
+
+    Args:
+        name: The name to use for the argument parameter
+        schema: The schema to use for the argument parameter
+        kw_only: Whether the field can be set with a positional argument as well as a keyword argument
+        init: Whether the field should be validated during initialization
+        init_only: Whether the field should be omitted  from `__dict__` and passed to `__post_init__`
+        validation_alias: The alias(es) to use to find the field in the validation data
+        serialization_alias: The alias to use as a key when serializing
+        serialization_exclude: Whether to exclude the field when serializing
+        serialization_exclude_if: A callable that determines whether to exclude the field when serializing based on its value.
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        frozen: Whether the field is frozen
+    """
+    return _dict_not_none(
+        type='dataclass-field',
+        name=name,
+        schema=schema,
+        kw_only=kw_only,
+        init=init,
+        init_only=init_only,
+        validation_alias=validation_alias,
+        serialization_alias=serialization_alias,
+        serialization_exclude=serialization_exclude,
+        serialization_exclude_if=serialization_exclude_if,
+        metadata=metadata,
+        frozen=frozen,
+    )
+
+
+class DataclassArgsSchema(TypedDict, total=False):
+    type: Required[Literal['dataclass-args']]
+    dataclass_name: Required[str]
+    fields: Required[list[DataclassField]]
+    computed_fields: list[ComputedField]
+    collect_init_only: bool  # default: False
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+    extra_behavior: ExtraBehavior
+
+
+def dataclass_args_schema(
+    dataclass_name: str,
+    fields: list[DataclassField],
+    *,
+    computed_fields: list[ComputedField] | None = None,
+    collect_init_only: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+    extra_behavior: ExtraBehavior | None = None,
+) -> DataclassArgsSchema:
+    """
+    Returns a schema for validating dataclass arguments, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    field_a = core_schema.dataclass_field(
+        name='a', schema=core_schema.str_schema(), kw_only=False
+    )
+    field_b = core_schema.dataclass_field(
+        name='b', schema=core_schema.bool_schema(), kw_only=False
+    )
+    schema = core_schema.dataclass_args_schema('Foobar', [field_a, field_b])
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': 'hello', 'b': True}) == ({'a': 'hello', 'b': True}, None)
+    ```
+
+    Args:
+        dataclass_name: The name of the dataclass being validated
+        fields: The fields to use for the dataclass
+        computed_fields: Computed fields to use when serializing the dataclass
+        collect_init_only: Whether to collect init only fields into a dict to pass to `__post_init__`
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+        extra_behavior: How to handle extra fields
+    """
+    return _dict_not_none(
+        type='dataclass-args',
+        dataclass_name=dataclass_name,
+        fields=fields,
+        computed_fields=computed_fields,
+        collect_init_only=collect_init_only,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+        extra_behavior=extra_behavior,
+    )
+
+
+class DataclassSchema(TypedDict, total=False):
+    type: Required[Literal['dataclass']]
+    cls: Required[type[Any]]
+    generic_origin: type[Any]
+    schema: Required[CoreSchema]
+    fields: Required[list[str]]
+    cls_name: str
+    post_init: bool  # default: False
+    revalidate_instances: Literal['always', 'never', 'subclass-instances']  # default: 'never'
+    strict: bool  # default: False
+    frozen: bool  # default False
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+    slots: bool
+    config: CoreConfig
+
+
+def dataclass_schema(
+    cls: type[Any],
+    schema: CoreSchema,
+    fields: list[str],
+    *,
+    generic_origin: type[Any] | None = None,
+    cls_name: str | None = None,
+    post_init: bool | None = None,
+    revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+    frozen: bool | None = None,
+    slots: bool | None = None,
+    config: CoreConfig | None = None,
+) -> DataclassSchema:
+    """
+    Returns a schema for a dataclass. As with `ModelSchema`, this schema can only be used as a field within
+    another schema, not as the root type.
+
+    Args:
+        cls: The dataclass type, used to perform subclass checks
+        schema: The schema to use for the dataclass fields
+        fields: Fields of the dataclass, this is used in serialization and in validation during re-validation
+            and while validating assignment
+        generic_origin: The origin type used for this dataclass, if it's a parametrized generic. Ex,
+            if this model schema represents `SomeDataclass[int]`, generic_origin is `SomeDataclass`
+        cls_name: The name to use in error locs, etc; this is useful for generics (default: `cls.__name__`)
+        post_init: Whether to call `__post_init__` after validation
+        revalidate_instances: whether instances of models and dataclasses (including subclass instances)
+            should re-validate defaults to config.revalidate_instances, else 'never'
+        strict: Whether to require an exact instance of `cls`
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+        frozen: Whether the dataclass is frozen
+        slots: Whether `slots=True` on the dataclass, means each field is assigned independently, rather than
+            simply setting `__dict__`, default false
+    """
+    return _dict_not_none(
+        type='dataclass',
+        cls=cls,
+        generic_origin=generic_origin,
+        fields=fields,
+        cls_name=cls_name,
+        schema=schema,
+        post_init=post_init,
+        revalidate_instances=revalidate_instances,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+        frozen=frozen,
+        slots=slots,
+        config=config,
+    )
+
+
+class ArgumentsParameter(TypedDict, total=False):
+    name: Required[str]
+    schema: Required[CoreSchema]
+    mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only']  # default positional_or_keyword
+    alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+
+
+def arguments_parameter(
+    name: str,
+    schema: CoreSchema,
+    *,
+    mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None,
+    alias: str | list[str | int] | list[list[str | int]] | None = None,
+) -> ArgumentsParameter:
+    """
+    Returns a schema that matches an argument parameter, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param = core_schema.arguments_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    schema = core_schema.arguments_schema([param])
+    v = SchemaValidator(schema)
+    assert v.validate_python(('hello',)) == (('hello',), {})
+    ```
+
+    Args:
+        name: The name to use for the argument parameter
+        schema: The schema to use for the argument parameter
+        mode: The mode to use for the argument parameter
+        alias: The alias to use for the argument parameter
+    """
+    return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias)
+
+
+VarKwargsMode: TypeAlias = Literal['uniform', 'unpacked-typed-dict']
+
+
+class ArgumentsSchema(TypedDict, total=False):
+    type: Required[Literal['arguments']]
+    arguments_schema: Required[list[ArgumentsParameter]]
+    validate_by_name: bool
+    validate_by_alias: bool
+    var_args_schema: CoreSchema
+    var_kwargs_mode: VarKwargsMode
+    var_kwargs_schema: CoreSchema
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def arguments_schema(
+    arguments: list[ArgumentsParameter],
+    *,
+    validate_by_name: bool | None = None,
+    validate_by_alias: bool | None = None,
+    var_args_schema: CoreSchema | None = None,
+    var_kwargs_mode: VarKwargsMode | None = None,
+    var_kwargs_schema: CoreSchema | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ArgumentsSchema:
+    """
+    Returns a schema that matches an arguments schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param_a = core_schema.arguments_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    param_b = core_schema.arguments_parameter(
+        name='b', schema=core_schema.bool_schema(), mode='positional_only'
+    )
+    schema = core_schema.arguments_schema([param_a, param_b])
+    v = SchemaValidator(schema)
+    assert v.validate_python(('hello', True)) == (('hello', True), {})
+    ```
+
+    Args:
+        arguments: The arguments to use for the arguments schema
+        validate_by_name: Whether to populate by the parameter names, defaults to `False`.
+        validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`.
+        var_args_schema: The variable args schema to use for the arguments schema
+        var_kwargs_mode: The validation mode to use for variadic keyword arguments. If `'uniform'`, every value of the
+            keyword arguments will be validated against the `var_kwargs_schema` schema. If `'unpacked-typed-dict'`,
+            the `var_kwargs_schema` argument must be a [`typed_dict_schema`][pydantic_core.core_schema.typed_dict_schema]
+        var_kwargs_schema: The variable kwargs schema to use for the arguments schema
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='arguments',
+        arguments_schema=arguments,
+        validate_by_name=validate_by_name,
+        validate_by_alias=validate_by_alias,
+        var_args_schema=var_args_schema,
+        var_kwargs_mode=var_kwargs_mode,
+        var_kwargs_schema=var_kwargs_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class ArgumentsV3Parameter(TypedDict, total=False):
+    name: Required[str]
+    schema: Required[CoreSchema]
+    mode: Literal[
+        'positional_only',
+        'positional_or_keyword',
+        'keyword_only',
+        'var_args',
+        'var_kwargs_uniform',
+        'var_kwargs_unpacked_typed_dict',
+    ]  # default positional_or_keyword
+    alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]]
+
+
+def arguments_v3_parameter(
+    name: str,
+    schema: CoreSchema,
+    *,
+    mode: Literal[
+        'positional_only',
+        'positional_or_keyword',
+        'keyword_only',
+        'var_args',
+        'var_kwargs_uniform',
+        'var_kwargs_unpacked_typed_dict',
+    ]
+    | None = None,
+    alias: str | list[str | int] | list[list[str | int]] | None = None,
+) -> ArgumentsV3Parameter:
+    """
+    Returns a schema that matches an argument parameter, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param = core_schema.arguments_v3_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    schema = core_schema.arguments_v3_schema([param])
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': 'hello'}) == (('hello',), {})
+    ```
+
+    Args:
+        name: The name to use for the argument parameter
+        schema: The schema to use for the argument parameter
+        mode: The mode to use for the argument parameter
+        alias: The alias to use for the argument parameter
+    """
+    return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias)
+
+
+class ArgumentsV3Schema(TypedDict, total=False):
+    type: Required[Literal['arguments-v3']]
+    arguments_schema: Required[list[ArgumentsV3Parameter]]
+    validate_by_name: bool
+    validate_by_alias: bool
+    extra_behavior: Literal['forbid', 'ignore']  # 'allow' doesn't make sense here.
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def arguments_v3_schema(
+    arguments: list[ArgumentsV3Parameter],
+    *,
+    validate_by_name: bool | None = None,
+    validate_by_alias: bool | None = None,
+    extra_behavior: Literal['forbid', 'ignore'] | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> ArgumentsV3Schema:
+    """
+    Returns a schema that matches an arguments schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param_a = core_schema.arguments_v3_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    param_b = core_schema.arguments_v3_parameter(
+        name='kwargs', schema=core_schema.bool_schema(), mode='var_kwargs_uniform'
+    )
+    schema = core_schema.arguments_v3_schema([param_a, param_b])
+    v = SchemaValidator(schema)
+    assert v.validate_python({'a': 'hi', 'kwargs': {'b': True}}) == (('hi',), {'b': True})
+    ```
+
+    This schema is currently not used by other Pydantic components. In V3, it will most likely
+    become the default arguments schema for the `'call'` schema.
+
+    Args:
+        arguments: The arguments to use for the arguments schema.
+        validate_by_name: Whether to populate by the parameter names, defaults to `False`.
+        validate_by_alias: Whether to populate by the parameter aliases, defaults to `True`.
+        extra_behavior: The extra behavior to use.
+        ref: optional unique identifier of the schema, used to reference the schema in other places.
+        metadata: Any other information you want to include with the schema, not used by pydantic-core.
+        serialization: Custom serialization schema.
+    """
+    return _dict_not_none(
+        type='arguments-v3',
+        arguments_schema=arguments,
+        validate_by_name=validate_by_name,
+        validate_by_alias=validate_by_alias,
+        extra_behavior=extra_behavior,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class CallSchema(TypedDict, total=False):
+    type: Required[Literal['call']]
+    arguments_schema: Required[CoreSchema]
+    function: Required[Callable[..., Any]]
+    function_name: str  # default function.__name__
+    return_schema: CoreSchema
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def call_schema(
+    arguments: CoreSchema,
+    function: Callable[..., Any],
+    *,
+    function_name: str | None = None,
+    return_schema: CoreSchema | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> CallSchema:
+    """
+    Returns a schema that matches an arguments schema, then calls a function, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    param_a = core_schema.arguments_parameter(
+        name='a', schema=core_schema.str_schema(), mode='positional_only'
+    )
+    param_b = core_schema.arguments_parameter(
+        name='b', schema=core_schema.bool_schema(), mode='positional_only'
+    )
+    args_schema = core_schema.arguments_schema([param_a, param_b])
+
+    schema = core_schema.call_schema(
+        arguments=args_schema,
+        function=lambda a, b: a + str(not b),
+        return_schema=core_schema.str_schema(),
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python((('hello', True))) == 'helloFalse'
+    ```
+
+    Args:
+        arguments: The arguments to use for the arguments schema
+        function: The function to use for the call schema
+        function_name: The function name to use for the call schema, if not provided `function.__name__` is used
+        return_schema: The return schema to use for the call schema
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='call',
+        arguments_schema=arguments,
+        function=function,
+        function_name=function_name,
+        return_schema=return_schema,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class CustomErrorSchema(TypedDict, total=False):
+    type: Required[Literal['custom-error']]
+    schema: Required[CoreSchema]
+    custom_error_type: Required[str]
+    custom_error_message: str
+    custom_error_context: dict[str, Union[str, int, float]]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def custom_error_schema(
+    schema: CoreSchema,
+    custom_error_type: str,
+    *,
+    custom_error_message: str | None = None,
+    custom_error_context: dict[str, Any] | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> CustomErrorSchema:
+    """
+    Returns a schema that matches a custom error value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.custom_error_schema(
+        schema=core_schema.int_schema(),
+        custom_error_type='MyError',
+        custom_error_message='Error msg',
+    )
+    v = SchemaValidator(schema)
+    v.validate_python(1)
+    ```
+
+    Args:
+        schema: The schema to use for the custom error schema
+        custom_error_type: The custom error type to use for the custom error schema
+        custom_error_message: The custom error message to use for the custom error schema
+        custom_error_context: The custom error context to use for the custom error schema
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='custom-error',
+        schema=schema,
+        custom_error_type=custom_error_type,
+        custom_error_message=custom_error_message,
+        custom_error_context=custom_error_context,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class JsonSchema(TypedDict, total=False):
+    type: Required[Literal['json']]
+    schema: CoreSchema
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def json_schema(
+    schema: CoreSchema | None = None,
+    *,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> JsonSchema:
+    """
+    Returns a schema that matches a JSON value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    dict_schema = core_schema.model_fields_schema(
+        {
+            'field_a': core_schema.model_field(core_schema.str_schema()),
+            'field_b': core_schema.model_field(core_schema.bool_schema()),
+        },
+    )
+
+    class MyModel:
+        __slots__ = (
+            '__dict__',
+            '__pydantic_fields_set__',
+            '__pydantic_extra__',
+            '__pydantic_private__',
+        )
+        field_a: str
+        field_b: bool
+
+    json_schema = core_schema.json_schema(schema=dict_schema)
+    schema = core_schema.model_schema(cls=MyModel, schema=json_schema)
+    v = SchemaValidator(schema)
+    m = v.validate_python('{"field_a": "hello", "field_b": true}')
+    assert isinstance(m, MyModel)
+    ```
+
+    Args:
+        schema: The schema to use for the JSON schema
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(type='json', schema=schema, ref=ref, metadata=metadata, serialization=serialization)
+
+
+class UrlSchema(TypedDict, total=False):
+    type: Required[Literal['url']]
+    max_length: int
+    allowed_schemes: list[str]
+    host_required: bool  # default False
+    default_host: str
+    default_port: int
+    default_path: str
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def url_schema(
+    *,
+    max_length: int | None = None,
+    allowed_schemes: list[str] | None = None,
+    host_required: bool | None = None,
+    default_host: str | None = None,
+    default_port: int | None = None,
+    default_path: str | None = None,
+    preserve_empty_path: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> UrlSchema:
+    """
+    Returns a schema that matches a URL value, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.url_schema()
+    v = SchemaValidator(schema)
+    print(v.validate_python('https://example.com'))
+    #> https://example.com/
+    ```
+
+    Args:
+        max_length: The maximum length of the URL
+        allowed_schemes: The allowed URL schemes
+        host_required: Whether the URL must have a host
+        default_host: The default host to use if the URL does not have a host
+        default_port: The default port to use if the URL does not have a port
+        default_path: The default path to use if the URL does not have a path
+        preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False
+        strict: Whether to use strict URL parsing
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='url',
+        max_length=max_length,
+        allowed_schemes=allowed_schemes,
+        host_required=host_required,
+        default_host=default_host,
+        default_port=default_port,
+        default_path=default_path,
+        preserve_empty_path=preserve_empty_path,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class MultiHostUrlSchema(TypedDict, total=False):
+    type: Required[Literal['multi-host-url']]
+    max_length: int
+    allowed_schemes: list[str]
+    host_required: bool  # default False
+    default_host: str
+    default_port: int
+    default_path: str
+    strict: bool
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def multi_host_url_schema(
+    *,
+    max_length: int | None = None,
+    allowed_schemes: list[str] | None = None,
+    host_required: bool | None = None,
+    default_host: str | None = None,
+    default_port: int | None = None,
+    default_path: str | None = None,
+    preserve_empty_path: bool | None = None,
+    strict: bool | None = None,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> MultiHostUrlSchema:
+    """
+    Returns a schema that matches a URL value with possibly multiple hosts, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.multi_host_url_schema()
+    v = SchemaValidator(schema)
+    print(v.validate_python('redis://localhost,0.0.0.0,127.0.0.1'))
+    #> redis://localhost,0.0.0.0,127.0.0.1
+    ```
+
+    Args:
+        max_length: The maximum length of the URL
+        allowed_schemes: The allowed URL schemes
+        host_required: Whether the URL must have a host
+        default_host: The default host to use if the URL does not have a host
+        default_port: The default port to use if the URL does not have a port
+        default_path: The default path to use if the URL does not have a path
+        preserve_empty_path: Whether to preserve an empty path or convert it to '/', default False
+        strict: Whether to use strict URL parsing
+        ref: optional unique identifier of the schema, used to reference the schema in other places
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='multi-host-url',
+        max_length=max_length,
+        allowed_schemes=allowed_schemes,
+        host_required=host_required,
+        default_host=default_host,
+        default_port=default_port,
+        default_path=default_path,
+        preserve_empty_path=preserve_empty_path,
+        strict=strict,
+        ref=ref,
+        metadata=metadata,
+        serialization=serialization,
+    )
+
+
+class DefinitionsSchema(TypedDict, total=False):
+    type: Required[Literal['definitions']]
+    schema: Required[CoreSchema]
+    definitions: Required[list[CoreSchema]]
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def definitions_schema(schema: CoreSchema, definitions: list[CoreSchema]) -> DefinitionsSchema:
+    """
+    Build a schema that contains both an inner schema and a list of definitions which can be used
+    within the inner schema.
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema = core_schema.definitions_schema(
+        core_schema.list_schema(core_schema.definition_reference_schema('foobar')),
+        [core_schema.int_schema(ref='foobar')],
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python([1, 2, '3']) == [1, 2, 3]
+    ```
+
+    Args:
+        schema: The inner schema
+        definitions: List of definitions which can be referenced within inner schema
+    """
+    return DefinitionsSchema(type='definitions', schema=schema, definitions=definitions)
+
+
+class DefinitionReferenceSchema(TypedDict, total=False):
+    type: Required[Literal['definition-ref']]
+    schema_ref: Required[str]
+    ref: str
+    metadata: dict[str, Any]
+    serialization: SerSchema
+
+
+def definition_reference_schema(
+    schema_ref: str,
+    ref: str | None = None,
+    metadata: dict[str, Any] | None = None,
+    serialization: SerSchema | None = None,
+) -> DefinitionReferenceSchema:
+    """
+    Returns a schema that points to a schema stored in "definitions", this is useful for nested recursive
+    models and also when you want to define validators separately from the main schema, e.g.:
+
+    ```py
+    from pydantic_core import SchemaValidator, core_schema
+
+    schema_definition = core_schema.definition_reference_schema('list-schema')
+    schema = core_schema.definitions_schema(
+        schema=schema_definition,
+        definitions=[
+            core_schema.list_schema(items_schema=schema_definition, ref='list-schema'),
+        ],
+    )
+    v = SchemaValidator(schema)
+    assert v.validate_python([()]) == [[]]
+    ```
+
+    Args:
+        schema_ref: The schema ref to use for the definition reference schema
+        metadata: Any other information you want to include with the schema, not used by pydantic-core
+        serialization: Custom serialization schema
+    """
+    return _dict_not_none(
+        type='definition-ref', schema_ref=schema_ref, ref=ref, metadata=metadata, serialization=serialization
+    )
+
+
+MYPY = False
+# See https://github.com/python/mypy/issues/14034 for details, in summary mypy is extremely slow to process this
+# union which kills performance not just for pydantic, but even for code using pydantic
+if not MYPY:
+    CoreSchema = Union[
+        InvalidSchema,
+        AnySchema,
+        NoneSchema,
+        BoolSchema,
+        IntSchema,
+        FloatSchema,
+        DecimalSchema,
+        StringSchema,
+        BytesSchema,
+        DateSchema,
+        TimeSchema,
+        DatetimeSchema,
+        TimedeltaSchema,
+        LiteralSchema,
+        MissingSentinelSchema,
+        EnumSchema,
+        IsInstanceSchema,
+        IsSubclassSchema,
+        CallableSchema,
+        ListSchema,
+        TupleSchema,
+        SetSchema,
+        FrozenSetSchema,
+        GeneratorSchema,
+        DictSchema,
+        AfterValidatorFunctionSchema,
+        BeforeValidatorFunctionSchema,
+        WrapValidatorFunctionSchema,
+        PlainValidatorFunctionSchema,
+        WithDefaultSchema,
+        NullableSchema,
+        UnionSchema,
+        TaggedUnionSchema,
+        ChainSchema,
+        LaxOrStrictSchema,
+        JsonOrPythonSchema,
+        TypedDictSchema,
+        ModelFieldsSchema,
+        ModelSchema,
+        DataclassArgsSchema,
+        DataclassSchema,
+        ArgumentsSchema,
+        ArgumentsV3Schema,
+        CallSchema,
+        CustomErrorSchema,
+        JsonSchema,
+        UrlSchema,
+        MultiHostUrlSchema,
+        DefinitionsSchema,
+        DefinitionReferenceSchema,
+        UuidSchema,
+        ComplexSchema,
+    ]
+elif False:
+    CoreSchema: TypeAlias = Mapping[str, Any]
+
+
+# to update this, call `pytest -k test_core_schema_type_literal` and copy the output
+CoreSchemaType = Literal[
+    'invalid',
+    'any',
+    'none',
+    'bool',
+    'int',
+    'float',
+    'decimal',
+    'str',
+    'bytes',
+    'date',
+    'time',
+    'datetime',
+    'timedelta',
+    'literal',
+    'missing-sentinel',
+    'enum',
+    'is-instance',
+    'is-subclass',
+    'callable',
+    'list',
+    'tuple',
+    'set',
+    'frozenset',
+    'generator',
+    'dict',
+    'function-after',
+    'function-before',
+    'function-wrap',
+    'function-plain',
+    'default',
+    'nullable',
+    'union',
+    'tagged-union',
+    'chain',
+    'lax-or-strict',
+    'json-or-python',
+    'typed-dict',
+    'model-fields',
+    'model',
+    'dataclass-args',
+    'dataclass',
+    'arguments',
+    'arguments-v3',
+    'call',
+    'custom-error',
+    'json',
+    'url',
+    'multi-host-url',
+    'definitions',
+    'definition-ref',
+    'uuid',
+    'complex',
+]
+
+CoreSchemaFieldType = Literal['model-field', 'dataclass-field', 'typed-dict-field', 'computed-field']
+
+
+# used in _pydantic_core.pyi::PydanticKnownError
+# to update this, call `pytest -k test_all_errors` and copy the output
+ErrorType = Literal[
+    'no_such_attribute',
+    'json_invalid',
+    'json_type',
+    'needs_python_object',
+    'recursion_loop',
+    'missing',
+    'frozen_field',
+    'frozen_instance',
+    'extra_forbidden',
+    'invalid_key',
+    'get_attribute_error',
+    'model_type',
+    'model_attributes_type',
+    'dataclass_type',
+    'dataclass_exact_type',
+    'default_factory_not_called',
+    'none_required',
+    'greater_than',
+    'greater_than_equal',
+    'less_than',
+    'less_than_equal',
+    'multiple_of',
+    'finite_number',
+    'too_short',
+    'too_long',
+    'iterable_type',
+    'iteration_error',
+    'string_type',
+    'string_sub_type',
+    'string_unicode',
+    'string_too_short',
+    'string_too_long',
+    'string_pattern_mismatch',
+    'enum',
+    'dict_type',
+    'mapping_type',
+    'list_type',
+    'tuple_type',
+    'set_type',
+    'set_item_not_hashable',
+    'bool_type',
+    'bool_parsing',
+    'int_type',
+    'int_parsing',
+    'int_parsing_size',
+    'int_from_float',
+    'float_type',
+    'float_parsing',
+    'bytes_type',
+    'bytes_too_short',
+    'bytes_too_long',
+    'bytes_invalid_encoding',
+    'value_error',
+    'assertion_error',
+    'literal_error',
+    'missing_sentinel_error',
+    'date_type',
+    'date_parsing',
+    'date_from_datetime_parsing',
+    'date_from_datetime_inexact',
+    'date_past',
+    'date_future',
+    'time_type',
+    'time_parsing',
+    'datetime_type',
+    'datetime_parsing',
+    'datetime_object_invalid',
+    'datetime_from_date_parsing',
+    'datetime_past',
+    'datetime_future',
+    'timezone_naive',
+    'timezone_aware',
+    'timezone_offset',
+    'time_delta_type',
+    'time_delta_parsing',
+    'frozen_set_type',
+    'is_instance_of',
+    'is_subclass_of',
+    'callable_type',
+    'union_tag_invalid',
+    'union_tag_not_found',
+    'arguments_type',
+    'missing_argument',
+    'unexpected_keyword_argument',
+    'missing_keyword_only_argument',
+    'unexpected_positional_argument',
+    'missing_positional_only_argument',
+    'multiple_argument_values',
+    'url_type',
+    'url_parsing',
+    'url_syntax_violation',
+    'url_too_long',
+    'url_scheme',
+    'uuid_type',
+    'uuid_parsing',
+    'uuid_version',
+    'decimal_type',
+    'decimal_parsing',
+    'decimal_max_digits',
+    'decimal_max_places',
+    'decimal_whole_digits',
+    'complex_type',
+    'complex_str_parsing',
+]
+
+
+def _dict_not_none(**kwargs: Any) -> Any:
+    return {k: v for k, v in kwargs.items() if v is not None}
+
+
+###############################################################################
+# All this stuff is deprecated by #980 and will be removed eventually
+# They're kept because some code external code will be using them
+
+
+@deprecated('`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.')
+def field_before_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs):
+    warnings.warn(
+        '`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_before_validator_function(function, schema, field_name=field_name, **kwargs)
+
+
+@deprecated('`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.')
+def general_before_validator_function(*args, **kwargs):
+    warnings.warn(
+        '`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_before_validator_function(*args, **kwargs)
+
+
+@deprecated('`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.')
+def field_after_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs):
+    warnings.warn(
+        '`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_after_validator_function(function, schema, field_name=field_name, **kwargs)
+
+
+@deprecated('`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.')
+def general_after_validator_function(*args, **kwargs):
+    warnings.warn(
+        '`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_after_validator_function(*args, **kwargs)
+
+
+@deprecated('`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.')
+def field_wrap_validator_function(
+    function: WithInfoWrapValidatorFunction, field_name: str, schema: CoreSchema, **kwargs
+):
+    warnings.warn(
+        '`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_wrap_validator_function(function, schema, field_name=field_name, **kwargs)
+
+
+@deprecated('`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.')
+def general_wrap_validator_function(*args, **kwargs):
+    warnings.warn(
+        '`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_wrap_validator_function(*args, **kwargs)
+
+
+@deprecated('`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.')
+def field_plain_validator_function(function: WithInfoValidatorFunction, field_name: str, **kwargs):
+    warnings.warn(
+        '`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_plain_validator_function(function, field_name=field_name, **kwargs)
+
+
+@deprecated('`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.')
+def general_plain_validator_function(*args, **kwargs):
+    warnings.warn(
+        '`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.',
+        DeprecationWarning,
+    )
+    return with_info_plain_validator_function(*args, **kwargs)
+
+
+_deprecated_import_lookup = {
+    'FieldValidationInfo': ValidationInfo,
+    'FieldValidatorFunction': WithInfoValidatorFunction,
+    'GeneralValidatorFunction': WithInfoValidatorFunction,
+    'FieldWrapValidatorFunction': WithInfoWrapValidatorFunction,
+}
+
+if TYPE_CHECKING:
+    FieldValidationInfo = ValidationInfo
+
+
+def __getattr__(attr_name: str) -> object:
+    new_attr = _deprecated_import_lookup.get(attr_name)
+    if new_attr is None:
+        raise AttributeError(f"module 'pydantic_core' has no attribute '{attr_name}'")
+    else:
+        import warnings
+
+        msg = f'`{attr_name}` is deprecated, use `{new_attr.__name__}` instead.'
+        warnings.warn(msg, DeprecationWarning, stacklevel=1)
+        return new_attr
diff --git a/data/miniconda3/lib/python3.13/site-packages/pydantic_core/py.typed b/data/miniconda3/lib/python3.13/site-packages/pydantic_core/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/INSTALLER b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
\ No newline at end of file
diff --git a/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/METADATA b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..00e201fec4d955d32ad2859128a4e6189118fb9f
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/METADATA
@@ -0,0 +1,330 @@
+Metadata-Version: 2.4
+Name: PySocks
+Version: 1.7.1
+Summary: A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information.
+Home-page: https://github.com/Anorov/PySocks
+Author: Anorov
+Author-email: anorov.vorona@gmail.com
+License: BSD
+Keywords: socks,proxy
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: 3.5
+Classifier: Programming Language :: Python :: 3.6
+Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: description
+Dynamic: description-content-type
+Dynamic: home-page
+Dynamic: keywords
+Dynamic: license
+Dynamic: license-file
+Dynamic: requires-python
+Dynamic: summary
+
+PySocks
+=======
+
+PySocks lets you send traffic through SOCKS and HTTP proxy servers. It is a modern fork of [SocksiPy](http://socksipy.sourceforge.net/) with bug fixes and extra features.
+
+Acts as a drop-in replacement to the socket module. Seamlessly configure SOCKS proxies for any socket object by calling `socket_object.set_proxy()`.
+
+----------------
+
+Features
+========
+
+* SOCKS proxy client for Python 2.7 and 3.4+
+* TCP supported
+* UDP mostly supported (issues may occur in some edge cases)
+* HTTP proxy client included but not supported or recommended (you should use urllib2's or requests' own HTTP proxy interface)
+* urllib2 handler included. `pip install` / `setup.py install` will automatically install the `sockshandler` module.
+
+Installation
+============
+
+    pip install PySocks
+
+Or download the tarball / `git clone` and...
+
+    python setup.py install
+
+These will install both the `socks` and `sockshandler` modules.
+
+Alternatively, include just `socks.py` in your project.
+
+--------------------------------------------
+
+*Warning:* PySocks/SocksiPy only supports HTTP proxies that use CONNECT tunneling. Certain HTTP proxies may not work with this library. If you wish to use HTTP (not SOCKS) proxies, it is recommended that you rely on your HTTP client's native proxy support (`proxies` dict for `requests`, or `urllib2.ProxyHandler` for `urllib2`) instead.
+
+--------------------------------------------
+
+Usage
+=====
+
+## socks.socksocket ##
+
+    import socks
+
+    s = socks.socksocket() # Same API as socket.socket in the standard lib
+
+    s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by default
+    # Or
+    s.set_proxy(socks.SOCKS4, "localhost", 4444)
+    # Or
+    s.set_proxy(socks.HTTP, "5.5.5.5", 8888)
+
+    # Can be treated identical to a regular socket object
+    s.connect(("www.somesite.com", 80))
+    s.sendall("GET / HTTP/1.1 ...")
+    print s.recv(4096)
+
+## Monkeypatching ##
+
+To monkeypatch the entire standard library with a single default proxy:
+
+    import urllib2
+    import socket
+    import socks
+
+    socks.set_default_proxy(socks.SOCKS5, "localhost")
+    socket.socket = socks.socksocket
+
+    urllib2.urlopen("http://www.somesite.com/") # All requests will pass through the SOCKS proxy
+
+Note that monkeypatching may not work for all standard modules or for all third party modules, and generally isn't recommended. Monkeypatching is usually an anti-pattern in Python.
+
+## urllib2 Handler ##
+
+Example use case with the `sockshandler` urllib2 handler. Note that you must import both `socks` and `sockshandler`, as the handler is its own module separate from PySocks. The module is included in the PyPI package.
+
+    import urllib2
+    import socks
+    from sockshandler import SocksiPyHandler
+
+    opener = urllib2.build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050))
+    print opener.open("http://www.somesite.com/") # All requests made by the opener will pass through the SOCKS proxy
+
+--------------------------------------------
+
+Original SocksiPy README attached below, amended to reflect API changes.
+
+--------------------------------------------
+
+SocksiPy
+
+A Python SOCKS module.
+
+(C) 2006 Dan-Haim. All rights reserved.
+
+See LICENSE file for details.
+
+
+*WHAT IS A SOCKS PROXY?*
+
+A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as
+a tunnel, relaying all traffic going through it without modifying it.
+SOCKS proxies can be used to relay traffic using any network protocol that
+uses TCP.
+
+*WHAT IS SOCKSIPY?*
+
+This Python module allows you to create TCP connections through a SOCKS
+proxy without any special effort.
+It also supports relaying UDP packets with a SOCKS5 proxy.
+
+*PROXY COMPATIBILITY*
+
+SocksiPy is compatible with three different types of proxies:
+
+1. SOCKS Version 4 (SOCKS4), including the SOCKS4a extension.
+2. SOCKS Version 5 (SOCKS5).
+3. HTTP Proxies which support tunneling using the CONNECT method.
+
+*SYSTEM REQUIREMENTS*
+
+Being written in Python, SocksiPy can run on any platform that has a Python
+interpreter and TCP/IP support.
+This module has been tested with Python 2.3 and should work with greater versions
+just as well.
+
+
+INSTALLATION
+-------------
+
+Simply copy the file "socks.py" to your Python's `lib/site-packages` directory,
+and you're ready to go. [Editor's note: it is better to use `python setup.py install` for PySocks]
+
+
+USAGE
+------
+
+First load the socks module with the command:
+
+    >>> import socks
+    >>>
+
+The socks module provides a class called `socksocket`, which is the base to all of the module's functionality.
+
+The `socksocket` object has the same initialization parameters as the normal socket
+object to ensure maximal compatibility, however it should be noted that `socksocket` will only function with family being `AF_INET` and
+type being either `SOCK_STREAM` or `SOCK_DGRAM`.
+Generally, it is best to initialize the `socksocket` object with no parameters
+
+    >>> s = socks.socksocket()
+    >>>
+
+The `socksocket` object has an interface which is very similiar to socket's (in fact
+the `socksocket` class is derived from socket) with a few extra methods.
+To select the proxy server you would like to use, use the `set_proxy` method, whose
+syntax is:
+
+    set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
+
+Explanation of the parameters:
+
+`proxy_type` - The type of the proxy server. This can be one of three possible
+choices: `PROXY_TYPE_SOCKS4`, `PROXY_TYPE_SOCKS5` and `PROXY_TYPE_HTTP` for SOCKS4,
+SOCKS5 and HTTP servers respectively. `SOCKS4`, `SOCKS5`, and `HTTP` are all aliases, respectively.
+
+`addr` - The IP address or DNS name of the proxy server.
+
+`port` - The port of the proxy server. Defaults to 1080 for socks and 8080 for http.
+
+`rdns` - This is a boolean flag than modifies the behavior regarding DNS resolving.
+If it is set to True, DNS resolving will be preformed remotely, on the server.
+If it is set to False, DNS resolving will be preformed locally. Please note that
+setting this to True with SOCKS4 servers actually use an extension to the protocol,
+called SOCKS4a, which may not be supported on all servers (SOCKS5 and http servers
+always support DNS). The default is True.
+
+`username` - For SOCKS5 servers, this allows simple username / password authentication
+with the server. For SOCKS4 servers, this parameter will be sent as the userid.
+This parameter is ignored if an HTTP server is being used. If it is not provided,
+authentication will not be used (servers may accept unauthenticated requests).
+
+`password` - This parameter is valid only for SOCKS5 servers and specifies the
+respective password for the username provided.
+
+Example of usage:
+
+    >>> s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080
+    >>> s.set_proxy(socks.SOCKS4, "socks.test.com", 1081)
+
+After the set_proxy method has been called, simply call the connect method with the
+traditional parameters to establish a connection through the proxy:
+
+    >>> s.connect(("www.sourceforge.net", 80))
+    >>>
+
+Connection will take a bit longer to allow negotiation with the proxy server.
+Please note that calling connect without calling `set_proxy` earlier will connect
+without a proxy (just like a regular socket).
+
+Errors: Any errors in the connection process will trigger exceptions. The exception
+may either be generated by the underlying socket layer or may be custom module
+exceptions, whose details follow:
+
+class `ProxyError` - This is a base exception class. It is not raised directly but
+rather all other exception classes raised by this module are derived from it.
+This allows an easy way to catch all proxy-related errors. It descends from `IOError`.
+
+All `ProxyError` exceptions have an attribute `socket_err`, which will contain either a
+caught `socket.error` exception, or `None` if there wasn't any.
+
+class `GeneralProxyError` - When thrown, it indicates a problem which does not fall
+into another category.
+
+* `Sent invalid data` - This error means that unexpected data has been received from
+the server. The most common reason is that the server specified as the proxy is
+not really a SOCKS4/SOCKS5/HTTP proxy, or maybe the proxy type specified is wrong.
+
+* `Connection closed unexpectedly` - The proxy server unexpectedly closed the connection.
+This may indicate that the proxy server is experiencing network or software problems.
+
+* `Bad proxy type` - This will be raised if the type of the proxy supplied to the
+set_proxy function was not one of `SOCKS4`/`SOCKS5`/`HTTP`.
+
+* `Bad input` - This will be raised if the `connect()` method is called with bad input
+parameters.
+
+class `SOCKS5AuthError` - This indicates that the connection through a SOCKS5 server
+failed due to an authentication problem.
+
+* `Authentication is required` - This will happen if you use a SOCKS5 server which
+requires authentication without providing a username / password at all.
+
+* `All offered authentication methods were rejected` - This will happen if the proxy
+requires a special authentication method which is not supported by this module.
+
+* `Unknown username or invalid password` - Self descriptive.
+
+class `SOCKS5Error` - This will be raised for SOCKS5 errors which are not related to
+authentication.
+The parameter is a tuple containing a code, as given by the server,
+and a description of the
+error. The possible errors, according to the RFC, are:
+
+* `0x01` - General SOCKS server failure - If for any reason the proxy server is unable to
+fulfill your request (internal server error).
+* `0x02` - connection not allowed by ruleset - If the address you're trying to connect to
+is blacklisted on the server or requires authentication.
+* `0x03` - Network unreachable - The target could not be contacted. A router on the network
+had replied with a destination net unreachable error.
+* `0x04` - Host unreachable - The target could not be contacted. A router on the network
+had replied with a destination host unreachable error.
+* `0x05` - Connection refused - The target server has actively refused the connection
+(the requested port is closed).
+* `0x06` - TTL expired - The TTL value of the SYN packet from the proxy to the target server
+has expired. This usually means that there are network problems causing the packet
+to be caught in a router-to-router "ping-pong".
+* `0x07` - Command not supported - For instance if the server does not support UDP.
+* `0x08` - Address type not supported - The client has provided an invalid address type.
+When using this module, this error should not occur.
+
+class `SOCKS4Error` - This will be raised for SOCKS4 errors. The parameter is a tuple
+containing a code and a description of the error, as given by the server. The
+possible error, according to the specification are:
+
+* `0x5B` - Request rejected or failed - Will be raised in the event of an failure for any
+reason other then the two mentioned next.
+* `0x5C` - request rejected because SOCKS server cannot connect to identd on the client -
+The Socks server had tried an ident lookup on your computer and has failed. In this
+case you should run an identd server and/or configure your firewall to allow incoming
+connections to local port 113 from the remote server.
+* `0x5D` - request rejected because the client program and identd report different user-ids -
+The Socks server had performed an ident lookup on your computer and has received a
+different userid than the one you have provided. Change your userid (through the
+username parameter of the set_proxy method) to match and try again.
+
+class `HTTPError` - This will be raised for HTTP errors. The message will contain
+the HTTP status code and provided error message.
+
+After establishing the connection, the object behaves like a standard socket.
+
+Methods like `makefile()` and `settimeout()` should behave just like regular sockets.
+Call the `close()` method to close the connection.
+
+In addition to the `socksocket` class, an additional function worth mentioning is the
+`set_default_proxy` function. The parameters are the same as the `set_proxy` method.
+This function will set default proxy settings for newly created `socksocket` objects,
+in which the proxy settings haven't been changed via the `set_proxy` method.
+This is quite useful if you wish to force 3rd party modules to use a SOCKS proxy,
+by overriding the socket object.
+For example:
+
+    >>> socks.set_default_proxy(socks.SOCKS5, "socks.example.com")
+    >>> socket.socket = socks.socksocket
+    >>> urllib.urlopen("http://www.sourceforge.net/")
+
+
+PROBLEMS
+---------
+
+Please open a GitHub issue at https://github.com/Anorov/PySocks
diff --git a/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/RECORD b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..82baa2b7fbf5f2bacd64317b2368f6721153e60a
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/RECORD
@@ -0,0 +1,12 @@
+__pycache__/socks.cpython-313.pyc,,
+__pycache__/sockshandler.cpython-313.pyc,,
+pysocks-1.7.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pysocks-1.7.1.dist-info/METADATA,sha256=s0tCSaT0WJRL6NNS7WXhn9ua6ECBV8DbCiIuNMaA9gk,13468
+pysocks-1.7.1.dist-info/RECORD,,
+pysocks-1.7.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pysocks-1.7.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+pysocks-1.7.1.dist-info/direct_url.json,sha256=_ZfWj0bcP27SuKgeo4gJgWMBJAVOqnCJw9yXdSBxzXk,97
+pysocks-1.7.1.dist-info/licenses/LICENSE,sha256=cCfiFOAU63i3rcwc7aWspxOnn8T2oMUsnaWz5wfm_-k,1401
+pysocks-1.7.1.dist-info/top_level.txt,sha256=TKSOIfCFBoK9EY8FBYbYqC3PWd3--G15ph9n8-QHPDk,19
+socks.py,sha256=xOYn27t9IGrbTBzWsUUuPa0YBuplgiUykzkOB5V5iFY,31086
+sockshandler.py,sha256=2SYGj-pwt1kjgLoZAmyeaEXCeZDWRmfVS_QG6kErGtY,3966
diff --git a/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/REQUESTED b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/WHEEL b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/direct_url.json b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..c16b54c81a6c0a0b718883ac4d8e07fd935f0d25
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///home/task_176175235884818/conda-bld/pysocks_1761753009495/work"}
\ No newline at end of file
diff --git a/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/top_level.txt b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..9476163ae51c2dba237187f3b76d5ff46e40892f
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/pysocks-1.7.1.dist-info/top_level.txt
@@ -0,0 +1,2 @@
+socks
+sockshandler
diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/__init__.py b/data/miniconda3/lib/python3.13/site-packages/rich/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b631d54495e838fd7d989fd1dd06d2e5e3e321f3
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/rich/__init__.py
@@ -0,0 +1,177 @@
+"""Rich text and beautiful formatting in the terminal."""
+
+import os
+from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union
+
+from ._extension import load_ipython_extension  # noqa: F401
+
+__all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"]
+
+if TYPE_CHECKING:
+    from .console import Console
+
+# Global console used by alternative print
+_console: Optional["Console"] = None
+
+try:
+    _IMPORT_CWD = os.path.abspath(os.getcwd())
+except FileNotFoundError:
+    # Can happen if the cwd has been deleted
+    _IMPORT_CWD = ""
+
+
+def get_console() -> "Console":
+    """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,
+    and hasn't been explicitly given one.
+
+    Returns:
+        Console: A console instance.
+    """
+    global _console
+    if _console is None:
+        from .console import Console
+
+        _console = Console()
+
+    return _console
+
+
+def reconfigure(*args: Any, **kwargs: Any) -> None:
+    """Reconfigures the global console by replacing it with another.
+
+    Args:
+        *args (Any): Positional arguments for the replacement :class:`~rich.console.Console`.
+        **kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`.
+    """
+    from rich.console import Console
+
+    new_console = Console(*args, **kwargs)
+    _console = get_console()
+    _console.__dict__ = new_console.__dict__
+
+
+def print(
+    *objects: Any,
+    sep: str = " ",
+    end: str = "\n",
+    file: Optional[IO[str]] = None,
+    flush: bool = False,
+) -> None:
+    r"""Print object(s) supplied via positional arguments.
+    This function has an identical signature to the built-in print.
+    For more advanced features, see the :class:`~rich.console.Console` class.
+
+    Args:
+        sep (str, optional): Separator between printed objects. Defaults to " ".
+        end (str, optional): Character to write at end of output. Defaults to "\\n".
+        file (IO[str], optional): File to write to, or None for stdout. Defaults to None.
+        flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False.
+
+    """
+    from .console import Console
+
+    write_console = get_console() if file is None else Console(file=file)
+    return write_console.print(*objects, sep=sep, end=end)
+
+
+def print_json(
+    json: Optional[str] = None,
+    *,
+    data: Any = None,
+    indent: Union[None, int, str] = 2,
+    highlight: bool = True,
+    skip_keys: bool = False,
+    ensure_ascii: bool = False,
+    check_circular: bool = True,
+    allow_nan: bool = True,
+    default: Optional[Callable[[Any], Any]] = None,
+    sort_keys: bool = False,
+) -> None:
+    """Pretty prints JSON. Output will be valid JSON.
+
+    Args:
+        json (str): A string containing JSON.
+        data (Any): If json is not supplied, then encode this data.
+        indent (int, optional): Number of spaces to indent. Defaults to 2.
+        highlight (bool, optional): Enable highlighting of output: Defaults to True.
+        skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
+        ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
+        check_circular (bool, optional): Check for circular references. Defaults to True.
+        allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
+        default (Callable, optional): A callable that converts values that can not be encoded
+            in to something that can be JSON encoded. Defaults to None.
+        sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
+    """
+
+    get_console().print_json(
+        json,
+        data=data,
+        indent=indent,
+        highlight=highlight,
+        skip_keys=skip_keys,
+        ensure_ascii=ensure_ascii,
+        check_circular=check_circular,
+        allow_nan=allow_nan,
+        default=default,
+        sort_keys=sort_keys,
+    )
+
+
+def inspect(
+    obj: Any,
+    *,
+    console: Optional["Console"] = None,
+    title: Optional[str] = None,
+    help: bool = False,
+    methods: bool = False,
+    docs: bool = True,
+    private: bool = False,
+    dunder: bool = False,
+    sort: bool = True,
+    all: bool = False,
+    value: bool = True,
+) -> None:
+    """Inspect any Python object.
+
+    * inspect() to see summarized info.
+    * inspect(, methods=True) to see methods.
+    * inspect(, help=True) to see full (non-abbreviated) help.
+    * inspect(, private=True) to see private attributes (single underscore).
+    * inspect(, dunder=True) to see attributes beginning with double underscore.
+    * inspect(, all=True) to see all attributes.
+
+    Args:
+        obj (Any): An object to inspect.
+        title (str, optional): Title to display over inspect result, or None use type. Defaults to None.
+        help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.
+        methods (bool, optional): Enable inspection of callables. Defaults to False.
+        docs (bool, optional): Also render doc strings. Defaults to True.
+        private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.
+        dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.
+        sort (bool, optional): Sort attributes alphabetically. Defaults to True.
+        all (bool, optional): Show all attributes. Defaults to False.
+        value (bool, optional): Pretty print value. Defaults to True.
+    """
+    _console = console or get_console()
+    from rich._inspect import Inspect
+
+    # Special case for inspect(inspect)
+    is_inspect = obj is inspect
+
+    _inspect = Inspect(
+        obj,
+        title=title,
+        help=is_inspect or help,
+        methods=is_inspect or methods,
+        docs=is_inspect or docs,
+        private=private,
+        dunder=dunder,
+        sort=sort,
+        all=all,
+        value=value,
+    )
+    _console.print(_inspect)
+
+
+if __name__ == "__main__":  # pragma: no cover
+    print("Hello, **World**")
diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/__main__.py b/data/miniconda3/lib/python3.13/site-packages/rich/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..06683305d7eae7b15152a1a34fd8a3d731c53aec
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/rich/__main__.py
@@ -0,0 +1,245 @@
+import colorsys
+import io
+from time import process_time
+
+from rich import box
+from rich.color import Color
+from rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult
+from rich.markdown import Markdown
+from rich.measure import Measurement
+from rich.pretty import Pretty
+from rich.segment import Segment
+from rich.style import Style
+from rich.syntax import Syntax
+from rich.table import Table
+from rich.text import Text
+
+
+class ColorBox:
+    def __rich_console__(
+        self, console: Console, options: ConsoleOptions
+    ) -> RenderResult:
+        for y in range(0, 5):
+            for x in range(options.max_width):
+                h = x / options.max_width
+                l = 0.1 + ((y / 5) * 0.7)
+                r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)
+                r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0)
+                bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)
+                color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)
+                yield Segment("▄", Style(color=color, bgcolor=bgcolor))
+            yield Segment.line()
+
+    def __rich_measure__(
+        self, console: "Console", options: ConsoleOptions
+    ) -> Measurement:
+        return Measurement(1, options.max_width)
+
+
+def make_test_card() -> Table:
+    """Get a renderable that demonstrates a number of features."""
+    table = Table.grid(padding=1, pad_edge=True)
+    table.title = "Rich features"
+    table.add_column("Feature", no_wrap=True, justify="center", style="bold red")
+    table.add_column("Demonstration")
+
+    color_table = Table(
+        box=None,
+        expand=False,
+        show_header=False,
+        show_edge=False,
+        pad_edge=False,
+    )
+    color_table.add_row(
+        (
+            "✓ [bold green]4-bit color[/]\n"
+            "✓ [bold blue]8-bit color[/]\n"
+            "✓ [bold magenta]Truecolor (16.7 million)[/]\n"
+            "✓ [bold yellow]Dumb terminals[/]\n"
+            "✓ [bold cyan]Automatic color conversion"
+        ),
+        ColorBox(),
+    )
+
+    table.add_row("Colors", color_table)
+
+    table.add_row(
+        "Styles",
+        "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].",
+    )
+
+    lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus."
+    lorem_table = Table.grid(padding=1, collapse_padding=True)
+    lorem_table.pad_edge = False
+    lorem_table.add_row(
+        Text(lorem, justify="left", style="green"),
+        Text(lorem, justify="center", style="yellow"),
+        Text(lorem, justify="right", style="blue"),
+        Text(lorem, justify="full", style="red"),
+    )
+    table.add_row(
+        "Text",
+        Group(
+            Text.from_markup(
+                """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n"""
+            ),
+            lorem_table,
+        ),
+    )
+
+    def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table:
+        table = Table(show_header=False, pad_edge=False, box=None, expand=True)
+        table.add_column("1", ratio=1)
+        table.add_column("2", ratio=1)
+        table.add_row(renderable1, renderable2)
+        return table
+
+    table.add_row(
+        "Asian\nlanguage\nsupport",
+        ":flag_for_china:  该库支持中文,日文和韩文文本!\n:flag_for_japan:  ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea:  이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다",
+    )
+
+    markup_example = (
+        "[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! "
+        ":+1: :apple: :ant: :bear: :baguette_bread: :bus: "
+    )
+    table.add_row("Markup", markup_example)
+
+    example_table = Table(
+        show_edge=False,
+        show_header=True,
+        expand=False,
+        row_styles=["none", "dim"],
+        box=box.SIMPLE,
+    )
+    example_table.add_column("[green]Date", style="green", no_wrap=True)
+    example_table.add_column("[blue]Title", style="blue")
+    example_table.add_column(
+        "[cyan]Production Budget",
+        style="cyan",
+        justify="right",
+        no_wrap=True,
+    )
+    example_table.add_column(
+        "[magenta]Box Office",
+        style="magenta",
+        justify="right",
+        no_wrap=True,
+    )
+    example_table.add_row(
+        "Dec 20, 2019",
+        "Star Wars: The Rise of Skywalker",
+        "$275,000,000",
+        "$375,126,118",
+    )
+    example_table.add_row(
+        "May 25, 2018",
+        "[b]Solo[/]: A Star Wars Story",
+        "$275,000,000",
+        "$393,151,347",
+    )
+    example_table.add_row(
+        "Dec 15, 2017",
+        "Star Wars Ep. VIII: The Last Jedi",
+        "$262,000,000",
+        "[bold]$1,332,539,889[/bold]",
+    )
+    example_table.add_row(
+        "May 19, 1999",
+        "Star Wars Ep. [b]I[/b]: [i]The phantom Menace",
+        "$115,000,000",
+        "$1,027,044,677",
+    )
+
+    table.add_row("Tables", example_table)
+
+    code = '''\
+def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
+    """Iterate and generate a tuple with a flag for last value."""
+    iter_values = iter(values)
+    try:
+        previous_value = next(iter_values)
+    except StopIteration:
+        return
+    for value in iter_values:
+        yield False, previous_value
+        previous_value = value
+    yield True, previous_value'''
+
+    pretty_data = {
+        "foo": [
+            3.1427,
+            (
+                "Paul Atreides",
+                "Vladimir Harkonnen",
+                "Thufir Hawat",
+            ),
+        ],
+        "atomic": (False, True, None),
+    }
+    table.add_row(
+        "Syntax\nhighlighting\n&\npretty\nprinting",
+        comparison(
+            Syntax(code, "python3", line_numbers=True, indent_guides=True),
+            Pretty(pretty_data, indent_guides=True),
+        ),
+    )
+
+    markdown_example = """\
+# Markdown
+
+Supports much of the *markdown* __syntax__!
+
+- Headers
+- Basic formatting: **bold**, *italic*, `code`
+- Block quotes
+- Lists, and more...
+    """
+    table.add_row(
+        "Markdown", comparison("[cyan]" + markdown_example, Markdown(markdown_example))
+    )
+
+    table.add_row(
+        "+more!",
+        """Progress bars, columns, styled logging handler, tracebacks, etc...""",
+    )
+    return table
+
+
+if __name__ == "__main__":  # pragma: no cover
+    from rich.panel import Panel
+
+    console = Console(
+        file=io.StringIO(),
+        force_terminal=True,
+    )
+    test_card = make_test_card()
+
+    # Print once to warm cache
+    start = process_time()
+    console.print(test_card)
+    pre_cache_taken = round((process_time() - start) * 1000.0, 1)
+
+    console.file = io.StringIO()
+
+    start = process_time()
+    console.print(test_card)
+    taken = round((process_time() - start) * 1000.0, 1)
+
+    c = Console(record=True)
+    c.print(test_card)
+
+    console = Console()
+    console.print(f"[dim]rendered in [not dim]{pre_cache_taken}ms[/] (cold cache)")
+    console.print(f"[dim]rendered in [not dim]{taken}ms[/] (warm cache)")
+    console.print()
+    console.print(
+        Panel.fit(
+            "[b magenta]Hope you enjoy using Rich![/]\n\n"
+            "Please consider sponsoring me if you get value from my work.\n\n"
+            "Even the price of a ☕ can brighten my day!\n\n"
+            "https://github.com/sponsors/willmcgugan",
+            border_style="red",
+            title="Help ensure Rich is maintained",
+        )
+    )
diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_cell_widths.py b/data/miniconda3/lib/python3.13/site-packages/rich/_cell_widths.py
new file mode 100644
index 0000000000000000000000000000000000000000..608ae3a75d16ef5af4a6afcc1958b03239f2067e
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/rich/_cell_widths.py
@@ -0,0 +1,454 @@
+# Auto generated by make_terminal_widths.py
+
+CELL_WIDTHS = [
+    (0, 0, 0),
+    (1, 31, -1),
+    (127, 159, -1),
+    (173, 173, 0),
+    (768, 879, 0),
+    (1155, 1161, 0),
+    (1425, 1469, 0),
+    (1471, 1471, 0),
+    (1473, 1474, 0),
+    (1476, 1477, 0),
+    (1479, 1479, 0),
+    (1536, 1541, 0),
+    (1552, 1562, 0),
+    (1564, 1564, 0),
+    (1611, 1631, 0),
+    (1648, 1648, 0),
+    (1750, 1757, 0),
+    (1759, 1764, 0),
+    (1767, 1768, 0),
+    (1770, 1773, 0),
+    (1807, 1807, 0),
+    (1809, 1809, 0),
+    (1840, 1866, 0),
+    (1958, 1968, 0),
+    (2027, 2035, 0),
+    (2045, 2045, 0),
+    (2070, 2073, 0),
+    (2075, 2083, 0),
+    (2085, 2087, 0),
+    (2089, 2093, 0),
+    (2137, 2139, 0),
+    (2192, 2193, 0),
+    (2200, 2207, 0),
+    (2250, 2307, 0),
+    (2362, 2364, 0),
+    (2366, 2383, 0),
+    (2385, 2391, 0),
+    (2402, 2403, 0),
+    (2433, 2435, 0),
+    (2492, 2492, 0),
+    (2494, 2500, 0),
+    (2503, 2504, 0),
+    (2507, 2509, 0),
+    (2519, 2519, 0),
+    (2530, 2531, 0),
+    (2558, 2558, 0),
+    (2561, 2563, 0),
+    (2620, 2620, 0),
+    (2622, 2626, 0),
+    (2631, 2632, 0),
+    (2635, 2637, 0),
+    (2641, 2641, 0),
+    (2672, 2673, 0),
+    (2677, 2677, 0),
+    (2689, 2691, 0),
+    (2748, 2748, 0),
+    (2750, 2757, 0),
+    (2759, 2761, 0),
+    (2763, 2765, 0),
+    (2786, 2787, 0),
+    (2810, 2815, 0),
+    (2817, 2819, 0),
+    (2876, 2876, 0),
+    (2878, 2884, 0),
+    (2887, 2888, 0),
+    (2891, 2893, 0),
+    (2901, 2903, 0),
+    (2914, 2915, 0),
+    (2946, 2946, 0),
+    (3006, 3010, 0),
+    (3014, 3016, 0),
+    (3018, 3021, 0),
+    (3031, 3031, 0),
+    (3072, 3076, 0),
+    (3132, 3132, 0),
+    (3134, 3140, 0),
+    (3142, 3144, 0),
+    (3146, 3149, 0),
+    (3157, 3158, 0),
+    (3170, 3171, 0),
+    (3201, 3203, 0),
+    (3260, 3260, 0),
+    (3262, 3268, 0),
+    (3270, 3272, 0),
+    (3274, 3277, 0),
+    (3285, 3286, 0),
+    (3298, 3299, 0),
+    (3315, 3315, 0),
+    (3328, 3331, 0),
+    (3387, 3388, 0),
+    (3390, 3396, 0),
+    (3398, 3400, 0),
+    (3402, 3405, 0),
+    (3415, 3415, 0),
+    (3426, 3427, 0),
+    (3457, 3459, 0),
+    (3530, 3530, 0),
+    (3535, 3540, 0),
+    (3542, 3542, 0),
+    (3544, 3551, 0),
+    (3570, 3571, 0),
+    (3633, 3633, 0),
+    (3636, 3642, 0),
+    (3655, 3662, 0),
+    (3761, 3761, 0),
+    (3764, 3772, 0),
+    (3784, 3790, 0),
+    (3864, 3865, 0),
+    (3893, 3893, 0),
+    (3895, 3895, 0),
+    (3897, 3897, 0),
+    (3902, 3903, 0),
+    (3953, 3972, 0),
+    (3974, 3975, 0),
+    (3981, 3991, 0),
+    (3993, 4028, 0),
+    (4038, 4038, 0),
+    (4139, 4158, 0),
+    (4182, 4185, 0),
+    (4190, 4192, 0),
+    (4194, 4196, 0),
+    (4199, 4205, 0),
+    (4209, 4212, 0),
+    (4226, 4237, 0),
+    (4239, 4239, 0),
+    (4250, 4253, 0),
+    (4352, 4447, 2),
+    (4448, 4607, 0),
+    (4957, 4959, 0),
+    (5906, 5909, 0),
+    (5938, 5940, 0),
+    (5970, 5971, 0),
+    (6002, 6003, 0),
+    (6068, 6099, 0),
+    (6109, 6109, 0),
+    (6155, 6159, 0),
+    (6277, 6278, 0),
+    (6313, 6313, 0),
+    (6432, 6443, 0),
+    (6448, 6459, 0),
+    (6679, 6683, 0),
+    (6741, 6750, 0),
+    (6752, 6780, 0),
+    (6783, 6783, 0),
+    (6832, 6862, 0),
+    (6912, 6916, 0),
+    (6964, 6980, 0),
+    (7019, 7027, 0),
+    (7040, 7042, 0),
+    (7073, 7085, 0),
+    (7142, 7155, 0),
+    (7204, 7223, 0),
+    (7376, 7378, 0),
+    (7380, 7400, 0),
+    (7405, 7405, 0),
+    (7412, 7412, 0),
+    (7415, 7417, 0),
+    (7616, 7679, 0),
+    (8203, 8207, 0),
+    (8232, 8238, 0),
+    (8288, 8292, 0),
+    (8294, 8303, 0),
+    (8400, 8432, 0),
+    (8986, 8987, 2),
+    (9001, 9002, 2),
+    (9193, 9196, 2),
+    (9200, 9200, 2),
+    (9203, 9203, 2),
+    (9725, 9726, 2),
+    (9748, 9749, 2),
+    (9800, 9811, 2),
+    (9855, 9855, 2),
+    (9875, 9875, 2),
+    (9889, 9889, 2),
+    (9898, 9899, 2),
+    (9917, 9918, 2),
+    (9924, 9925, 2),
+    (9934, 9934, 2),
+    (9940, 9940, 2),
+    (9962, 9962, 2),
+    (9970, 9971, 2),
+    (9973, 9973, 2),
+    (9978, 9978, 2),
+    (9981, 9981, 2),
+    (9989, 9989, 2),
+    (9994, 9995, 2),
+    (10024, 10024, 2),
+    (10060, 10060, 2),
+    (10062, 10062, 2),
+    (10067, 10069, 2),
+    (10071, 10071, 2),
+    (10133, 10135, 2),
+    (10160, 10160, 2),
+    (10175, 10175, 2),
+    (11035, 11036, 2),
+    (11088, 11088, 2),
+    (11093, 11093, 2),
+    (11503, 11505, 0),
+    (11647, 11647, 0),
+    (11744, 11775, 0),
+    (11904, 11929, 2),
+    (11931, 12019, 2),
+    (12032, 12245, 2),
+    (12272, 12329, 2),
+    (12330, 12335, 0),
+    (12336, 12350, 2),
+    (12353, 12438, 2),
+    (12441, 12442, 0),
+    (12443, 12543, 2),
+    (12549, 12591, 2),
+    (12593, 12686, 2),
+    (12688, 12771, 2),
+    (12783, 12830, 2),
+    (12832, 12871, 2),
+    (12880, 19903, 2),
+    (19968, 42124, 2),
+    (42128, 42182, 2),
+    (42607, 42610, 0),
+    (42612, 42621, 0),
+    (42654, 42655, 0),
+    (42736, 42737, 0),
+    (43010, 43010, 0),
+    (43014, 43014, 0),
+    (43019, 43019, 0),
+    (43043, 43047, 0),
+    (43052, 43052, 0),
+    (43136, 43137, 0),
+    (43188, 43205, 0),
+    (43232, 43249, 0),
+    (43263, 43263, 0),
+    (43302, 43309, 0),
+    (43335, 43347, 0),
+    (43360, 43388, 2),
+    (43392, 43395, 0),
+    (43443, 43456, 0),
+    (43493, 43493, 0),
+    (43561, 43574, 0),
+    (43587, 43587, 0),
+    (43596, 43597, 0),
+    (43643, 43645, 0),
+    (43696, 43696, 0),
+    (43698, 43700, 0),
+    (43703, 43704, 0),
+    (43710, 43711, 0),
+    (43713, 43713, 0),
+    (43755, 43759, 0),
+    (43765, 43766, 0),
+    (44003, 44010, 0),
+    (44012, 44013, 0),
+    (44032, 55203, 2),
+    (55216, 55295, 0),
+    (63744, 64255, 2),
+    (64286, 64286, 0),
+    (65024, 65039, 0),
+    (65040, 65049, 2),
+    (65056, 65071, 0),
+    (65072, 65106, 2),
+    (65108, 65126, 2),
+    (65128, 65131, 2),
+    (65279, 65279, 0),
+    (65281, 65376, 2),
+    (65504, 65510, 2),
+    (65529, 65531, 0),
+    (66045, 66045, 0),
+    (66272, 66272, 0),
+    (66422, 66426, 0),
+    (68097, 68099, 0),
+    (68101, 68102, 0),
+    (68108, 68111, 0),
+    (68152, 68154, 0),
+    (68159, 68159, 0),
+    (68325, 68326, 0),
+    (68900, 68903, 0),
+    (69291, 69292, 0),
+    (69373, 69375, 0),
+    (69446, 69456, 0),
+    (69506, 69509, 0),
+    (69632, 69634, 0),
+    (69688, 69702, 0),
+    (69744, 69744, 0),
+    (69747, 69748, 0),
+    (69759, 69762, 0),
+    (69808, 69818, 0),
+    (69821, 69821, 0),
+    (69826, 69826, 0),
+    (69837, 69837, 0),
+    (69888, 69890, 0),
+    (69927, 69940, 0),
+    (69957, 69958, 0),
+    (70003, 70003, 0),
+    (70016, 70018, 0),
+    (70067, 70080, 0),
+    (70089, 70092, 0),
+    (70094, 70095, 0),
+    (70188, 70199, 0),
+    (70206, 70206, 0),
+    (70209, 70209, 0),
+    (70367, 70378, 0),
+    (70400, 70403, 0),
+    (70459, 70460, 0),
+    (70462, 70468, 0),
+    (70471, 70472, 0),
+    (70475, 70477, 0),
+    (70487, 70487, 0),
+    (70498, 70499, 0),
+    (70502, 70508, 0),
+    (70512, 70516, 0),
+    (70709, 70726, 0),
+    (70750, 70750, 0),
+    (70832, 70851, 0),
+    (71087, 71093, 0),
+    (71096, 71104, 0),
+    (71132, 71133, 0),
+    (71216, 71232, 0),
+    (71339, 71351, 0),
+    (71453, 71467, 0),
+    (71724, 71738, 0),
+    (71984, 71989, 0),
+    (71991, 71992, 0),
+    (71995, 71998, 0),
+    (72000, 72000, 0),
+    (72002, 72003, 0),
+    (72145, 72151, 0),
+    (72154, 72160, 0),
+    (72164, 72164, 0),
+    (72193, 72202, 0),
+    (72243, 72249, 0),
+    (72251, 72254, 0),
+    (72263, 72263, 0),
+    (72273, 72283, 0),
+    (72330, 72345, 0),
+    (72751, 72758, 0),
+    (72760, 72767, 0),
+    (72850, 72871, 0),
+    (72873, 72886, 0),
+    (73009, 73014, 0),
+    (73018, 73018, 0),
+    (73020, 73021, 0),
+    (73023, 73029, 0),
+    (73031, 73031, 0),
+    (73098, 73102, 0),
+    (73104, 73105, 0),
+    (73107, 73111, 0),
+    (73459, 73462, 0),
+    (73472, 73473, 0),
+    (73475, 73475, 0),
+    (73524, 73530, 0),
+    (73534, 73538, 0),
+    (78896, 78912, 0),
+    (78919, 78933, 0),
+    (92912, 92916, 0),
+    (92976, 92982, 0),
+    (94031, 94031, 0),
+    (94033, 94087, 0),
+    (94095, 94098, 0),
+    (94176, 94179, 2),
+    (94180, 94180, 0),
+    (94192, 94193, 0),
+    (94208, 100343, 2),
+    (100352, 101589, 2),
+    (101632, 101640, 2),
+    (110576, 110579, 2),
+    (110581, 110587, 2),
+    (110589, 110590, 2),
+    (110592, 110882, 2),
+    (110898, 110898, 2),
+    (110928, 110930, 2),
+    (110933, 110933, 2),
+    (110948, 110951, 2),
+    (110960, 111355, 2),
+    (113821, 113822, 0),
+    (113824, 113827, 0),
+    (118528, 118573, 0),
+    (118576, 118598, 0),
+    (119141, 119145, 0),
+    (119149, 119170, 0),
+    (119173, 119179, 0),
+    (119210, 119213, 0),
+    (119362, 119364, 0),
+    (121344, 121398, 0),
+    (121403, 121452, 0),
+    (121461, 121461, 0),
+    (121476, 121476, 0),
+    (121499, 121503, 0),
+    (121505, 121519, 0),
+    (122880, 122886, 0),
+    (122888, 122904, 0),
+    (122907, 122913, 0),
+    (122915, 122916, 0),
+    (122918, 122922, 0),
+    (123023, 123023, 0),
+    (123184, 123190, 0),
+    (123566, 123566, 0),
+    (123628, 123631, 0),
+    (124140, 124143, 0),
+    (125136, 125142, 0),
+    (125252, 125258, 0),
+    (126980, 126980, 2),
+    (127183, 127183, 2),
+    (127374, 127374, 2),
+    (127377, 127386, 2),
+    (127488, 127490, 2),
+    (127504, 127547, 2),
+    (127552, 127560, 2),
+    (127568, 127569, 2),
+    (127584, 127589, 2),
+    (127744, 127776, 2),
+    (127789, 127797, 2),
+    (127799, 127868, 2),
+    (127870, 127891, 2),
+    (127904, 127946, 2),
+    (127951, 127955, 2),
+    (127968, 127984, 2),
+    (127988, 127988, 2),
+    (127992, 127994, 2),
+    (127995, 127999, 0),
+    (128000, 128062, 2),
+    (128064, 128064, 2),
+    (128066, 128252, 2),
+    (128255, 128317, 2),
+    (128331, 128334, 2),
+    (128336, 128359, 2),
+    (128378, 128378, 2),
+    (128405, 128406, 2),
+    (128420, 128420, 2),
+    (128507, 128591, 2),
+    (128640, 128709, 2),
+    (128716, 128716, 2),
+    (128720, 128722, 2),
+    (128725, 128727, 2),
+    (128732, 128735, 2),
+    (128747, 128748, 2),
+    (128756, 128764, 2),
+    (128992, 129003, 2),
+    (129008, 129008, 2),
+    (129292, 129338, 2),
+    (129340, 129349, 2),
+    (129351, 129535, 2),
+    (129648, 129660, 2),
+    (129664, 129672, 2),
+    (129680, 129725, 2),
+    (129727, 129733, 2),
+    (129742, 129755, 2),
+    (129760, 129768, 2),
+    (129776, 129784, 2),
+    (131072, 196605, 2),
+    (196608, 262141, 2),
+    (917505, 917505, 0),
+    (917536, 917631, 0),
+    (917760, 917999, 0),
+]
diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_emoji_codes.py b/data/miniconda3/lib/python3.13/site-packages/rich/_emoji_codes.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f2877bb2bd520253502b1c05bb811bb0d7ef64c
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/rich/_emoji_codes.py
@@ -0,0 +1,3610 @@
+EMOJI = {
+    "1st_place_medal": "🥇",
+    "2nd_place_medal": "🥈",
+    "3rd_place_medal": "🥉",
+    "ab_button_(blood_type)": "🆎",
+    "atm_sign": "🏧",
+    "a_button_(blood_type)": "🅰",
+    "afghanistan": "🇦🇫",
+    "albania": "🇦🇱",
+    "algeria": "🇩🇿",
+    "american_samoa": "🇦🇸",
+    "andorra": "🇦🇩",
+    "angola": "🇦🇴",
+    "anguilla": "🇦🇮",
+    "antarctica": "🇦🇶",
+    "antigua_&_barbuda": "🇦🇬",
+    "aquarius": "♒",
+    "argentina": "🇦🇷",
+    "aries": "♈",
+    "armenia": "🇦🇲",
+    "aruba": "🇦🇼",
+    "ascension_island": "🇦🇨",
+    "australia": "🇦🇺",
+    "austria": "🇦🇹",
+    "azerbaijan": "🇦🇿",
+    "back_arrow": "🔙",
+    "b_button_(blood_type)": "🅱",
+    "bahamas": "🇧🇸",
+    "bahrain": "🇧🇭",
+    "bangladesh": "🇧🇩",
+    "barbados": "🇧🇧",
+    "belarus": "🇧🇾",
+    "belgium": "🇧🇪",
+    "belize": "🇧🇿",
+    "benin": "🇧🇯",
+    "bermuda": "🇧🇲",
+    "bhutan": "🇧🇹",
+    "bolivia": "🇧🇴",
+    "bosnia_&_herzegovina": "🇧🇦",
+    "botswana": "🇧🇼",
+    "bouvet_island": "🇧🇻",
+    "brazil": "🇧🇷",
+    "british_indian_ocean_territory": "🇮🇴",
+    "british_virgin_islands": "🇻🇬",
+    "brunei": "🇧🇳",
+    "bulgaria": "🇧🇬",
+    "burkina_faso": "🇧🇫",
+    "burundi": "🇧🇮",
+    "cl_button": "🆑",
+    "cool_button": "🆒",
+    "cambodia": "🇰🇭",
+    "cameroon": "🇨🇲",
+    "canada": "🇨🇦",
+    "canary_islands": "🇮🇨",
+    "cancer": "♋",
+    "cape_verde": "🇨🇻",
+    "capricorn": "♑",
+    "caribbean_netherlands": "🇧🇶",
+    "cayman_islands": "🇰🇾",
+    "central_african_republic": "🇨🇫",
+    "ceuta_&_melilla": "🇪🇦",
+    "chad": "🇹🇩",
+    "chile": "🇨🇱",
+    "china": "🇨🇳",
+    "christmas_island": "🇨🇽",
+    "christmas_tree": "🎄",
+    "clipperton_island": "🇨🇵",
+    "cocos_(keeling)_islands": "🇨🇨",
+    "colombia": "🇨🇴",
+    "comoros": "🇰🇲",
+    "congo_-_brazzaville": "🇨🇬",
+    "congo_-_kinshasa": "🇨🇩",
+    "cook_islands": "🇨🇰",
+    "costa_rica": "🇨🇷",
+    "croatia": "🇭🇷",
+    "cuba": "🇨🇺",
+    "curaçao": "🇨🇼",
+    "cyprus": "🇨🇾",
+    "czechia": "🇨🇿",
+    "côte_d’ivoire": "🇨🇮",
+    "denmark": "🇩🇰",
+    "diego_garcia": "🇩🇬",
+    "djibouti": "🇩🇯",
+    "dominica": "🇩🇲",
+    "dominican_republic": "🇩🇴",
+    "end_arrow": "🔚",
+    "ecuador": "🇪🇨",
+    "egypt": "🇪🇬",
+    "el_salvador": "🇸🇻",
+    "england": "🏴\U000e0067\U000e0062\U000e0065\U000e006e\U000e0067\U000e007f",
+    "equatorial_guinea": "🇬🇶",
+    "eritrea": "🇪🇷",
+    "estonia": "🇪🇪",
+    "ethiopia": "🇪🇹",
+    "european_union": "🇪🇺",
+    "free_button": "🆓",
+    "falkland_islands": "🇫🇰",
+    "faroe_islands": "🇫🇴",
+    "fiji": "🇫🇯",
+    "finland": "🇫🇮",
+    "france": "🇫🇷",
+    "french_guiana": "🇬🇫",
+    "french_polynesia": "🇵🇫",
+    "french_southern_territories": "🇹🇫",
+    "gabon": "🇬🇦",
+    "gambia": "🇬🇲",
+    "gemini": "♊",
+    "georgia": "🇬🇪",
+    "germany": "🇩🇪",
+    "ghana": "🇬🇭",
+    "gibraltar": "🇬🇮",
+    "greece": "🇬🇷",
+    "greenland": "🇬🇱",
+    "grenada": "🇬🇩",
+    "guadeloupe": "🇬🇵",
+    "guam": "🇬🇺",
+    "guatemala": "🇬🇹",
+    "guernsey": "🇬🇬",
+    "guinea": "🇬🇳",
+    "guinea-bissau": "🇬🇼",
+    "guyana": "🇬🇾",
+    "haiti": "🇭🇹",
+    "heard_&_mcdonald_islands": "🇭🇲",
+    "honduras": "🇭🇳",
+    "hong_kong_sar_china": "🇭🇰",
+    "hungary": "🇭🇺",
+    "id_button": "🆔",
+    "iceland": "🇮🇸",
+    "india": "🇮🇳",
+    "indonesia": "🇮🇩",
+    "iran": "🇮🇷",
+    "iraq": "🇮🇶",
+    "ireland": "🇮🇪",
+    "isle_of_man": "🇮🇲",
+    "israel": "🇮🇱",
+    "italy": "🇮🇹",
+    "jamaica": "🇯🇲",
+    "japan": "🗾",
+    "japanese_acceptable_button": "🉑",
+    "japanese_application_button": "🈸",
+    "japanese_bargain_button": "🉐",
+    "japanese_castle": "🏯",
+    "japanese_congratulations_button": "㊗",
+    "japanese_discount_button": "🈹",
+    "japanese_dolls": "🎎",
+    "japanese_free_of_charge_button": "🈚",
+    "japanese_here_button": "🈁",
+    "japanese_monthly_amount_button": "🈷",
+    "japanese_no_vacancy_button": "🈵",
+    "japanese_not_free_of_charge_button": "🈶",
+    "japanese_open_for_business_button": "🈺",
+    "japanese_passing_grade_button": "🈴",
+    "japanese_post_office": "🏣",
+    "japanese_prohibited_button": "🈲",
+    "japanese_reserved_button": "🈯",
+    "japanese_secret_button": "㊙",
+    "japanese_service_charge_button": "🈂",
+    "japanese_symbol_for_beginner": "🔰",
+    "japanese_vacancy_button": "🈳",
+    "jersey": "🇯🇪",
+    "jordan": "🇯🇴",
+    "kazakhstan": "🇰🇿",
+    "kenya": "🇰🇪",
+    "kiribati": "🇰🇮",
+    "kosovo": "🇽🇰",
+    "kuwait": "🇰🇼",
+    "kyrgyzstan": "🇰🇬",
+    "laos": "🇱🇦",
+    "latvia": "🇱🇻",
+    "lebanon": "🇱🇧",
+    "leo": "♌",
+    "lesotho": "🇱🇸",
+    "liberia": "🇱🇷",
+    "libra": "♎",
+    "libya": "🇱🇾",
+    "liechtenstein": "🇱🇮",
+    "lithuania": "🇱🇹",
+    "luxembourg": "🇱🇺",
+    "macau_sar_china": "🇲🇴",
+    "macedonia": "🇲🇰",
+    "madagascar": "🇲🇬",
+    "malawi": "🇲🇼",
+    "malaysia": "🇲🇾",
+    "maldives": "🇲🇻",
+    "mali": "🇲🇱",
+    "malta": "🇲🇹",
+    "marshall_islands": "🇲🇭",
+    "martinique": "🇲🇶",
+    "mauritania": "🇲🇷",
+    "mauritius": "🇲🇺",
+    "mayotte": "🇾🇹",
+    "mexico": "🇲🇽",
+    "micronesia": "🇫🇲",
+    "moldova": "🇲🇩",
+    "monaco": "🇲🇨",
+    "mongolia": "🇲🇳",
+    "montenegro": "🇲🇪",
+    "montserrat": "🇲🇸",
+    "morocco": "🇲🇦",
+    "mozambique": "🇲🇿",
+    "mrs._claus": "🤶",
+    "mrs._claus_dark_skin_tone": "🤶🏿",
+    "mrs._claus_light_skin_tone": "🤶🏻",
+    "mrs._claus_medium-dark_skin_tone": "🤶🏾",
+    "mrs._claus_medium-light_skin_tone": "🤶🏼",
+    "mrs._claus_medium_skin_tone": "🤶🏽",
+    "myanmar_(burma)": "🇲🇲",
+    "new_button": "🆕",
+    "ng_button": "🆖",
+    "namibia": "🇳🇦",
+    "nauru": "🇳🇷",
+    "nepal": "🇳🇵",
+    "netherlands": "🇳🇱",
+    "new_caledonia": "🇳🇨",
+    "new_zealand": "🇳🇿",
+    "nicaragua": "🇳🇮",
+    "niger": "🇳🇪",
+    "nigeria": "🇳🇬",
+    "niue": "🇳🇺",
+    "norfolk_island": "🇳🇫",
+    "north_korea": "🇰🇵",
+    "northern_mariana_islands": "🇲🇵",
+    "norway": "🇳🇴",
+    "ok_button": "🆗",
+    "ok_hand": "👌",
+    "ok_hand_dark_skin_tone": "👌🏿",
+    "ok_hand_light_skin_tone": "👌🏻",
+    "ok_hand_medium-dark_skin_tone": "👌🏾",
+    "ok_hand_medium-light_skin_tone": "👌🏼",
+    "ok_hand_medium_skin_tone": "👌🏽",
+    "on!_arrow": "🔛",
+    "o_button_(blood_type)": "🅾",
+    "oman": "🇴🇲",
+    "ophiuchus": "⛎",
+    "p_button": "🅿",
+    "pakistan": "🇵🇰",
+    "palau": "🇵🇼",
+    "palestinian_territories": "🇵🇸",
+    "panama": "🇵🇦",
+    "papua_new_guinea": "🇵🇬",
+    "paraguay": "🇵🇾",
+    "peru": "🇵🇪",
+    "philippines": "🇵🇭",
+    "pisces": "♓",
+    "pitcairn_islands": "🇵🇳",
+    "poland": "🇵🇱",
+    "portugal": "🇵🇹",
+    "puerto_rico": "🇵🇷",
+    "qatar": "🇶🇦",
+    "romania": "🇷🇴",
+    "russia": "🇷🇺",
+    "rwanda": "🇷🇼",
+    "réunion": "🇷🇪",
+    "soon_arrow": "🔜",
+    "sos_button": "🆘",
+    "sagittarius": "♐",
+    "samoa": "🇼🇸",
+    "san_marino": "🇸🇲",
+    "santa_claus": "🎅",
+    "santa_claus_dark_skin_tone": "🎅🏿",
+    "santa_claus_light_skin_tone": "🎅🏻",
+    "santa_claus_medium-dark_skin_tone": "🎅🏾",
+    "santa_claus_medium-light_skin_tone": "🎅🏼",
+    "santa_claus_medium_skin_tone": "🎅🏽",
+    "saudi_arabia": "🇸🇦",
+    "scorpio": "♏",
+    "scotland": "🏴\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f",
+    "senegal": "🇸🇳",
+    "serbia": "🇷🇸",
+    "seychelles": "🇸🇨",
+    "sierra_leone": "🇸🇱",
+    "singapore": "🇸🇬",
+    "sint_maarten": "🇸🇽",
+    "slovakia": "🇸🇰",
+    "slovenia": "🇸🇮",
+    "solomon_islands": "🇸🇧",
+    "somalia": "🇸🇴",
+    "south_africa": "🇿🇦",
+    "south_georgia_&_south_sandwich_islands": "🇬🇸",
+    "south_korea": "🇰🇷",
+    "south_sudan": "🇸🇸",
+    "spain": "🇪🇸",
+    "sri_lanka": "🇱🇰",
+    "st._barthélemy": "🇧🇱",
+    "st._helena": "🇸🇭",
+    "st._kitts_&_nevis": "🇰🇳",
+    "st._lucia": "🇱🇨",
+    "st._martin": "🇲🇫",
+    "st._pierre_&_miquelon": "🇵🇲",
+    "st._vincent_&_grenadines": "🇻🇨",
+    "statue_of_liberty": "🗽",
+    "sudan": "🇸🇩",
+    "suriname": "🇸🇷",
+    "svalbard_&_jan_mayen": "🇸🇯",
+    "swaziland": "🇸🇿",
+    "sweden": "🇸🇪",
+    "switzerland": "🇨🇭",
+    "syria": "🇸🇾",
+    "são_tomé_&_príncipe": "🇸🇹",
+    "t-rex": "🦖",
+    "top_arrow": "🔝",
+    "taiwan": "🇹🇼",
+    "tajikistan": "🇹🇯",
+    "tanzania": "🇹🇿",
+    "taurus": "♉",
+    "thailand": "🇹🇭",
+    "timor-leste": "🇹🇱",
+    "togo": "🇹🇬",
+    "tokelau": "🇹🇰",
+    "tokyo_tower": "🗼",
+    "tonga": "🇹🇴",
+    "trinidad_&_tobago": "🇹🇹",
+    "tristan_da_cunha": "🇹🇦",
+    "tunisia": "🇹🇳",
+    "turkey": "🦃",
+    "turkmenistan": "🇹🇲",
+    "turks_&_caicos_islands": "🇹🇨",
+    "tuvalu": "🇹🇻",
+    "u.s._outlying_islands": "🇺🇲",
+    "u.s._virgin_islands": "🇻🇮",
+    "up!_button": "🆙",
+    "uganda": "🇺🇬",
+    "ukraine": "🇺🇦",
+    "united_arab_emirates": "🇦🇪",
+    "united_kingdom": "🇬🇧",
+    "united_nations": "🇺🇳",
+    "united_states": "🇺🇸",
+    "uruguay": "🇺🇾",
+    "uzbekistan": "🇺🇿",
+    "vs_button": "🆚",
+    "vanuatu": "🇻🇺",
+    "vatican_city": "🇻🇦",
+    "venezuela": "🇻🇪",
+    "vietnam": "🇻🇳",
+    "virgo": "♍",
+    "wales": "🏴\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f",
+    "wallis_&_futuna": "🇼🇫",
+    "western_sahara": "🇪🇭",
+    "yemen": "🇾🇪",
+    "zambia": "🇿🇲",
+    "zimbabwe": "🇿🇼",
+    "abacus": "🧮",
+    "adhesive_bandage": "🩹",
+    "admission_tickets": "🎟",
+    "adult": "🧑",
+    "adult_dark_skin_tone": "🧑🏿",
+    "adult_light_skin_tone": "🧑🏻",
+    "adult_medium-dark_skin_tone": "🧑🏾",
+    "adult_medium-light_skin_tone": "🧑🏼",
+    "adult_medium_skin_tone": "🧑🏽",
+    "aerial_tramway": "🚡",
+    "airplane": "✈",
+    "airplane_arrival": "🛬",
+    "airplane_departure": "🛫",
+    "alarm_clock": "⏰",
+    "alembic": "⚗",
+    "alien": "👽",
+    "alien_monster": "👾",
+    "ambulance": "🚑",
+    "american_football": "🏈",
+    "amphora": "🏺",
+    "anchor": "⚓",
+    "anger_symbol": "💢",
+    "angry_face": "😠",
+    "angry_face_with_horns": "👿",
+    "anguished_face": "😧",
+    "ant": "🐜",
+    "antenna_bars": "📶",
+    "anxious_face_with_sweat": "😰",
+    "articulated_lorry": "🚛",
+    "artist_palette": "🎨",
+    "astonished_face": "😲",
+    "atom_symbol": "⚛",
+    "auto_rickshaw": "🛺",
+    "automobile": "🚗",
+    "avocado": "🥑",
+    "axe": "🪓",
+    "baby": "👶",
+    "baby_angel": "👼",
+    "baby_angel_dark_skin_tone": "👼🏿",
+    "baby_angel_light_skin_tone": "👼🏻",
+    "baby_angel_medium-dark_skin_tone": "👼🏾",
+    "baby_angel_medium-light_skin_tone": "👼🏼",
+    "baby_angel_medium_skin_tone": "👼🏽",
+    "baby_bottle": "🍼",
+    "baby_chick": "🐤",
+    "baby_dark_skin_tone": "👶🏿",
+    "baby_light_skin_tone": "👶🏻",
+    "baby_medium-dark_skin_tone": "👶🏾",
+    "baby_medium-light_skin_tone": "👶🏼",
+    "baby_medium_skin_tone": "👶🏽",
+    "baby_symbol": "🚼",
+    "backhand_index_pointing_down": "👇",
+    "backhand_index_pointing_down_dark_skin_tone": "👇🏿",
+    "backhand_index_pointing_down_light_skin_tone": "👇🏻",
+    "backhand_index_pointing_down_medium-dark_skin_tone": "👇🏾",
+    "backhand_index_pointing_down_medium-light_skin_tone": "👇🏼",
+    "backhand_index_pointing_down_medium_skin_tone": "👇🏽",
+    "backhand_index_pointing_left": "👈",
+    "backhand_index_pointing_left_dark_skin_tone": "👈🏿",
+    "backhand_index_pointing_left_light_skin_tone": "👈🏻",
+    "backhand_index_pointing_left_medium-dark_skin_tone": "👈🏾",
+    "backhand_index_pointing_left_medium-light_skin_tone": "👈🏼",
+    "backhand_index_pointing_left_medium_skin_tone": "👈🏽",
+    "backhand_index_pointing_right": "👉",
+    "backhand_index_pointing_right_dark_skin_tone": "👉🏿",
+    "backhand_index_pointing_right_light_skin_tone": "👉🏻",
+    "backhand_index_pointing_right_medium-dark_skin_tone": "👉🏾",
+    "backhand_index_pointing_right_medium-light_skin_tone": "👉🏼",
+    "backhand_index_pointing_right_medium_skin_tone": "👉🏽",
+    "backhand_index_pointing_up": "👆",
+    "backhand_index_pointing_up_dark_skin_tone": "👆🏿",
+    "backhand_index_pointing_up_light_skin_tone": "👆🏻",
+    "backhand_index_pointing_up_medium-dark_skin_tone": "👆🏾",
+    "backhand_index_pointing_up_medium-light_skin_tone": "👆🏼",
+    "backhand_index_pointing_up_medium_skin_tone": "👆🏽",
+    "bacon": "🥓",
+    "badger": "🦡",
+    "badminton": "🏸",
+    "bagel": "🥯",
+    "baggage_claim": "🛄",
+    "baguette_bread": "🥖",
+    "balance_scale": "⚖",
+    "bald": "🦲",
+    "bald_man": "👨\u200d🦲",
+    "bald_woman": "👩\u200d🦲",
+    "ballet_shoes": "🩰",
+    "balloon": "🎈",
+    "ballot_box_with_ballot": "🗳",
+    "ballot_box_with_check": "☑",
+    "banana": "🍌",
+    "banjo": "🪕",
+    "bank": "🏦",
+    "bar_chart": "📊",
+    "barber_pole": "💈",
+    "baseball": "⚾",
+    "basket": "🧺",
+    "basketball": "🏀",
+    "bat": "🦇",
+    "bathtub": "🛁",
+    "battery": "🔋",
+    "beach_with_umbrella": "🏖",
+    "beaming_face_with_smiling_eyes": "😁",
+    "bear_face": "🐻",
+    "bearded_person": "🧔",
+    "bearded_person_dark_skin_tone": "🧔🏿",
+    "bearded_person_light_skin_tone": "🧔🏻",
+    "bearded_person_medium-dark_skin_tone": "🧔🏾",
+    "bearded_person_medium-light_skin_tone": "🧔🏼",
+    "bearded_person_medium_skin_tone": "🧔🏽",
+    "beating_heart": "💓",
+    "bed": "🛏",
+    "beer_mug": "🍺",
+    "bell": "🔔",
+    "bell_with_slash": "🔕",
+    "bellhop_bell": "🛎",
+    "bento_box": "🍱",
+    "beverage_box": "🧃",
+    "bicycle": "🚲",
+    "bikini": "👙",
+    "billed_cap": "🧢",
+    "biohazard": "☣",
+    "bird": "🐦",
+    "birthday_cake": "🎂",
+    "black_circle": "⚫",
+    "black_flag": "🏴",
+    "black_heart": "🖤",
+    "black_large_square": "⬛",
+    "black_medium-small_square": "◾",
+    "black_medium_square": "◼",
+    "black_nib": "✒",
+    "black_small_square": "▪",
+    "black_square_button": "🔲",
+    "blond-haired_man": "👱\u200d♂️",
+    "blond-haired_man_dark_skin_tone": "👱🏿\u200d♂️",
+    "blond-haired_man_light_skin_tone": "👱🏻\u200d♂️",
+    "blond-haired_man_medium-dark_skin_tone": "👱🏾\u200d♂️",
+    "blond-haired_man_medium-light_skin_tone": "👱🏼\u200d♂️",
+    "blond-haired_man_medium_skin_tone": "👱🏽\u200d♂️",
+    "blond-haired_person": "👱",
+    "blond-haired_person_dark_skin_tone": "👱🏿",
+    "blond-haired_person_light_skin_tone": "👱🏻",
+    "blond-haired_person_medium-dark_skin_tone": "👱🏾",
+    "blond-haired_person_medium-light_skin_tone": "👱🏼",
+    "blond-haired_person_medium_skin_tone": "👱🏽",
+    "blond-haired_woman": "👱\u200d♀️",
+    "blond-haired_woman_dark_skin_tone": "👱🏿\u200d♀️",
+    "blond-haired_woman_light_skin_tone": "👱🏻\u200d♀️",
+    "blond-haired_woman_medium-dark_skin_tone": "👱🏾\u200d♀️",
+    "blond-haired_woman_medium-light_skin_tone": "👱🏼\u200d♀️",
+    "blond-haired_woman_medium_skin_tone": "👱🏽\u200d♀️",
+    "blossom": "🌼",
+    "blowfish": "🐡",
+    "blue_book": "📘",
+    "blue_circle": "🔵",
+    "blue_heart": "💙",
+    "blue_square": "🟦",
+    "boar": "🐗",
+    "bomb": "💣",
+    "bone": "🦴",
+    "bookmark": "🔖",
+    "bookmark_tabs": "📑",
+    "books": "📚",
+    "bottle_with_popping_cork": "🍾",
+    "bouquet": "💐",
+    "bow_and_arrow": "🏹",
+    "bowl_with_spoon": "🥣",
+    "bowling": "🎳",
+    "boxing_glove": "🥊",
+    "boy": "👦",
+    "boy_dark_skin_tone": "👦🏿",
+    "boy_light_skin_tone": "👦🏻",
+    "boy_medium-dark_skin_tone": "👦🏾",
+    "boy_medium-light_skin_tone": "👦🏼",
+    "boy_medium_skin_tone": "👦🏽",
+    "brain": "🧠",
+    "bread": "🍞",
+    "breast-feeding": "🤱",
+    "breast-feeding_dark_skin_tone": "🤱🏿",
+    "breast-feeding_light_skin_tone": "🤱🏻",
+    "breast-feeding_medium-dark_skin_tone": "🤱🏾",
+    "breast-feeding_medium-light_skin_tone": "🤱🏼",
+    "breast-feeding_medium_skin_tone": "🤱🏽",
+    "brick": "🧱",
+    "bride_with_veil": "👰",
+    "bride_with_veil_dark_skin_tone": "👰🏿",
+    "bride_with_veil_light_skin_tone": "👰🏻",
+    "bride_with_veil_medium-dark_skin_tone": "👰🏾",
+    "bride_with_veil_medium-light_skin_tone": "👰🏼",
+    "bride_with_veil_medium_skin_tone": "👰🏽",
+    "bridge_at_night": "🌉",
+    "briefcase": "💼",
+    "briefs": "🩲",
+    "bright_button": "🔆",
+    "broccoli": "🥦",
+    "broken_heart": "💔",
+    "broom": "🧹",
+    "brown_circle": "🟤",
+    "brown_heart": "🤎",
+    "brown_square": "🟫",
+    "bug": "🐛",
+    "building_construction": "🏗",
+    "bullet_train": "🚅",
+    "burrito": "🌯",
+    "bus": "🚌",
+    "bus_stop": "🚏",
+    "bust_in_silhouette": "👤",
+    "busts_in_silhouette": "👥",
+    "butter": "🧈",
+    "butterfly": "🦋",
+    "cactus": "🌵",
+    "calendar": "📆",
+    "call_me_hand": "🤙",
+    "call_me_hand_dark_skin_tone": "🤙🏿",
+    "call_me_hand_light_skin_tone": "🤙🏻",
+    "call_me_hand_medium-dark_skin_tone": "🤙🏾",
+    "call_me_hand_medium-light_skin_tone": "🤙🏼",
+    "call_me_hand_medium_skin_tone": "🤙🏽",
+    "camel": "🐫",
+    "camera": "📷",
+    "camera_with_flash": "📸",
+    "camping": "🏕",
+    "candle": "🕯",
+    "candy": "🍬",
+    "canned_food": "🥫",
+    "canoe": "🛶",
+    "card_file_box": "🗃",
+    "card_index": "📇",
+    "card_index_dividers": "🗂",
+    "carousel_horse": "🎠",
+    "carp_streamer": "🎏",
+    "carrot": "🥕",
+    "castle": "🏰",
+    "cat": "🐱",
+    "cat_face": "🐱",
+    "cat_face_with_tears_of_joy": "😹",
+    "cat_face_with_wry_smile": "😼",
+    "chains": "⛓",
+    "chair": "🪑",
+    "chart_decreasing": "📉",
+    "chart_increasing": "📈",
+    "chart_increasing_with_yen": "💹",
+    "cheese_wedge": "🧀",
+    "chequered_flag": "🏁",
+    "cherries": "🍒",
+    "cherry_blossom": "🌸",
+    "chess_pawn": "♟",
+    "chestnut": "🌰",
+    "chicken": "🐔",
+    "child": "🧒",
+    "child_dark_skin_tone": "🧒🏿",
+    "child_light_skin_tone": "🧒🏻",
+    "child_medium-dark_skin_tone": "🧒🏾",
+    "child_medium-light_skin_tone": "🧒🏼",
+    "child_medium_skin_tone": "🧒🏽",
+    "children_crossing": "🚸",
+    "chipmunk": "🐿",
+    "chocolate_bar": "🍫",
+    "chopsticks": "🥢",
+    "church": "⛪",
+    "cigarette": "🚬",
+    "cinema": "🎦",
+    "circled_m": "Ⓜ",
+    "circus_tent": "🎪",
+    "cityscape": "🏙",
+    "cityscape_at_dusk": "🌆",
+    "clamp": "🗜",
+    "clapper_board": "🎬",
+    "clapping_hands": "👏",
+    "clapping_hands_dark_skin_tone": "👏🏿",
+    "clapping_hands_light_skin_tone": "👏🏻",
+    "clapping_hands_medium-dark_skin_tone": "👏🏾",
+    "clapping_hands_medium-light_skin_tone": "👏🏼",
+    "clapping_hands_medium_skin_tone": "👏🏽",
+    "classical_building": "🏛",
+    "clinking_beer_mugs": "🍻",
+    "clinking_glasses": "🥂",
+    "clipboard": "📋",
+    "clockwise_vertical_arrows": "🔃",
+    "closed_book": "📕",
+    "closed_mailbox_with_lowered_flag": "📪",
+    "closed_mailbox_with_raised_flag": "📫",
+    "closed_umbrella": "🌂",
+    "cloud": "☁",
+    "cloud_with_lightning": "🌩",
+    "cloud_with_lightning_and_rain": "⛈",
+    "cloud_with_rain": "🌧",
+    "cloud_with_snow": "🌨",
+    "clown_face": "🤡",
+    "club_suit": "♣",
+    "clutch_bag": "👝",
+    "coat": "🧥",
+    "cocktail_glass": "🍸",
+    "coconut": "🥥",
+    "coffin": "⚰",
+    "cold_face": "🥶",
+    "collision": "💥",
+    "comet": "☄",
+    "compass": "🧭",
+    "computer_disk": "💽",
+    "computer_mouse": "🖱",
+    "confetti_ball": "🎊",
+    "confounded_face": "😖",
+    "confused_face": "😕",
+    "construction": "🚧",
+    "construction_worker": "👷",
+    "construction_worker_dark_skin_tone": "👷🏿",
+    "construction_worker_light_skin_tone": "👷🏻",
+    "construction_worker_medium-dark_skin_tone": "👷🏾",
+    "construction_worker_medium-light_skin_tone": "👷🏼",
+    "construction_worker_medium_skin_tone": "👷🏽",
+    "control_knobs": "🎛",
+    "convenience_store": "🏪",
+    "cooked_rice": "🍚",
+    "cookie": "🍪",
+    "cooking": "🍳",
+    "copyright": "©",
+    "couch_and_lamp": "🛋",
+    "counterclockwise_arrows_button": "🔄",
+    "couple_with_heart": "💑",
+    "couple_with_heart_man_man": "👨\u200d❤️\u200d👨",
+    "couple_with_heart_woman_man": "👩\u200d❤️\u200d👨",
+    "couple_with_heart_woman_woman": "👩\u200d❤️\u200d👩",
+    "cow": "🐮",
+    "cow_face": "🐮",
+    "cowboy_hat_face": "🤠",
+    "crab": "🦀",
+    "crayon": "🖍",
+    "credit_card": "💳",
+    "crescent_moon": "🌙",
+    "cricket": "🦗",
+    "cricket_game": "🏏",
+    "crocodile": "🐊",
+    "croissant": "🥐",
+    "cross_mark": "❌",
+    "cross_mark_button": "❎",
+    "crossed_fingers": "🤞",
+    "crossed_fingers_dark_skin_tone": "🤞🏿",
+    "crossed_fingers_light_skin_tone": "🤞🏻",
+    "crossed_fingers_medium-dark_skin_tone": "🤞🏾",
+    "crossed_fingers_medium-light_skin_tone": "🤞🏼",
+    "crossed_fingers_medium_skin_tone": "🤞🏽",
+    "crossed_flags": "🎌",
+    "crossed_swords": "⚔",
+    "crown": "👑",
+    "crying_cat_face": "😿",
+    "crying_face": "😢",
+    "crystal_ball": "🔮",
+    "cucumber": "🥒",
+    "cupcake": "🧁",
+    "cup_with_straw": "🥤",
+    "curling_stone": "🥌",
+    "curly_hair": "🦱",
+    "curly-haired_man": "👨\u200d🦱",
+    "curly-haired_woman": "👩\u200d🦱",
+    "curly_loop": "➰",
+    "currency_exchange": "💱",
+    "curry_rice": "🍛",
+    "custard": "🍮",
+    "customs": "🛃",
+    "cut_of_meat": "🥩",
+    "cyclone": "🌀",
+    "dagger": "🗡",
+    "dango": "🍡",
+    "dashing_away": "💨",
+    "deaf_person": "🧏",
+    "deciduous_tree": "🌳",
+    "deer": "🦌",
+    "delivery_truck": "🚚",
+    "department_store": "🏬",
+    "derelict_house": "🏚",
+    "desert": "🏜",
+    "desert_island": "🏝",
+    "desktop_computer": "🖥",
+    "detective": "🕵",
+    "detective_dark_skin_tone": "🕵🏿",
+    "detective_light_skin_tone": "🕵🏻",
+    "detective_medium-dark_skin_tone": "🕵🏾",
+    "detective_medium-light_skin_tone": "🕵🏼",
+    "detective_medium_skin_tone": "🕵🏽",
+    "diamond_suit": "♦",
+    "diamond_with_a_dot": "💠",
+    "dim_button": "🔅",
+    "direct_hit": "🎯",
+    "disappointed_face": "😞",
+    "diving_mask": "🤿",
+    "diya_lamp": "🪔",
+    "dizzy": "💫",
+    "dizzy_face": "😵",
+    "dna": "🧬",
+    "dog": "🐶",
+    "dog_face": "🐶",
+    "dollar_banknote": "💵",
+    "dolphin": "🐬",
+    "door": "🚪",
+    "dotted_six-pointed_star": "🔯",
+    "double_curly_loop": "➿",
+    "double_exclamation_mark": "‼",
+    "doughnut": "🍩",
+    "dove": "🕊",
+    "down-left_arrow": "↙",
+    "down-right_arrow": "↘",
+    "down_arrow": "⬇",
+    "downcast_face_with_sweat": "😓",
+    "downwards_button": "🔽",
+    "dragon": "🐉",
+    "dragon_face": "🐲",
+    "dress": "👗",
+    "drooling_face": "🤤",
+    "drop_of_blood": "🩸",
+    "droplet": "💧",
+    "drum": "🥁",
+    "duck": "🦆",
+    "dumpling": "🥟",
+    "dvd": "📀",
+    "e-mail": "📧",
+    "eagle": "🦅",
+    "ear": "👂",
+    "ear_dark_skin_tone": "👂🏿",
+    "ear_light_skin_tone": "👂🏻",
+    "ear_medium-dark_skin_tone": "👂🏾",
+    "ear_medium-light_skin_tone": "👂🏼",
+    "ear_medium_skin_tone": "👂🏽",
+    "ear_of_corn": "🌽",
+    "ear_with_hearing_aid": "🦻",
+    "egg": "🍳",
+    "eggplant": "🍆",
+    "eight-pointed_star": "✴",
+    "eight-spoked_asterisk": "✳",
+    "eight-thirty": "🕣",
+    "eight_o’clock": "🕗",
+    "eject_button": "⏏",
+    "electric_plug": "🔌",
+    "elephant": "🐘",
+    "eleven-thirty": "🕦",
+    "eleven_o’clock": "🕚",
+    "elf": "🧝",
+    "elf_dark_skin_tone": "🧝🏿",
+    "elf_light_skin_tone": "🧝🏻",
+    "elf_medium-dark_skin_tone": "🧝🏾",
+    "elf_medium-light_skin_tone": "🧝🏼",
+    "elf_medium_skin_tone": "🧝🏽",
+    "envelope": "✉",
+    "envelope_with_arrow": "📩",
+    "euro_banknote": "💶",
+    "evergreen_tree": "🌲",
+    "ewe": "🐑",
+    "exclamation_mark": "❗",
+    "exclamation_question_mark": "⁉",
+    "exploding_head": "🤯",
+    "expressionless_face": "😑",
+    "eye": "👁",
+    "eye_in_speech_bubble": "👁️\u200d🗨️",
+    "eyes": "👀",
+    "face_blowing_a_kiss": "😘",
+    "face_savoring_food": "😋",
+    "face_screaming_in_fear": "😱",
+    "face_vomiting": "🤮",
+    "face_with_hand_over_mouth": "🤭",
+    "face_with_head-bandage": "🤕",
+    "face_with_medical_mask": "😷",
+    "face_with_monocle": "🧐",
+    "face_with_open_mouth": "😮",
+    "face_with_raised_eyebrow": "🤨",
+    "face_with_rolling_eyes": "🙄",
+    "face_with_steam_from_nose": "😤",
+    "face_with_symbols_on_mouth": "🤬",
+    "face_with_tears_of_joy": "😂",
+    "face_with_thermometer": "🤒",
+    "face_with_tongue": "😛",
+    "face_without_mouth": "😶",
+    "factory": "🏭",
+    "fairy": "🧚",
+    "fairy_dark_skin_tone": "🧚🏿",
+    "fairy_light_skin_tone": "🧚🏻",
+    "fairy_medium-dark_skin_tone": "🧚🏾",
+    "fairy_medium-light_skin_tone": "🧚🏼",
+    "fairy_medium_skin_tone": "🧚🏽",
+    "falafel": "🧆",
+    "fallen_leaf": "🍂",
+    "family": "👪",
+    "family_man_boy": "👨\u200d👦",
+    "family_man_boy_boy": "👨\u200d👦\u200d👦",
+    "family_man_girl": "👨\u200d👧",
+    "family_man_girl_boy": "👨\u200d👧\u200d👦",
+    "family_man_girl_girl": "👨\u200d👧\u200d👧",
+    "family_man_man_boy": "👨\u200d👨\u200d👦",
+    "family_man_man_boy_boy": "👨\u200d👨\u200d👦\u200d👦",
+    "family_man_man_girl": "👨\u200d👨\u200d👧",
+    "family_man_man_girl_boy": "👨\u200d👨\u200d👧\u200d👦",
+    "family_man_man_girl_girl": "👨\u200d👨\u200d👧\u200d👧",
+    "family_man_woman_boy": "👨\u200d👩\u200d👦",
+    "family_man_woman_boy_boy": "👨\u200d👩\u200d👦\u200d👦",
+    "family_man_woman_girl": "👨\u200d👩\u200d👧",
+    "family_man_woman_girl_boy": "👨\u200d👩\u200d👧\u200d👦",
+    "family_man_woman_girl_girl": "👨\u200d👩\u200d👧\u200d👧",
+    "family_woman_boy": "👩\u200d👦",
+    "family_woman_boy_boy": "👩\u200d👦\u200d👦",
+    "family_woman_girl": "👩\u200d👧",
+    "family_woman_girl_boy": "👩\u200d👧\u200d👦",
+    "family_woman_girl_girl": "👩\u200d👧\u200d👧",
+    "family_woman_woman_boy": "👩\u200d👩\u200d👦",
+    "family_woman_woman_boy_boy": "👩\u200d👩\u200d👦\u200d👦",
+    "family_woman_woman_girl": "👩\u200d👩\u200d👧",
+    "family_woman_woman_girl_boy": "👩\u200d👩\u200d👧\u200d👦",
+    "family_woman_woman_girl_girl": "👩\u200d👩\u200d👧\u200d👧",
+    "fast-forward_button": "⏩",
+    "fast_down_button": "⏬",
+    "fast_reverse_button": "⏪",
+    "fast_up_button": "⏫",
+    "fax_machine": "📠",
+    "fearful_face": "😨",
+    "female_sign": "♀",
+    "ferris_wheel": "🎡",
+    "ferry": "⛴",
+    "field_hockey": "🏑",
+    "file_cabinet": "🗄",
+    "file_folder": "📁",
+    "film_frames": "🎞",
+    "film_projector": "📽",
+    "fire": "🔥",
+    "fire_extinguisher": "🧯",
+    "firecracker": "🧨",
+    "fire_engine": "🚒",
+    "fireworks": "🎆",
+    "first_quarter_moon": "🌓",
+    "first_quarter_moon_face": "🌛",
+    "fish": "🐟",
+    "fish_cake_with_swirl": "🍥",
+    "fishing_pole": "🎣",
+    "five-thirty": "🕠",
+    "five_o’clock": "🕔",
+    "flag_in_hole": "⛳",
+    "flamingo": "🦩",
+    "flashlight": "🔦",
+    "flat_shoe": "🥿",
+    "fleur-de-lis": "⚜",
+    "flexed_biceps": "💪",
+    "flexed_biceps_dark_skin_tone": "💪🏿",
+    "flexed_biceps_light_skin_tone": "💪🏻",
+    "flexed_biceps_medium-dark_skin_tone": "💪🏾",
+    "flexed_biceps_medium-light_skin_tone": "💪🏼",
+    "flexed_biceps_medium_skin_tone": "💪🏽",
+    "floppy_disk": "💾",
+    "flower_playing_cards": "🎴",
+    "flushed_face": "😳",
+    "flying_disc": "🥏",
+    "flying_saucer": "🛸",
+    "fog": "🌫",
+    "foggy": "🌁",
+    "folded_hands": "🙏",
+    "folded_hands_dark_skin_tone": "🙏🏿",
+    "folded_hands_light_skin_tone": "🙏🏻",
+    "folded_hands_medium-dark_skin_tone": "🙏🏾",
+    "folded_hands_medium-light_skin_tone": "🙏🏼",
+    "folded_hands_medium_skin_tone": "🙏🏽",
+    "foot": "🦶",
+    "footprints": "👣",
+    "fork_and_knife": "🍴",
+    "fork_and_knife_with_plate": "🍽",
+    "fortune_cookie": "🥠",
+    "fountain": "⛲",
+    "fountain_pen": "🖋",
+    "four-thirty": "🕟",
+    "four_leaf_clover": "🍀",
+    "four_o’clock": "🕓",
+    "fox_face": "🦊",
+    "framed_picture": "🖼",
+    "french_fries": "🍟",
+    "fried_shrimp": "🍤",
+    "frog_face": "🐸",
+    "front-facing_baby_chick": "🐥",
+    "frowning_face": "☹",
+    "frowning_face_with_open_mouth": "😦",
+    "fuel_pump": "⛽",
+    "full_moon": "🌕",
+    "full_moon_face": "🌝",
+    "funeral_urn": "⚱",
+    "game_die": "🎲",
+    "garlic": "🧄",
+    "gear": "⚙",
+    "gem_stone": "💎",
+    "genie": "🧞",
+    "ghost": "👻",
+    "giraffe": "🦒",
+    "girl": "👧",
+    "girl_dark_skin_tone": "👧🏿",
+    "girl_light_skin_tone": "👧🏻",
+    "girl_medium-dark_skin_tone": "👧🏾",
+    "girl_medium-light_skin_tone": "👧🏼",
+    "girl_medium_skin_tone": "👧🏽",
+    "glass_of_milk": "🥛",
+    "glasses": "👓",
+    "globe_showing_americas": "🌎",
+    "globe_showing_asia-australia": "🌏",
+    "globe_showing_europe-africa": "🌍",
+    "globe_with_meridians": "🌐",
+    "gloves": "🧤",
+    "glowing_star": "🌟",
+    "goal_net": "🥅",
+    "goat": "🐐",
+    "goblin": "👺",
+    "goggles": "🥽",
+    "gorilla": "🦍",
+    "graduation_cap": "🎓",
+    "grapes": "🍇",
+    "green_apple": "🍏",
+    "green_book": "📗",
+    "green_circle": "🟢",
+    "green_heart": "💚",
+    "green_salad": "🥗",
+    "green_square": "🟩",
+    "grimacing_face": "😬",
+    "grinning_cat_face": "😺",
+    "grinning_cat_face_with_smiling_eyes": "😸",
+    "grinning_face": "😀",
+    "grinning_face_with_big_eyes": "😃",
+    "grinning_face_with_smiling_eyes": "😄",
+    "grinning_face_with_sweat": "😅",
+    "grinning_squinting_face": "😆",
+    "growing_heart": "💗",
+    "guard": "💂",
+    "guard_dark_skin_tone": "💂🏿",
+    "guard_light_skin_tone": "💂🏻",
+    "guard_medium-dark_skin_tone": "💂🏾",
+    "guard_medium-light_skin_tone": "💂🏼",
+    "guard_medium_skin_tone": "💂🏽",
+    "guide_dog": "🦮",
+    "guitar": "🎸",
+    "hamburger": "🍔",
+    "hammer": "🔨",
+    "hammer_and_pick": "⚒",
+    "hammer_and_wrench": "🛠",
+    "hamster_face": "🐹",
+    "hand_with_fingers_splayed": "🖐",
+    "hand_with_fingers_splayed_dark_skin_tone": "🖐🏿",
+    "hand_with_fingers_splayed_light_skin_tone": "🖐🏻",
+    "hand_with_fingers_splayed_medium-dark_skin_tone": "🖐🏾",
+    "hand_with_fingers_splayed_medium-light_skin_tone": "🖐🏼",
+    "hand_with_fingers_splayed_medium_skin_tone": "🖐🏽",
+    "handbag": "👜",
+    "handshake": "🤝",
+    "hatching_chick": "🐣",
+    "headphone": "🎧",
+    "hear-no-evil_monkey": "🙉",
+    "heart_decoration": "💟",
+    "heart_suit": "♥",
+    "heart_with_arrow": "💘",
+    "heart_with_ribbon": "💝",
+    "heavy_check_mark": "✔",
+    "heavy_division_sign": "➗",
+    "heavy_dollar_sign": "💲",
+    "heavy_heart_exclamation": "❣",
+    "heavy_large_circle": "⭕",
+    "heavy_minus_sign": "➖",
+    "heavy_multiplication_x": "✖",
+    "heavy_plus_sign": "➕",
+    "hedgehog": "🦔",
+    "helicopter": "🚁",
+    "herb": "🌿",
+    "hibiscus": "🌺",
+    "high-heeled_shoe": "👠",
+    "high-speed_train": "🚄",
+    "high_voltage": "⚡",
+    "hiking_boot": "🥾",
+    "hindu_temple": "🛕",
+    "hippopotamus": "🦛",
+    "hole": "🕳",
+    "honey_pot": "🍯",
+    "honeybee": "🐝",
+    "horizontal_traffic_light": "🚥",
+    "horse": "🐴",
+    "horse_face": "🐴",
+    "horse_racing": "🏇",
+    "horse_racing_dark_skin_tone": "🏇🏿",
+    "horse_racing_light_skin_tone": "🏇🏻",
+    "horse_racing_medium-dark_skin_tone": "🏇🏾",
+    "horse_racing_medium-light_skin_tone": "🏇🏼",
+    "horse_racing_medium_skin_tone": "🏇🏽",
+    "hospital": "🏥",
+    "hot_beverage": "☕",
+    "hot_dog": "🌭",
+    "hot_face": "🥵",
+    "hot_pepper": "🌶",
+    "hot_springs": "♨",
+    "hotel": "🏨",
+    "hourglass_done": "⌛",
+    "hourglass_not_done": "⏳",
+    "house": "🏠",
+    "house_with_garden": "🏡",
+    "houses": "🏘",
+    "hugging_face": "🤗",
+    "hundred_points": "💯",
+    "hushed_face": "😯",
+    "ice": "🧊",
+    "ice_cream": "🍨",
+    "ice_hockey": "🏒",
+    "ice_skate": "⛸",
+    "inbox_tray": "📥",
+    "incoming_envelope": "📨",
+    "index_pointing_up": "☝",
+    "index_pointing_up_dark_skin_tone": "☝🏿",
+    "index_pointing_up_light_skin_tone": "☝🏻",
+    "index_pointing_up_medium-dark_skin_tone": "☝🏾",
+    "index_pointing_up_medium-light_skin_tone": "☝🏼",
+    "index_pointing_up_medium_skin_tone": "☝🏽",
+    "infinity": "♾",
+    "information": "ℹ",
+    "input_latin_letters": "🔤",
+    "input_latin_lowercase": "🔡",
+    "input_latin_uppercase": "🔠",
+    "input_numbers": "🔢",
+    "input_symbols": "🔣",
+    "jack-o-lantern": "🎃",
+    "jeans": "👖",
+    "jigsaw": "🧩",
+    "joker": "🃏",
+    "joystick": "🕹",
+    "kaaba": "🕋",
+    "kangaroo": "🦘",
+    "key": "🔑",
+    "keyboard": "⌨",
+    "keycap_#": "#️⃣",
+    "keycap_*": "*️⃣",
+    "keycap_0": "0️⃣",
+    "keycap_1": "1️⃣",
+    "keycap_10": "🔟",
+    "keycap_2": "2️⃣",
+    "keycap_3": "3️⃣",
+    "keycap_4": "4️⃣",
+    "keycap_5": "5️⃣",
+    "keycap_6": "6️⃣",
+    "keycap_7": "7️⃣",
+    "keycap_8": "8️⃣",
+    "keycap_9": "9️⃣",
+    "kick_scooter": "🛴",
+    "kimono": "👘",
+    "kiss": "💋",
+    "kiss_man_man": "👨\u200d❤️\u200d💋\u200d👨",
+    "kiss_mark": "💋",
+    "kiss_woman_man": "👩\u200d❤️\u200d💋\u200d👨",
+    "kiss_woman_woman": "👩\u200d❤️\u200d💋\u200d👩",
+    "kissing_cat_face": "😽",
+    "kissing_face": "😗",
+    "kissing_face_with_closed_eyes": "😚",
+    "kissing_face_with_smiling_eyes": "😙",
+    "kitchen_knife": "🔪",
+    "kite": "🪁",
+    "kiwi_fruit": "🥝",
+    "koala": "🐨",
+    "lab_coat": "🥼",
+    "label": "🏷",
+    "lacrosse": "🥍",
+    "lady_beetle": "🐞",
+    "laptop_computer": "💻",
+    "large_blue_diamond": "🔷",
+    "large_orange_diamond": "🔶",
+    "last_quarter_moon": "🌗",
+    "last_quarter_moon_face": "🌜",
+    "last_track_button": "⏮",
+    "latin_cross": "✝",
+    "leaf_fluttering_in_wind": "🍃",
+    "leafy_green": "🥬",
+    "ledger": "📒",
+    "left-facing_fist": "🤛",
+    "left-facing_fist_dark_skin_tone": "🤛🏿",
+    "left-facing_fist_light_skin_tone": "🤛🏻",
+    "left-facing_fist_medium-dark_skin_tone": "🤛🏾",
+    "left-facing_fist_medium-light_skin_tone": "🤛🏼",
+    "left-facing_fist_medium_skin_tone": "🤛🏽",
+    "left-right_arrow": "↔",
+    "left_arrow": "⬅",
+    "left_arrow_curving_right": "↪",
+    "left_luggage": "🛅",
+    "left_speech_bubble": "🗨",
+    "leg": "🦵",
+    "lemon": "🍋",
+    "leopard": "🐆",
+    "level_slider": "🎚",
+    "light_bulb": "💡",
+    "light_rail": "🚈",
+    "link": "🔗",
+    "linked_paperclips": "🖇",
+    "lion_face": "🦁",
+    "lipstick": "💄",
+    "litter_in_bin_sign": "🚮",
+    "lizard": "🦎",
+    "llama": "🦙",
+    "lobster": "🦞",
+    "locked": "🔒",
+    "locked_with_key": "🔐",
+    "locked_with_pen": "🔏",
+    "locomotive": "🚂",
+    "lollipop": "🍭",
+    "lotion_bottle": "🧴",
+    "loudly_crying_face": "😭",
+    "loudspeaker": "📢",
+    "love-you_gesture": "🤟",
+    "love-you_gesture_dark_skin_tone": "🤟🏿",
+    "love-you_gesture_light_skin_tone": "🤟🏻",
+    "love-you_gesture_medium-dark_skin_tone": "🤟🏾",
+    "love-you_gesture_medium-light_skin_tone": "🤟🏼",
+    "love-you_gesture_medium_skin_tone": "🤟🏽",
+    "love_hotel": "🏩",
+    "love_letter": "💌",
+    "luggage": "🧳",
+    "lying_face": "🤥",
+    "mage": "🧙",
+    "mage_dark_skin_tone": "🧙🏿",
+    "mage_light_skin_tone": "🧙🏻",
+    "mage_medium-dark_skin_tone": "🧙🏾",
+    "mage_medium-light_skin_tone": "🧙🏼",
+    "mage_medium_skin_tone": "🧙🏽",
+    "magnet": "🧲",
+    "magnifying_glass_tilted_left": "🔍",
+    "magnifying_glass_tilted_right": "🔎",
+    "mahjong_red_dragon": "🀄",
+    "male_sign": "♂",
+    "man": "👨",
+    "man_and_woman_holding_hands": "👫",
+    "man_artist": "👨\u200d🎨",
+    "man_artist_dark_skin_tone": "👨🏿\u200d🎨",
+    "man_artist_light_skin_tone": "👨🏻\u200d🎨",
+    "man_artist_medium-dark_skin_tone": "👨🏾\u200d🎨",
+    "man_artist_medium-light_skin_tone": "👨🏼\u200d🎨",
+    "man_artist_medium_skin_tone": "👨🏽\u200d🎨",
+    "man_astronaut": "👨\u200d🚀",
+    "man_astronaut_dark_skin_tone": "👨🏿\u200d🚀",
+    "man_astronaut_light_skin_tone": "👨🏻\u200d🚀",
+    "man_astronaut_medium-dark_skin_tone": "👨🏾\u200d🚀",
+    "man_astronaut_medium-light_skin_tone": "👨🏼\u200d🚀",
+    "man_astronaut_medium_skin_tone": "👨🏽\u200d🚀",
+    "man_biking": "🚴\u200d♂️",
+    "man_biking_dark_skin_tone": "🚴🏿\u200d♂️",
+    "man_biking_light_skin_tone": "🚴🏻\u200d♂️",
+    "man_biking_medium-dark_skin_tone": "🚴🏾\u200d♂️",
+    "man_biking_medium-light_skin_tone": "🚴🏼\u200d♂️",
+    "man_biking_medium_skin_tone": "🚴🏽\u200d♂️",
+    "man_bouncing_ball": "⛹️\u200d♂️",
+    "man_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♂️",
+    "man_bouncing_ball_light_skin_tone": "⛹🏻\u200d♂️",
+    "man_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♂️",
+    "man_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♂️",
+    "man_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♂️",
+    "man_bowing": "🙇\u200d♂️",
+    "man_bowing_dark_skin_tone": "🙇🏿\u200d♂️",
+    "man_bowing_light_skin_tone": "🙇🏻\u200d♂️",
+    "man_bowing_medium-dark_skin_tone": "🙇🏾\u200d♂️",
+    "man_bowing_medium-light_skin_tone": "🙇🏼\u200d♂️",
+    "man_bowing_medium_skin_tone": "🙇🏽\u200d♂️",
+    "man_cartwheeling": "🤸\u200d♂️",
+    "man_cartwheeling_dark_skin_tone": "🤸🏿\u200d♂️",
+    "man_cartwheeling_light_skin_tone": "🤸🏻\u200d♂️",
+    "man_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♂️",
+    "man_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♂️",
+    "man_cartwheeling_medium_skin_tone": "🤸🏽\u200d♂️",
+    "man_climbing": "🧗\u200d♂️",
+    "man_climbing_dark_skin_tone": "🧗🏿\u200d♂️",
+    "man_climbing_light_skin_tone": "🧗🏻\u200d♂️",
+    "man_climbing_medium-dark_skin_tone": "🧗🏾\u200d♂️",
+    "man_climbing_medium-light_skin_tone": "🧗🏼\u200d♂️",
+    "man_climbing_medium_skin_tone": "🧗🏽\u200d♂️",
+    "man_construction_worker": "👷\u200d♂️",
+    "man_construction_worker_dark_skin_tone": "👷🏿\u200d♂️",
+    "man_construction_worker_light_skin_tone": "👷🏻\u200d♂️",
+    "man_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♂️",
+    "man_construction_worker_medium-light_skin_tone": "👷🏼\u200d♂️",
+    "man_construction_worker_medium_skin_tone": "👷🏽\u200d♂️",
+    "man_cook": "👨\u200d🍳",
+    "man_cook_dark_skin_tone": "👨🏿\u200d🍳",
+    "man_cook_light_skin_tone": "👨🏻\u200d🍳",
+    "man_cook_medium-dark_skin_tone": "👨🏾\u200d🍳",
+    "man_cook_medium-light_skin_tone": "👨🏼\u200d🍳",
+    "man_cook_medium_skin_tone": "👨🏽\u200d🍳",
+    "man_dancing": "🕺",
+    "man_dancing_dark_skin_tone": "🕺🏿",
+    "man_dancing_light_skin_tone": "🕺🏻",
+    "man_dancing_medium-dark_skin_tone": "🕺🏾",
+    "man_dancing_medium-light_skin_tone": "🕺🏼",
+    "man_dancing_medium_skin_tone": "🕺🏽",
+    "man_dark_skin_tone": "👨🏿",
+    "man_detective": "🕵️\u200d♂️",
+    "man_detective_dark_skin_tone": "🕵🏿\u200d♂️",
+    "man_detective_light_skin_tone": "🕵🏻\u200d♂️",
+    "man_detective_medium-dark_skin_tone": "🕵🏾\u200d♂️",
+    "man_detective_medium-light_skin_tone": "🕵🏼\u200d♂️",
+    "man_detective_medium_skin_tone": "🕵🏽\u200d♂️",
+    "man_elf": "🧝\u200d♂️",
+    "man_elf_dark_skin_tone": "🧝🏿\u200d♂️",
+    "man_elf_light_skin_tone": "🧝🏻\u200d♂️",
+    "man_elf_medium-dark_skin_tone": "🧝🏾\u200d♂️",
+    "man_elf_medium-light_skin_tone": "🧝🏼\u200d♂️",
+    "man_elf_medium_skin_tone": "🧝🏽\u200d♂️",
+    "man_facepalming": "🤦\u200d♂️",
+    "man_facepalming_dark_skin_tone": "🤦🏿\u200d♂️",
+    "man_facepalming_light_skin_tone": "🤦🏻\u200d♂️",
+    "man_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♂️",
+    "man_facepalming_medium-light_skin_tone": "🤦🏼\u200d♂️",
+    "man_facepalming_medium_skin_tone": "🤦🏽\u200d♂️",
+    "man_factory_worker": "👨\u200d🏭",
+    "man_factory_worker_dark_skin_tone": "👨🏿\u200d🏭",
+    "man_factory_worker_light_skin_tone": "👨🏻\u200d🏭",
+    "man_factory_worker_medium-dark_skin_tone": "👨🏾\u200d🏭",
+    "man_factory_worker_medium-light_skin_tone": "👨🏼\u200d🏭",
+    "man_factory_worker_medium_skin_tone": "👨🏽\u200d🏭",
+    "man_fairy": "🧚\u200d♂️",
+    "man_fairy_dark_skin_tone": "🧚🏿\u200d♂️",
+    "man_fairy_light_skin_tone": "🧚🏻\u200d♂️",
+    "man_fairy_medium-dark_skin_tone": "🧚🏾\u200d♂️",
+    "man_fairy_medium-light_skin_tone": "🧚🏼\u200d♂️",
+    "man_fairy_medium_skin_tone": "🧚🏽\u200d♂️",
+    "man_farmer": "👨\u200d🌾",
+    "man_farmer_dark_skin_tone": "👨🏿\u200d🌾",
+    "man_farmer_light_skin_tone": "👨🏻\u200d🌾",
+    "man_farmer_medium-dark_skin_tone": "👨🏾\u200d🌾",
+    "man_farmer_medium-light_skin_tone": "👨🏼\u200d🌾",
+    "man_farmer_medium_skin_tone": "👨🏽\u200d🌾",
+    "man_firefighter": "👨\u200d🚒",
+    "man_firefighter_dark_skin_tone": "👨🏿\u200d🚒",
+    "man_firefighter_light_skin_tone": "👨🏻\u200d🚒",
+    "man_firefighter_medium-dark_skin_tone": "👨🏾\u200d🚒",
+    "man_firefighter_medium-light_skin_tone": "👨🏼\u200d🚒",
+    "man_firefighter_medium_skin_tone": "👨🏽\u200d🚒",
+    "man_frowning": "🙍\u200d♂️",
+    "man_frowning_dark_skin_tone": "🙍🏿\u200d♂️",
+    "man_frowning_light_skin_tone": "🙍🏻\u200d♂️",
+    "man_frowning_medium-dark_skin_tone": "🙍🏾\u200d♂️",
+    "man_frowning_medium-light_skin_tone": "🙍🏼\u200d♂️",
+    "man_frowning_medium_skin_tone": "🙍🏽\u200d♂️",
+    "man_genie": "🧞\u200d♂️",
+    "man_gesturing_no": "🙅\u200d♂️",
+    "man_gesturing_no_dark_skin_tone": "🙅🏿\u200d♂️",
+    "man_gesturing_no_light_skin_tone": "🙅🏻\u200d♂️",
+    "man_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♂️",
+    "man_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♂️",
+    "man_gesturing_no_medium_skin_tone": "🙅🏽\u200d♂️",
+    "man_gesturing_ok": "🙆\u200d♂️",
+    "man_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♂️",
+    "man_gesturing_ok_light_skin_tone": "🙆🏻\u200d♂️",
+    "man_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♂️",
+    "man_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♂️",
+    "man_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♂️",
+    "man_getting_haircut": "💇\u200d♂️",
+    "man_getting_haircut_dark_skin_tone": "💇🏿\u200d♂️",
+    "man_getting_haircut_light_skin_tone": "💇🏻\u200d♂️",
+    "man_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♂️",
+    "man_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♂️",
+    "man_getting_haircut_medium_skin_tone": "💇🏽\u200d♂️",
+    "man_getting_massage": "💆\u200d♂️",
+    "man_getting_massage_dark_skin_tone": "💆🏿\u200d♂️",
+    "man_getting_massage_light_skin_tone": "💆🏻\u200d♂️",
+    "man_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♂️",
+    "man_getting_massage_medium-light_skin_tone": "💆🏼\u200d♂️",
+    "man_getting_massage_medium_skin_tone": "💆🏽\u200d♂️",
+    "man_golfing": "🏌️\u200d♂️",
+    "man_golfing_dark_skin_tone": "🏌🏿\u200d♂️",
+    "man_golfing_light_skin_tone": "🏌🏻\u200d♂️",
+    "man_golfing_medium-dark_skin_tone": "🏌🏾\u200d♂️",
+    "man_golfing_medium-light_skin_tone": "🏌🏼\u200d♂️",
+    "man_golfing_medium_skin_tone": "🏌🏽\u200d♂️",
+    "man_guard": "💂\u200d♂️",
+    "man_guard_dark_skin_tone": "💂🏿\u200d♂️",
+    "man_guard_light_skin_tone": "💂🏻\u200d♂️",
+    "man_guard_medium-dark_skin_tone": "💂🏾\u200d♂️",
+    "man_guard_medium-light_skin_tone": "💂🏼\u200d♂️",
+    "man_guard_medium_skin_tone": "💂🏽\u200d♂️",
+    "man_health_worker": "👨\u200d⚕️",
+    "man_health_worker_dark_skin_tone": "👨🏿\u200d⚕️",
+    "man_health_worker_light_skin_tone": "👨🏻\u200d⚕️",
+    "man_health_worker_medium-dark_skin_tone": "👨🏾\u200d⚕️",
+    "man_health_worker_medium-light_skin_tone": "👨🏼\u200d⚕️",
+    "man_health_worker_medium_skin_tone": "👨🏽\u200d⚕️",
+    "man_in_lotus_position": "🧘\u200d♂️",
+    "man_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♂️",
+    "man_in_lotus_position_light_skin_tone": "🧘🏻\u200d♂️",
+    "man_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♂️",
+    "man_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♂️",
+    "man_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♂️",
+    "man_in_manual_wheelchair": "👨\u200d🦽",
+    "man_in_motorized_wheelchair": "👨\u200d🦼",
+    "man_in_steamy_room": "🧖\u200d♂️",
+    "man_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♂️",
+    "man_in_steamy_room_light_skin_tone": "🧖🏻\u200d♂️",
+    "man_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♂️",
+    "man_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♂️",
+    "man_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♂️",
+    "man_in_suit_levitating": "🕴",
+    "man_in_suit_levitating_dark_skin_tone": "🕴🏿",
+    "man_in_suit_levitating_light_skin_tone": "🕴🏻",
+    "man_in_suit_levitating_medium-dark_skin_tone": "🕴🏾",
+    "man_in_suit_levitating_medium-light_skin_tone": "🕴🏼",
+    "man_in_suit_levitating_medium_skin_tone": "🕴🏽",
+    "man_in_tuxedo": "🤵",
+    "man_in_tuxedo_dark_skin_tone": "🤵🏿",
+    "man_in_tuxedo_light_skin_tone": "🤵🏻",
+    "man_in_tuxedo_medium-dark_skin_tone": "🤵🏾",
+    "man_in_tuxedo_medium-light_skin_tone": "🤵🏼",
+    "man_in_tuxedo_medium_skin_tone": "🤵🏽",
+    "man_judge": "👨\u200d⚖️",
+    "man_judge_dark_skin_tone": "👨🏿\u200d⚖️",
+    "man_judge_light_skin_tone": "👨🏻\u200d⚖️",
+    "man_judge_medium-dark_skin_tone": "👨🏾\u200d⚖️",
+    "man_judge_medium-light_skin_tone": "👨🏼\u200d⚖️",
+    "man_judge_medium_skin_tone": "👨🏽\u200d⚖️",
+    "man_juggling": "🤹\u200d♂️",
+    "man_juggling_dark_skin_tone": "🤹🏿\u200d♂️",
+    "man_juggling_light_skin_tone": "🤹🏻\u200d♂️",
+    "man_juggling_medium-dark_skin_tone": "🤹🏾\u200d♂️",
+    "man_juggling_medium-light_skin_tone": "🤹🏼\u200d♂️",
+    "man_juggling_medium_skin_tone": "🤹🏽\u200d♂️",
+    "man_lifting_weights": "🏋️\u200d♂️",
+    "man_lifting_weights_dark_skin_tone": "🏋🏿\u200d♂️",
+    "man_lifting_weights_light_skin_tone": "🏋🏻\u200d♂️",
+    "man_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♂️",
+    "man_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♂️",
+    "man_lifting_weights_medium_skin_tone": "🏋🏽\u200d♂️",
+    "man_light_skin_tone": "👨🏻",
+    "man_mage": "🧙\u200d♂️",
+    "man_mage_dark_skin_tone": "🧙🏿\u200d♂️",
+    "man_mage_light_skin_tone": "🧙🏻\u200d♂️",
+    "man_mage_medium-dark_skin_tone": "🧙🏾\u200d♂️",
+    "man_mage_medium-light_skin_tone": "🧙🏼\u200d♂️",
+    "man_mage_medium_skin_tone": "🧙🏽\u200d♂️",
+    "man_mechanic": "👨\u200d🔧",
+    "man_mechanic_dark_skin_tone": "👨🏿\u200d🔧",
+    "man_mechanic_light_skin_tone": "👨🏻\u200d🔧",
+    "man_mechanic_medium-dark_skin_tone": "👨🏾\u200d🔧",
+    "man_mechanic_medium-light_skin_tone": "👨🏼\u200d🔧",
+    "man_mechanic_medium_skin_tone": "👨🏽\u200d🔧",
+    "man_medium-dark_skin_tone": "👨🏾",
+    "man_medium-light_skin_tone": "👨🏼",
+    "man_medium_skin_tone": "👨🏽",
+    "man_mountain_biking": "🚵\u200d♂️",
+    "man_mountain_biking_dark_skin_tone": "🚵🏿\u200d♂️",
+    "man_mountain_biking_light_skin_tone": "🚵🏻\u200d♂️",
+    "man_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♂️",
+    "man_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♂️",
+    "man_mountain_biking_medium_skin_tone": "🚵🏽\u200d♂️",
+    "man_office_worker": "👨\u200d💼",
+    "man_office_worker_dark_skin_tone": "👨🏿\u200d💼",
+    "man_office_worker_light_skin_tone": "👨🏻\u200d💼",
+    "man_office_worker_medium-dark_skin_tone": "👨🏾\u200d💼",
+    "man_office_worker_medium-light_skin_tone": "👨🏼\u200d💼",
+    "man_office_worker_medium_skin_tone": "👨🏽\u200d💼",
+    "man_pilot": "👨\u200d✈️",
+    "man_pilot_dark_skin_tone": "👨🏿\u200d✈️",
+    "man_pilot_light_skin_tone": "👨🏻\u200d✈️",
+    "man_pilot_medium-dark_skin_tone": "👨🏾\u200d✈️",
+    "man_pilot_medium-light_skin_tone": "👨🏼\u200d✈️",
+    "man_pilot_medium_skin_tone": "👨🏽\u200d✈️",
+    "man_playing_handball": "🤾\u200d♂️",
+    "man_playing_handball_dark_skin_tone": "🤾🏿\u200d♂️",
+    "man_playing_handball_light_skin_tone": "🤾🏻\u200d♂️",
+    "man_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♂️",
+    "man_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♂️",
+    "man_playing_handball_medium_skin_tone": "🤾🏽\u200d♂️",
+    "man_playing_water_polo": "🤽\u200d♂️",
+    "man_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♂️",
+    "man_playing_water_polo_light_skin_tone": "🤽🏻\u200d♂️",
+    "man_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♂️",
+    "man_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♂️",
+    "man_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♂️",
+    "man_police_officer": "👮\u200d♂️",
+    "man_police_officer_dark_skin_tone": "👮🏿\u200d♂️",
+    "man_police_officer_light_skin_tone": "👮🏻\u200d♂️",
+    "man_police_officer_medium-dark_skin_tone": "👮🏾\u200d♂️",
+    "man_police_officer_medium-light_skin_tone": "👮🏼\u200d♂️",
+    "man_police_officer_medium_skin_tone": "👮🏽\u200d♂️",
+    "man_pouting": "🙎\u200d♂️",
+    "man_pouting_dark_skin_tone": "🙎🏿\u200d♂️",
+    "man_pouting_light_skin_tone": "🙎🏻\u200d♂️",
+    "man_pouting_medium-dark_skin_tone": "🙎🏾\u200d♂️",
+    "man_pouting_medium-light_skin_tone": "🙎🏼\u200d♂️",
+    "man_pouting_medium_skin_tone": "🙎🏽\u200d♂️",
+    "man_raising_hand": "🙋\u200d♂️",
+    "man_raising_hand_dark_skin_tone": "🙋🏿\u200d♂️",
+    "man_raising_hand_light_skin_tone": "🙋🏻\u200d♂️",
+    "man_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♂️",
+    "man_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♂️",
+    "man_raising_hand_medium_skin_tone": "🙋🏽\u200d♂️",
+    "man_rowing_boat": "🚣\u200d♂️",
+    "man_rowing_boat_dark_skin_tone": "🚣🏿\u200d♂️",
+    "man_rowing_boat_light_skin_tone": "🚣🏻\u200d♂️",
+    "man_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♂️",
+    "man_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♂️",
+    "man_rowing_boat_medium_skin_tone": "🚣🏽\u200d♂️",
+    "man_running": "🏃\u200d♂️",
+    "man_running_dark_skin_tone": "🏃🏿\u200d♂️",
+    "man_running_light_skin_tone": "🏃🏻\u200d♂️",
+    "man_running_medium-dark_skin_tone": "🏃🏾\u200d♂️",
+    "man_running_medium-light_skin_tone": "🏃🏼\u200d♂️",
+    "man_running_medium_skin_tone": "🏃🏽\u200d♂️",
+    "man_scientist": "👨\u200d🔬",
+    "man_scientist_dark_skin_tone": "👨🏿\u200d🔬",
+    "man_scientist_light_skin_tone": "👨🏻\u200d🔬",
+    "man_scientist_medium-dark_skin_tone": "👨🏾\u200d🔬",
+    "man_scientist_medium-light_skin_tone": "👨🏼\u200d🔬",
+    "man_scientist_medium_skin_tone": "👨🏽\u200d🔬",
+    "man_shrugging": "🤷\u200d♂️",
+    "man_shrugging_dark_skin_tone": "🤷🏿\u200d♂️",
+    "man_shrugging_light_skin_tone": "🤷🏻\u200d♂️",
+    "man_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♂️",
+    "man_shrugging_medium-light_skin_tone": "🤷🏼\u200d♂️",
+    "man_shrugging_medium_skin_tone": "🤷🏽\u200d♂️",
+    "man_singer": "👨\u200d🎤",
+    "man_singer_dark_skin_tone": "👨🏿\u200d🎤",
+    "man_singer_light_skin_tone": "👨🏻\u200d🎤",
+    "man_singer_medium-dark_skin_tone": "👨🏾\u200d🎤",
+    "man_singer_medium-light_skin_tone": "👨🏼\u200d🎤",
+    "man_singer_medium_skin_tone": "👨🏽\u200d🎤",
+    "man_student": "👨\u200d🎓",
+    "man_student_dark_skin_tone": "👨🏿\u200d🎓",
+    "man_student_light_skin_tone": "👨🏻\u200d🎓",
+    "man_student_medium-dark_skin_tone": "👨🏾\u200d🎓",
+    "man_student_medium-light_skin_tone": "👨🏼\u200d🎓",
+    "man_student_medium_skin_tone": "👨🏽\u200d🎓",
+    "man_surfing": "🏄\u200d♂️",
+    "man_surfing_dark_skin_tone": "🏄🏿\u200d♂️",
+    "man_surfing_light_skin_tone": "🏄🏻\u200d♂️",
+    "man_surfing_medium-dark_skin_tone": "🏄🏾\u200d♂️",
+    "man_surfing_medium-light_skin_tone": "🏄🏼\u200d♂️",
+    "man_surfing_medium_skin_tone": "🏄🏽\u200d♂️",
+    "man_swimming": "🏊\u200d♂️",
+    "man_swimming_dark_skin_tone": "🏊🏿\u200d♂️",
+    "man_swimming_light_skin_tone": "🏊🏻\u200d♂️",
+    "man_swimming_medium-dark_skin_tone": "🏊🏾\u200d♂️",
+    "man_swimming_medium-light_skin_tone": "🏊🏼\u200d♂️",
+    "man_swimming_medium_skin_tone": "🏊🏽\u200d♂️",
+    "man_teacher": "👨\u200d🏫",
+    "man_teacher_dark_skin_tone": "👨🏿\u200d🏫",
+    "man_teacher_light_skin_tone": "👨🏻\u200d🏫",
+    "man_teacher_medium-dark_skin_tone": "👨🏾\u200d🏫",
+    "man_teacher_medium-light_skin_tone": "👨🏼\u200d🏫",
+    "man_teacher_medium_skin_tone": "👨🏽\u200d🏫",
+    "man_technologist": "👨\u200d💻",
+    "man_technologist_dark_skin_tone": "👨🏿\u200d💻",
+    "man_technologist_light_skin_tone": "👨🏻\u200d💻",
+    "man_technologist_medium-dark_skin_tone": "👨🏾\u200d💻",
+    "man_technologist_medium-light_skin_tone": "👨🏼\u200d💻",
+    "man_technologist_medium_skin_tone": "👨🏽\u200d💻",
+    "man_tipping_hand": "💁\u200d♂️",
+    "man_tipping_hand_dark_skin_tone": "💁🏿\u200d♂️",
+    "man_tipping_hand_light_skin_tone": "💁🏻\u200d♂️",
+    "man_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♂️",
+    "man_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♂️",
+    "man_tipping_hand_medium_skin_tone": "💁🏽\u200d♂️",
+    "man_vampire": "🧛\u200d♂️",
+    "man_vampire_dark_skin_tone": "🧛🏿\u200d♂️",
+    "man_vampire_light_skin_tone": "🧛🏻\u200d♂️",
+    "man_vampire_medium-dark_skin_tone": "🧛🏾\u200d♂️",
+    "man_vampire_medium-light_skin_tone": "🧛🏼\u200d♂️",
+    "man_vampire_medium_skin_tone": "🧛🏽\u200d♂️",
+    "man_walking": "🚶\u200d♂️",
+    "man_walking_dark_skin_tone": "🚶🏿\u200d♂️",
+    "man_walking_light_skin_tone": "🚶🏻\u200d♂️",
+    "man_walking_medium-dark_skin_tone": "🚶🏾\u200d♂️",
+    "man_walking_medium-light_skin_tone": "🚶🏼\u200d♂️",
+    "man_walking_medium_skin_tone": "🚶🏽\u200d♂️",
+    "man_wearing_turban": "👳\u200d♂️",
+    "man_wearing_turban_dark_skin_tone": "👳🏿\u200d♂️",
+    "man_wearing_turban_light_skin_tone": "👳🏻\u200d♂️",
+    "man_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♂️",
+    "man_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♂️",
+    "man_wearing_turban_medium_skin_tone": "👳🏽\u200d♂️",
+    "man_with_probing_cane": "👨\u200d🦯",
+    "man_with_chinese_cap": "👲",
+    "man_with_chinese_cap_dark_skin_tone": "👲🏿",
+    "man_with_chinese_cap_light_skin_tone": "👲🏻",
+    "man_with_chinese_cap_medium-dark_skin_tone": "👲🏾",
+    "man_with_chinese_cap_medium-light_skin_tone": "👲🏼",
+    "man_with_chinese_cap_medium_skin_tone": "👲🏽",
+    "man_zombie": "🧟\u200d♂️",
+    "mango": "🥭",
+    "mantelpiece_clock": "🕰",
+    "manual_wheelchair": "🦽",
+    "man’s_shoe": "👞",
+    "map_of_japan": "🗾",
+    "maple_leaf": "🍁",
+    "martial_arts_uniform": "🥋",
+    "mate": "🧉",
+    "meat_on_bone": "🍖",
+    "mechanical_arm": "🦾",
+    "mechanical_leg": "🦿",
+    "medical_symbol": "⚕",
+    "megaphone": "📣",
+    "melon": "🍈",
+    "memo": "📝",
+    "men_with_bunny_ears": "👯\u200d♂️",
+    "men_wrestling": "🤼\u200d♂️",
+    "menorah": "🕎",
+    "men’s_room": "🚹",
+    "mermaid": "🧜\u200d♀️",
+    "mermaid_dark_skin_tone": "🧜🏿\u200d♀️",
+    "mermaid_light_skin_tone": "🧜🏻\u200d♀️",
+    "mermaid_medium-dark_skin_tone": "🧜🏾\u200d♀️",
+    "mermaid_medium-light_skin_tone": "🧜🏼\u200d♀️",
+    "mermaid_medium_skin_tone": "🧜🏽\u200d♀️",
+    "merman": "🧜\u200d♂️",
+    "merman_dark_skin_tone": "🧜🏿\u200d♂️",
+    "merman_light_skin_tone": "🧜🏻\u200d♂️",
+    "merman_medium-dark_skin_tone": "🧜🏾\u200d♂️",
+    "merman_medium-light_skin_tone": "🧜🏼\u200d♂️",
+    "merman_medium_skin_tone": "🧜🏽\u200d♂️",
+    "merperson": "🧜",
+    "merperson_dark_skin_tone": "🧜🏿",
+    "merperson_light_skin_tone": "🧜🏻",
+    "merperson_medium-dark_skin_tone": "🧜🏾",
+    "merperson_medium-light_skin_tone": "🧜🏼",
+    "merperson_medium_skin_tone": "🧜🏽",
+    "metro": "🚇",
+    "microbe": "🦠",
+    "microphone": "🎤",
+    "microscope": "🔬",
+    "middle_finger": "🖕",
+    "middle_finger_dark_skin_tone": "🖕🏿",
+    "middle_finger_light_skin_tone": "🖕🏻",
+    "middle_finger_medium-dark_skin_tone": "🖕🏾",
+    "middle_finger_medium-light_skin_tone": "🖕🏼",
+    "middle_finger_medium_skin_tone": "🖕🏽",
+    "military_medal": "🎖",
+    "milky_way": "🌌",
+    "minibus": "🚐",
+    "moai": "🗿",
+    "mobile_phone": "📱",
+    "mobile_phone_off": "📴",
+    "mobile_phone_with_arrow": "📲",
+    "money-mouth_face": "🤑",
+    "money_bag": "💰",
+    "money_with_wings": "💸",
+    "monkey": "🐒",
+    "monkey_face": "🐵",
+    "monorail": "🚝",
+    "moon_cake": "🥮",
+    "moon_viewing_ceremony": "🎑",
+    "mosque": "🕌",
+    "mosquito": "🦟",
+    "motor_boat": "🛥",
+    "motor_scooter": "🛵",
+    "motorcycle": "🏍",
+    "motorized_wheelchair": "🦼",
+    "motorway": "🛣",
+    "mount_fuji": "🗻",
+    "mountain": "⛰",
+    "mountain_cableway": "🚠",
+    "mountain_railway": "🚞",
+    "mouse": "🐭",
+    "mouse_face": "🐭",
+    "mouth": "👄",
+    "movie_camera": "🎥",
+    "mushroom": "🍄",
+    "musical_keyboard": "🎹",
+    "musical_note": "🎵",
+    "musical_notes": "🎶",
+    "musical_score": "🎼",
+    "muted_speaker": "🔇",
+    "nail_polish": "💅",
+    "nail_polish_dark_skin_tone": "💅🏿",
+    "nail_polish_light_skin_tone": "💅🏻",
+    "nail_polish_medium-dark_skin_tone": "💅🏾",
+    "nail_polish_medium-light_skin_tone": "💅🏼",
+    "nail_polish_medium_skin_tone": "💅🏽",
+    "name_badge": "📛",
+    "national_park": "🏞",
+    "nauseated_face": "🤢",
+    "nazar_amulet": "🧿",
+    "necktie": "👔",
+    "nerd_face": "🤓",
+    "neutral_face": "😐",
+    "new_moon": "🌑",
+    "new_moon_face": "🌚",
+    "newspaper": "📰",
+    "next_track_button": "⏭",
+    "night_with_stars": "🌃",
+    "nine-thirty": "🕤",
+    "nine_o’clock": "🕘",
+    "no_bicycles": "🚳",
+    "no_entry": "⛔",
+    "no_littering": "🚯",
+    "no_mobile_phones": "📵",
+    "no_one_under_eighteen": "🔞",
+    "no_pedestrians": "🚷",
+    "no_smoking": "🚭",
+    "non-potable_water": "🚱",
+    "nose": "👃",
+    "nose_dark_skin_tone": "👃🏿",
+    "nose_light_skin_tone": "👃🏻",
+    "nose_medium-dark_skin_tone": "👃🏾",
+    "nose_medium-light_skin_tone": "👃🏼",
+    "nose_medium_skin_tone": "👃🏽",
+    "notebook": "📓",
+    "notebook_with_decorative_cover": "📔",
+    "nut_and_bolt": "🔩",
+    "octopus": "🐙",
+    "oden": "🍢",
+    "office_building": "🏢",
+    "ogre": "👹",
+    "oil_drum": "🛢",
+    "old_key": "🗝",
+    "old_man": "👴",
+    "old_man_dark_skin_tone": "👴🏿",
+    "old_man_light_skin_tone": "👴🏻",
+    "old_man_medium-dark_skin_tone": "👴🏾",
+    "old_man_medium-light_skin_tone": "👴🏼",
+    "old_man_medium_skin_tone": "👴🏽",
+    "old_woman": "👵",
+    "old_woman_dark_skin_tone": "👵🏿",
+    "old_woman_light_skin_tone": "👵🏻",
+    "old_woman_medium-dark_skin_tone": "👵🏾",
+    "old_woman_medium-light_skin_tone": "👵🏼",
+    "old_woman_medium_skin_tone": "👵🏽",
+    "older_adult": "🧓",
+    "older_adult_dark_skin_tone": "🧓🏿",
+    "older_adult_light_skin_tone": "🧓🏻",
+    "older_adult_medium-dark_skin_tone": "🧓🏾",
+    "older_adult_medium-light_skin_tone": "🧓🏼",
+    "older_adult_medium_skin_tone": "🧓🏽",
+    "om": "🕉",
+    "oncoming_automobile": "🚘",
+    "oncoming_bus": "🚍",
+    "oncoming_fist": "👊",
+    "oncoming_fist_dark_skin_tone": "👊🏿",
+    "oncoming_fist_light_skin_tone": "👊🏻",
+    "oncoming_fist_medium-dark_skin_tone": "👊🏾",
+    "oncoming_fist_medium-light_skin_tone": "👊🏼",
+    "oncoming_fist_medium_skin_tone": "👊🏽",
+    "oncoming_police_car": "🚔",
+    "oncoming_taxi": "🚖",
+    "one-piece_swimsuit": "🩱",
+    "one-thirty": "🕜",
+    "one_o’clock": "🕐",
+    "onion": "🧅",
+    "open_book": "📖",
+    "open_file_folder": "📂",
+    "open_hands": "👐",
+    "open_hands_dark_skin_tone": "👐🏿",
+    "open_hands_light_skin_tone": "👐🏻",
+    "open_hands_medium-dark_skin_tone": "👐🏾",
+    "open_hands_medium-light_skin_tone": "👐🏼",
+    "open_hands_medium_skin_tone": "👐🏽",
+    "open_mailbox_with_lowered_flag": "📭",
+    "open_mailbox_with_raised_flag": "📬",
+    "optical_disk": "💿",
+    "orange_book": "📙",
+    "orange_circle": "🟠",
+    "orange_heart": "🧡",
+    "orange_square": "🟧",
+    "orangutan": "🦧",
+    "orthodox_cross": "☦",
+    "otter": "🦦",
+    "outbox_tray": "📤",
+    "owl": "🦉",
+    "ox": "🐂",
+    "oyster": "🦪",
+    "package": "📦",
+    "page_facing_up": "📄",
+    "page_with_curl": "📃",
+    "pager": "📟",
+    "paintbrush": "🖌",
+    "palm_tree": "🌴",
+    "palms_up_together": "🤲",
+    "palms_up_together_dark_skin_tone": "🤲🏿",
+    "palms_up_together_light_skin_tone": "🤲🏻",
+    "palms_up_together_medium-dark_skin_tone": "🤲🏾",
+    "palms_up_together_medium-light_skin_tone": "🤲🏼",
+    "palms_up_together_medium_skin_tone": "🤲🏽",
+    "pancakes": "🥞",
+    "panda_face": "🐼",
+    "paperclip": "📎",
+    "parrot": "🦜",
+    "part_alternation_mark": "〽",
+    "party_popper": "🎉",
+    "partying_face": "🥳",
+    "passenger_ship": "🛳",
+    "passport_control": "🛂",
+    "pause_button": "⏸",
+    "paw_prints": "🐾",
+    "peace_symbol": "☮",
+    "peach": "🍑",
+    "peacock": "🦚",
+    "peanuts": "🥜",
+    "pear": "🍐",
+    "pen": "🖊",
+    "pencil": "📝",
+    "penguin": "🐧",
+    "pensive_face": "😔",
+    "people_holding_hands": "🧑\u200d🤝\u200d🧑",
+    "people_with_bunny_ears": "👯",
+    "people_wrestling": "🤼",
+    "performing_arts": "🎭",
+    "persevering_face": "😣",
+    "person_biking": "🚴",
+    "person_biking_dark_skin_tone": "🚴🏿",
+    "person_biking_light_skin_tone": "🚴🏻",
+    "person_biking_medium-dark_skin_tone": "🚴🏾",
+    "person_biking_medium-light_skin_tone": "🚴🏼",
+    "person_biking_medium_skin_tone": "🚴🏽",
+    "person_bouncing_ball": "⛹",
+    "person_bouncing_ball_dark_skin_tone": "⛹🏿",
+    "person_bouncing_ball_light_skin_tone": "⛹🏻",
+    "person_bouncing_ball_medium-dark_skin_tone": "⛹🏾",
+    "person_bouncing_ball_medium-light_skin_tone": "⛹🏼",
+    "person_bouncing_ball_medium_skin_tone": "⛹🏽",
+    "person_bowing": "🙇",
+    "person_bowing_dark_skin_tone": "🙇🏿",
+    "person_bowing_light_skin_tone": "🙇🏻",
+    "person_bowing_medium-dark_skin_tone": "🙇🏾",
+    "person_bowing_medium-light_skin_tone": "🙇🏼",
+    "person_bowing_medium_skin_tone": "🙇🏽",
+    "person_cartwheeling": "🤸",
+    "person_cartwheeling_dark_skin_tone": "🤸🏿",
+    "person_cartwheeling_light_skin_tone": "🤸🏻",
+    "person_cartwheeling_medium-dark_skin_tone": "🤸🏾",
+    "person_cartwheeling_medium-light_skin_tone": "🤸🏼",
+    "person_cartwheeling_medium_skin_tone": "🤸🏽",
+    "person_climbing": "🧗",
+    "person_climbing_dark_skin_tone": "🧗🏿",
+    "person_climbing_light_skin_tone": "🧗🏻",
+    "person_climbing_medium-dark_skin_tone": "🧗🏾",
+    "person_climbing_medium-light_skin_tone": "🧗🏼",
+    "person_climbing_medium_skin_tone": "🧗🏽",
+    "person_facepalming": "🤦",
+    "person_facepalming_dark_skin_tone": "🤦🏿",
+    "person_facepalming_light_skin_tone": "🤦🏻",
+    "person_facepalming_medium-dark_skin_tone": "🤦🏾",
+    "person_facepalming_medium-light_skin_tone": "🤦🏼",
+    "person_facepalming_medium_skin_tone": "🤦🏽",
+    "person_fencing": "🤺",
+    "person_frowning": "🙍",
+    "person_frowning_dark_skin_tone": "🙍🏿",
+    "person_frowning_light_skin_tone": "🙍🏻",
+    "person_frowning_medium-dark_skin_tone": "🙍🏾",
+    "person_frowning_medium-light_skin_tone": "🙍🏼",
+    "person_frowning_medium_skin_tone": "🙍🏽",
+    "person_gesturing_no": "🙅",
+    "person_gesturing_no_dark_skin_tone": "🙅🏿",
+    "person_gesturing_no_light_skin_tone": "🙅🏻",
+    "person_gesturing_no_medium-dark_skin_tone": "🙅🏾",
+    "person_gesturing_no_medium-light_skin_tone": "🙅🏼",
+    "person_gesturing_no_medium_skin_tone": "🙅🏽",
+    "person_gesturing_ok": "🙆",
+    "person_gesturing_ok_dark_skin_tone": "🙆🏿",
+    "person_gesturing_ok_light_skin_tone": "🙆🏻",
+    "person_gesturing_ok_medium-dark_skin_tone": "🙆🏾",
+    "person_gesturing_ok_medium-light_skin_tone": "🙆🏼",
+    "person_gesturing_ok_medium_skin_tone": "🙆🏽",
+    "person_getting_haircut": "💇",
+    "person_getting_haircut_dark_skin_tone": "💇🏿",
+    "person_getting_haircut_light_skin_tone": "💇🏻",
+    "person_getting_haircut_medium-dark_skin_tone": "💇🏾",
+    "person_getting_haircut_medium-light_skin_tone": "💇🏼",
+    "person_getting_haircut_medium_skin_tone": "💇🏽",
+    "person_getting_massage": "💆",
+    "person_getting_massage_dark_skin_tone": "💆🏿",
+    "person_getting_massage_light_skin_tone": "💆🏻",
+    "person_getting_massage_medium-dark_skin_tone": "💆🏾",
+    "person_getting_massage_medium-light_skin_tone": "💆🏼",
+    "person_getting_massage_medium_skin_tone": "💆🏽",
+    "person_golfing": "🏌",
+    "person_golfing_dark_skin_tone": "🏌🏿",
+    "person_golfing_light_skin_tone": "🏌🏻",
+    "person_golfing_medium-dark_skin_tone": "🏌🏾",
+    "person_golfing_medium-light_skin_tone": "🏌🏼",
+    "person_golfing_medium_skin_tone": "🏌🏽",
+    "person_in_bed": "🛌",
+    "person_in_bed_dark_skin_tone": "🛌🏿",
+    "person_in_bed_light_skin_tone": "🛌🏻",
+    "person_in_bed_medium-dark_skin_tone": "🛌🏾",
+    "person_in_bed_medium-light_skin_tone": "🛌🏼",
+    "person_in_bed_medium_skin_tone": "🛌🏽",
+    "person_in_lotus_position": "🧘",
+    "person_in_lotus_position_dark_skin_tone": "🧘🏿",
+    "person_in_lotus_position_light_skin_tone": "🧘🏻",
+    "person_in_lotus_position_medium-dark_skin_tone": "🧘🏾",
+    "person_in_lotus_position_medium-light_skin_tone": "🧘🏼",
+    "person_in_lotus_position_medium_skin_tone": "🧘🏽",
+    "person_in_steamy_room": "🧖",
+    "person_in_steamy_room_dark_skin_tone": "🧖🏿",
+    "person_in_steamy_room_light_skin_tone": "🧖🏻",
+    "person_in_steamy_room_medium-dark_skin_tone": "🧖🏾",
+    "person_in_steamy_room_medium-light_skin_tone": "🧖🏼",
+    "person_in_steamy_room_medium_skin_tone": "🧖🏽",
+    "person_juggling": "🤹",
+    "person_juggling_dark_skin_tone": "🤹🏿",
+    "person_juggling_light_skin_tone": "🤹🏻",
+    "person_juggling_medium-dark_skin_tone": "🤹🏾",
+    "person_juggling_medium-light_skin_tone": "🤹🏼",
+    "person_juggling_medium_skin_tone": "🤹🏽",
+    "person_kneeling": "🧎",
+    "person_lifting_weights": "🏋",
+    "person_lifting_weights_dark_skin_tone": "🏋🏿",
+    "person_lifting_weights_light_skin_tone": "🏋🏻",
+    "person_lifting_weights_medium-dark_skin_tone": "🏋🏾",
+    "person_lifting_weights_medium-light_skin_tone": "🏋🏼",
+    "person_lifting_weights_medium_skin_tone": "🏋🏽",
+    "person_mountain_biking": "🚵",
+    "person_mountain_biking_dark_skin_tone": "🚵🏿",
+    "person_mountain_biking_light_skin_tone": "🚵🏻",
+    "person_mountain_biking_medium-dark_skin_tone": "🚵🏾",
+    "person_mountain_biking_medium-light_skin_tone": "🚵🏼",
+    "person_mountain_biking_medium_skin_tone": "🚵🏽",
+    "person_playing_handball": "🤾",
+    "person_playing_handball_dark_skin_tone": "🤾🏿",
+    "person_playing_handball_light_skin_tone": "🤾🏻",
+    "person_playing_handball_medium-dark_skin_tone": "🤾🏾",
+    "person_playing_handball_medium-light_skin_tone": "🤾🏼",
+    "person_playing_handball_medium_skin_tone": "🤾🏽",
+    "person_playing_water_polo": "🤽",
+    "person_playing_water_polo_dark_skin_tone": "🤽🏿",
+    "person_playing_water_polo_light_skin_tone": "🤽🏻",
+    "person_playing_water_polo_medium-dark_skin_tone": "🤽🏾",
+    "person_playing_water_polo_medium-light_skin_tone": "🤽🏼",
+    "person_playing_water_polo_medium_skin_tone": "🤽🏽",
+    "person_pouting": "🙎",
+    "person_pouting_dark_skin_tone": "🙎🏿",
+    "person_pouting_light_skin_tone": "🙎🏻",
+    "person_pouting_medium-dark_skin_tone": "🙎🏾",
+    "person_pouting_medium-light_skin_tone": "🙎🏼",
+    "person_pouting_medium_skin_tone": "🙎🏽",
+    "person_raising_hand": "🙋",
+    "person_raising_hand_dark_skin_tone": "🙋🏿",
+    "person_raising_hand_light_skin_tone": "🙋🏻",
+    "person_raising_hand_medium-dark_skin_tone": "🙋🏾",
+    "person_raising_hand_medium-light_skin_tone": "🙋🏼",
+    "person_raising_hand_medium_skin_tone": "🙋🏽",
+    "person_rowing_boat": "🚣",
+    "person_rowing_boat_dark_skin_tone": "🚣🏿",
+    "person_rowing_boat_light_skin_tone": "🚣🏻",
+    "person_rowing_boat_medium-dark_skin_tone": "🚣🏾",
+    "person_rowing_boat_medium-light_skin_tone": "🚣🏼",
+    "person_rowing_boat_medium_skin_tone": "🚣🏽",
+    "person_running": "🏃",
+    "person_running_dark_skin_tone": "🏃🏿",
+    "person_running_light_skin_tone": "🏃🏻",
+    "person_running_medium-dark_skin_tone": "🏃🏾",
+    "person_running_medium-light_skin_tone": "🏃🏼",
+    "person_running_medium_skin_tone": "🏃🏽",
+    "person_shrugging": "🤷",
+    "person_shrugging_dark_skin_tone": "🤷🏿",
+    "person_shrugging_light_skin_tone": "🤷🏻",
+    "person_shrugging_medium-dark_skin_tone": "🤷🏾",
+    "person_shrugging_medium-light_skin_tone": "🤷🏼",
+    "person_shrugging_medium_skin_tone": "🤷🏽",
+    "person_standing": "🧍",
+    "person_surfing": "🏄",
+    "person_surfing_dark_skin_tone": "🏄🏿",
+    "person_surfing_light_skin_tone": "🏄🏻",
+    "person_surfing_medium-dark_skin_tone": "🏄🏾",
+    "person_surfing_medium-light_skin_tone": "🏄🏼",
+    "person_surfing_medium_skin_tone": "🏄🏽",
+    "person_swimming": "🏊",
+    "person_swimming_dark_skin_tone": "🏊🏿",
+    "person_swimming_light_skin_tone": "🏊🏻",
+    "person_swimming_medium-dark_skin_tone": "🏊🏾",
+    "person_swimming_medium-light_skin_tone": "🏊🏼",
+    "person_swimming_medium_skin_tone": "🏊🏽",
+    "person_taking_bath": "🛀",
+    "person_taking_bath_dark_skin_tone": "🛀🏿",
+    "person_taking_bath_light_skin_tone": "🛀🏻",
+    "person_taking_bath_medium-dark_skin_tone": "🛀🏾",
+    "person_taking_bath_medium-light_skin_tone": "🛀🏼",
+    "person_taking_bath_medium_skin_tone": "🛀🏽",
+    "person_tipping_hand": "💁",
+    "person_tipping_hand_dark_skin_tone": "💁🏿",
+    "person_tipping_hand_light_skin_tone": "💁🏻",
+    "person_tipping_hand_medium-dark_skin_tone": "💁🏾",
+    "person_tipping_hand_medium-light_skin_tone": "💁🏼",
+    "person_tipping_hand_medium_skin_tone": "💁🏽",
+    "person_walking": "🚶",
+    "person_walking_dark_skin_tone": "🚶🏿",
+    "person_walking_light_skin_tone": "🚶🏻",
+    "person_walking_medium-dark_skin_tone": "🚶🏾",
+    "person_walking_medium-light_skin_tone": "🚶🏼",
+    "person_walking_medium_skin_tone": "🚶🏽",
+    "person_wearing_turban": "👳",
+    "person_wearing_turban_dark_skin_tone": "👳🏿",
+    "person_wearing_turban_light_skin_tone": "👳🏻",
+    "person_wearing_turban_medium-dark_skin_tone": "👳🏾",
+    "person_wearing_turban_medium-light_skin_tone": "👳🏼",
+    "person_wearing_turban_medium_skin_tone": "👳🏽",
+    "petri_dish": "🧫",
+    "pick": "⛏",
+    "pie": "🥧",
+    "pig": "🐷",
+    "pig_face": "🐷",
+    "pig_nose": "🐽",
+    "pile_of_poo": "💩",
+    "pill": "💊",
+    "pinching_hand": "🤏",
+    "pine_decoration": "🎍",
+    "pineapple": "🍍",
+    "ping_pong": "🏓",
+    "pirate_flag": "🏴\u200d☠️",
+    "pistol": "🔫",
+    "pizza": "🍕",
+    "place_of_worship": "🛐",
+    "play_button": "▶",
+    "play_or_pause_button": "⏯",
+    "pleading_face": "🥺",
+    "police_car": "🚓",
+    "police_car_light": "🚨",
+    "police_officer": "👮",
+    "police_officer_dark_skin_tone": "👮🏿",
+    "police_officer_light_skin_tone": "👮🏻",
+    "police_officer_medium-dark_skin_tone": "👮🏾",
+    "police_officer_medium-light_skin_tone": "👮🏼",
+    "police_officer_medium_skin_tone": "👮🏽",
+    "poodle": "🐩",
+    "pool_8_ball": "🎱",
+    "popcorn": "🍿",
+    "post_office": "🏣",
+    "postal_horn": "📯",
+    "postbox": "📮",
+    "pot_of_food": "🍲",
+    "potable_water": "🚰",
+    "potato": "🥔",
+    "poultry_leg": "🍗",
+    "pound_banknote": "💷",
+    "pouting_cat_face": "😾",
+    "pouting_face": "😡",
+    "prayer_beads": "📿",
+    "pregnant_woman": "🤰",
+    "pregnant_woman_dark_skin_tone": "🤰🏿",
+    "pregnant_woman_light_skin_tone": "🤰🏻",
+    "pregnant_woman_medium-dark_skin_tone": "🤰🏾",
+    "pregnant_woman_medium-light_skin_tone": "🤰🏼",
+    "pregnant_woman_medium_skin_tone": "🤰🏽",
+    "pretzel": "🥨",
+    "probing_cane": "🦯",
+    "prince": "🤴",
+    "prince_dark_skin_tone": "🤴🏿",
+    "prince_light_skin_tone": "🤴🏻",
+    "prince_medium-dark_skin_tone": "🤴🏾",
+    "prince_medium-light_skin_tone": "🤴🏼",
+    "prince_medium_skin_tone": "🤴🏽",
+    "princess": "👸",
+    "princess_dark_skin_tone": "👸🏿",
+    "princess_light_skin_tone": "👸🏻",
+    "princess_medium-dark_skin_tone": "👸🏾",
+    "princess_medium-light_skin_tone": "👸🏼",
+    "princess_medium_skin_tone": "👸🏽",
+    "printer": "🖨",
+    "prohibited": "🚫",
+    "purple_circle": "🟣",
+    "purple_heart": "💜",
+    "purple_square": "🟪",
+    "purse": "👛",
+    "pushpin": "📌",
+    "question_mark": "❓",
+    "rabbit": "🐰",
+    "rabbit_face": "🐰",
+    "raccoon": "🦝",
+    "racing_car": "🏎",
+    "radio": "📻",
+    "radio_button": "🔘",
+    "radioactive": "☢",
+    "railway_car": "🚃",
+    "railway_track": "🛤",
+    "rainbow": "🌈",
+    "rainbow_flag": "🏳️\u200d🌈",
+    "raised_back_of_hand": "🤚",
+    "raised_back_of_hand_dark_skin_tone": "🤚🏿",
+    "raised_back_of_hand_light_skin_tone": "🤚🏻",
+    "raised_back_of_hand_medium-dark_skin_tone": "🤚🏾",
+    "raised_back_of_hand_medium-light_skin_tone": "🤚🏼",
+    "raised_back_of_hand_medium_skin_tone": "🤚🏽",
+    "raised_fist": "✊",
+    "raised_fist_dark_skin_tone": "✊🏿",
+    "raised_fist_light_skin_tone": "✊🏻",
+    "raised_fist_medium-dark_skin_tone": "✊🏾",
+    "raised_fist_medium-light_skin_tone": "✊🏼",
+    "raised_fist_medium_skin_tone": "✊🏽",
+    "raised_hand": "✋",
+    "raised_hand_dark_skin_tone": "✋🏿",
+    "raised_hand_light_skin_tone": "✋🏻",
+    "raised_hand_medium-dark_skin_tone": "✋🏾",
+    "raised_hand_medium-light_skin_tone": "✋🏼",
+    "raised_hand_medium_skin_tone": "✋🏽",
+    "raising_hands": "🙌",
+    "raising_hands_dark_skin_tone": "🙌🏿",
+    "raising_hands_light_skin_tone": "🙌🏻",
+    "raising_hands_medium-dark_skin_tone": "🙌🏾",
+    "raising_hands_medium-light_skin_tone": "🙌🏼",
+    "raising_hands_medium_skin_tone": "🙌🏽",
+    "ram": "🐏",
+    "rat": "🐀",
+    "razor": "🪒",
+    "ringed_planet": "🪐",
+    "receipt": "🧾",
+    "record_button": "⏺",
+    "recycling_symbol": "♻",
+    "red_apple": "🍎",
+    "red_circle": "🔴",
+    "red_envelope": "🧧",
+    "red_hair": "🦰",
+    "red-haired_man": "👨\u200d🦰",
+    "red-haired_woman": "👩\u200d🦰",
+    "red_heart": "❤",
+    "red_paper_lantern": "🏮",
+    "red_square": "🟥",
+    "red_triangle_pointed_down": "🔻",
+    "red_triangle_pointed_up": "🔺",
+    "registered": "®",
+    "relieved_face": "😌",
+    "reminder_ribbon": "🎗",
+    "repeat_button": "🔁",
+    "repeat_single_button": "🔂",
+    "rescue_worker’s_helmet": "⛑",
+    "restroom": "🚻",
+    "reverse_button": "◀",
+    "revolving_hearts": "💞",
+    "rhinoceros": "🦏",
+    "ribbon": "🎀",
+    "rice_ball": "🍙",
+    "rice_cracker": "🍘",
+    "right-facing_fist": "🤜",
+    "right-facing_fist_dark_skin_tone": "🤜🏿",
+    "right-facing_fist_light_skin_tone": "🤜🏻",
+    "right-facing_fist_medium-dark_skin_tone": "🤜🏾",
+    "right-facing_fist_medium-light_skin_tone": "🤜🏼",
+    "right-facing_fist_medium_skin_tone": "🤜🏽",
+    "right_anger_bubble": "🗯",
+    "right_arrow": "➡",
+    "right_arrow_curving_down": "⤵",
+    "right_arrow_curving_left": "↩",
+    "right_arrow_curving_up": "⤴",
+    "ring": "💍",
+    "roasted_sweet_potato": "🍠",
+    "robot_face": "🤖",
+    "rocket": "🚀",
+    "roll_of_paper": "🧻",
+    "rolled-up_newspaper": "🗞",
+    "roller_coaster": "🎢",
+    "rolling_on_the_floor_laughing": "🤣",
+    "rooster": "🐓",
+    "rose": "🌹",
+    "rosette": "🏵",
+    "round_pushpin": "📍",
+    "rugby_football": "🏉",
+    "running_shirt": "🎽",
+    "running_shoe": "👟",
+    "sad_but_relieved_face": "😥",
+    "safety_pin": "🧷",
+    "safety_vest": "🦺",
+    "salt": "🧂",
+    "sailboat": "⛵",
+    "sake": "🍶",
+    "sandwich": "🥪",
+    "sari": "🥻",
+    "satellite": "📡",
+    "satellite_antenna": "📡",
+    "sauropod": "🦕",
+    "saxophone": "🎷",
+    "scarf": "🧣",
+    "school": "🏫",
+    "school_backpack": "🎒",
+    "scissors": "✂",
+    "scorpion": "🦂",
+    "scroll": "📜",
+    "seat": "💺",
+    "see-no-evil_monkey": "🙈",
+    "seedling": "🌱",
+    "selfie": "🤳",
+    "selfie_dark_skin_tone": "🤳🏿",
+    "selfie_light_skin_tone": "🤳🏻",
+    "selfie_medium-dark_skin_tone": "🤳🏾",
+    "selfie_medium-light_skin_tone": "🤳🏼",
+    "selfie_medium_skin_tone": "🤳🏽",
+    "service_dog": "🐕\u200d🦺",
+    "seven-thirty": "🕢",
+    "seven_o’clock": "🕖",
+    "shallow_pan_of_food": "🥘",
+    "shamrock": "☘",
+    "shark": "🦈",
+    "shaved_ice": "🍧",
+    "sheaf_of_rice": "🌾",
+    "shield": "🛡",
+    "shinto_shrine": "⛩",
+    "ship": "🚢",
+    "shooting_star": "🌠",
+    "shopping_bags": "🛍",
+    "shopping_cart": "🛒",
+    "shortcake": "🍰",
+    "shorts": "🩳",
+    "shower": "🚿",
+    "shrimp": "🦐",
+    "shuffle_tracks_button": "🔀",
+    "shushing_face": "🤫",
+    "sign_of_the_horns": "🤘",
+    "sign_of_the_horns_dark_skin_tone": "🤘🏿",
+    "sign_of_the_horns_light_skin_tone": "🤘🏻",
+    "sign_of_the_horns_medium-dark_skin_tone": "🤘🏾",
+    "sign_of_the_horns_medium-light_skin_tone": "🤘🏼",
+    "sign_of_the_horns_medium_skin_tone": "🤘🏽",
+    "six-thirty": "🕡",
+    "six_o’clock": "🕕",
+    "skateboard": "🛹",
+    "skier": "⛷",
+    "skis": "🎿",
+    "skull": "💀",
+    "skull_and_crossbones": "☠",
+    "skunk": "🦨",
+    "sled": "🛷",
+    "sleeping_face": "😴",
+    "sleepy_face": "😪",
+    "slightly_frowning_face": "🙁",
+    "slightly_smiling_face": "🙂",
+    "slot_machine": "🎰",
+    "sloth": "🦥",
+    "small_airplane": "🛩",
+    "small_blue_diamond": "🔹",
+    "small_orange_diamond": "🔸",
+    "smiling_cat_face_with_heart-eyes": "😻",
+    "smiling_face": "☺",
+    "smiling_face_with_halo": "😇",
+    "smiling_face_with_3_hearts": "🥰",
+    "smiling_face_with_heart-eyes": "😍",
+    "smiling_face_with_horns": "😈",
+    "smiling_face_with_smiling_eyes": "😊",
+    "smiling_face_with_sunglasses": "😎",
+    "smirking_face": "😏",
+    "snail": "🐌",
+    "snake": "🐍",
+    "sneezing_face": "🤧",
+    "snow-capped_mountain": "🏔",
+    "snowboarder": "🏂",
+    "snowboarder_dark_skin_tone": "🏂🏿",
+    "snowboarder_light_skin_tone": "🏂🏻",
+    "snowboarder_medium-dark_skin_tone": "🏂🏾",
+    "snowboarder_medium-light_skin_tone": "🏂🏼",
+    "snowboarder_medium_skin_tone": "🏂🏽",
+    "snowflake": "❄",
+    "snowman": "☃",
+    "snowman_without_snow": "⛄",
+    "soap": "🧼",
+    "soccer_ball": "⚽",
+    "socks": "🧦",
+    "softball": "🥎",
+    "soft_ice_cream": "🍦",
+    "spade_suit": "♠",
+    "spaghetti": "🍝",
+    "sparkle": "❇",
+    "sparkler": "🎇",
+    "sparkles": "✨",
+    "sparkling_heart": "💖",
+    "speak-no-evil_monkey": "🙊",
+    "speaker_high_volume": "🔊",
+    "speaker_low_volume": "🔈",
+    "speaker_medium_volume": "🔉",
+    "speaking_head": "🗣",
+    "speech_balloon": "💬",
+    "speedboat": "🚤",
+    "spider": "🕷",
+    "spider_web": "🕸",
+    "spiral_calendar": "🗓",
+    "spiral_notepad": "🗒",
+    "spiral_shell": "🐚",
+    "spoon": "🥄",
+    "sponge": "🧽",
+    "sport_utility_vehicle": "🚙",
+    "sports_medal": "🏅",
+    "spouting_whale": "🐳",
+    "squid": "🦑",
+    "squinting_face_with_tongue": "😝",
+    "stadium": "🏟",
+    "star-struck": "🤩",
+    "star_and_crescent": "☪",
+    "star_of_david": "✡",
+    "station": "🚉",
+    "steaming_bowl": "🍜",
+    "stethoscope": "🩺",
+    "stop_button": "⏹",
+    "stop_sign": "🛑",
+    "stopwatch": "⏱",
+    "straight_ruler": "📏",
+    "strawberry": "🍓",
+    "studio_microphone": "🎙",
+    "stuffed_flatbread": "🥙",
+    "sun": "☀",
+    "sun_behind_cloud": "⛅",
+    "sun_behind_large_cloud": "🌥",
+    "sun_behind_rain_cloud": "🌦",
+    "sun_behind_small_cloud": "🌤",
+    "sun_with_face": "🌞",
+    "sunflower": "🌻",
+    "sunglasses": "😎",
+    "sunrise": "🌅",
+    "sunrise_over_mountains": "🌄",
+    "sunset": "🌇",
+    "superhero": "🦸",
+    "supervillain": "🦹",
+    "sushi": "🍣",
+    "suspension_railway": "🚟",
+    "swan": "🦢",
+    "sweat_droplets": "💦",
+    "synagogue": "🕍",
+    "syringe": "💉",
+    "t-shirt": "👕",
+    "taco": "🌮",
+    "takeout_box": "🥡",
+    "tanabata_tree": "🎋",
+    "tangerine": "🍊",
+    "taxi": "🚕",
+    "teacup_without_handle": "🍵",
+    "tear-off_calendar": "📆",
+    "teddy_bear": "🧸",
+    "telephone": "☎",
+    "telephone_receiver": "📞",
+    "telescope": "🔭",
+    "television": "📺",
+    "ten-thirty": "🕥",
+    "ten_o’clock": "🕙",
+    "tennis": "🎾",
+    "tent": "⛺",
+    "test_tube": "🧪",
+    "thermometer": "🌡",
+    "thinking_face": "🤔",
+    "thought_balloon": "💭",
+    "thread": "🧵",
+    "three-thirty": "🕞",
+    "three_o’clock": "🕒",
+    "thumbs_down": "👎",
+    "thumbs_down_dark_skin_tone": "👎🏿",
+    "thumbs_down_light_skin_tone": "👎🏻",
+    "thumbs_down_medium-dark_skin_tone": "👎🏾",
+    "thumbs_down_medium-light_skin_tone": "👎🏼",
+    "thumbs_down_medium_skin_tone": "👎🏽",
+    "thumbs_up": "👍",
+    "thumbs_up_dark_skin_tone": "👍🏿",
+    "thumbs_up_light_skin_tone": "👍🏻",
+    "thumbs_up_medium-dark_skin_tone": "👍🏾",
+    "thumbs_up_medium-light_skin_tone": "👍🏼",
+    "thumbs_up_medium_skin_tone": "👍🏽",
+    "ticket": "🎫",
+    "tiger": "🐯",
+    "tiger_face": "🐯",
+    "timer_clock": "⏲",
+    "tired_face": "😫",
+    "toolbox": "🧰",
+    "toilet": "🚽",
+    "tomato": "🍅",
+    "tongue": "👅",
+    "tooth": "🦷",
+    "top_hat": "🎩",
+    "tornado": "🌪",
+    "trackball": "🖲",
+    "tractor": "🚜",
+    "trade_mark": "™",
+    "train": "🚋",
+    "tram": "🚊",
+    "tram_car": "🚋",
+    "triangular_flag": "🚩",
+    "triangular_ruler": "📐",
+    "trident_emblem": "🔱",
+    "trolleybus": "🚎",
+    "trophy": "🏆",
+    "tropical_drink": "🍹",
+    "tropical_fish": "🐠",
+    "trumpet": "🎺",
+    "tulip": "🌷",
+    "tumbler_glass": "🥃",
+    "turtle": "🐢",
+    "twelve-thirty": "🕧",
+    "twelve_o’clock": "🕛",
+    "two-hump_camel": "🐫",
+    "two-thirty": "🕝",
+    "two_hearts": "💕",
+    "two_men_holding_hands": "👬",
+    "two_o’clock": "🕑",
+    "two_women_holding_hands": "👭",
+    "umbrella": "☂",
+    "umbrella_on_ground": "⛱",
+    "umbrella_with_rain_drops": "☔",
+    "unamused_face": "😒",
+    "unicorn_face": "🦄",
+    "unlocked": "🔓",
+    "up-down_arrow": "↕",
+    "up-left_arrow": "↖",
+    "up-right_arrow": "↗",
+    "up_arrow": "⬆",
+    "upside-down_face": "🙃",
+    "upwards_button": "🔼",
+    "vampire": "🧛",
+    "vampire_dark_skin_tone": "🧛🏿",
+    "vampire_light_skin_tone": "🧛🏻",
+    "vampire_medium-dark_skin_tone": "🧛🏾",
+    "vampire_medium-light_skin_tone": "🧛🏼",
+    "vampire_medium_skin_tone": "🧛🏽",
+    "vertical_traffic_light": "🚦",
+    "vibration_mode": "📳",
+    "victory_hand": "✌",
+    "victory_hand_dark_skin_tone": "✌🏿",
+    "victory_hand_light_skin_tone": "✌🏻",
+    "victory_hand_medium-dark_skin_tone": "✌🏾",
+    "victory_hand_medium-light_skin_tone": "✌🏼",
+    "victory_hand_medium_skin_tone": "✌🏽",
+    "video_camera": "📹",
+    "video_game": "🎮",
+    "videocassette": "📼",
+    "violin": "🎻",
+    "volcano": "🌋",
+    "volleyball": "🏐",
+    "vulcan_salute": "🖖",
+    "vulcan_salute_dark_skin_tone": "🖖🏿",
+    "vulcan_salute_light_skin_tone": "🖖🏻",
+    "vulcan_salute_medium-dark_skin_tone": "🖖🏾",
+    "vulcan_salute_medium-light_skin_tone": "🖖🏼",
+    "vulcan_salute_medium_skin_tone": "🖖🏽",
+    "waffle": "🧇",
+    "waning_crescent_moon": "🌘",
+    "waning_gibbous_moon": "🌖",
+    "warning": "⚠",
+    "wastebasket": "🗑",
+    "watch": "⌚",
+    "water_buffalo": "🐃",
+    "water_closet": "🚾",
+    "water_wave": "🌊",
+    "watermelon": "🍉",
+    "waving_hand": "👋",
+    "waving_hand_dark_skin_tone": "👋🏿",
+    "waving_hand_light_skin_tone": "👋🏻",
+    "waving_hand_medium-dark_skin_tone": "👋🏾",
+    "waving_hand_medium-light_skin_tone": "👋🏼",
+    "waving_hand_medium_skin_tone": "👋🏽",
+    "wavy_dash": "〰",
+    "waxing_crescent_moon": "🌒",
+    "waxing_gibbous_moon": "🌔",
+    "weary_cat_face": "🙀",
+    "weary_face": "😩",
+    "wedding": "💒",
+    "whale": "🐳",
+    "wheel_of_dharma": "☸",
+    "wheelchair_symbol": "♿",
+    "white_circle": "⚪",
+    "white_exclamation_mark": "❕",
+    "white_flag": "🏳",
+    "white_flower": "💮",
+    "white_hair": "🦳",
+    "white-haired_man": "👨\u200d🦳",
+    "white-haired_woman": "👩\u200d🦳",
+    "white_heart": "🤍",
+    "white_heavy_check_mark": "✅",
+    "white_large_square": "⬜",
+    "white_medium-small_square": "◽",
+    "white_medium_square": "◻",
+    "white_medium_star": "⭐",
+    "white_question_mark": "❔",
+    "white_small_square": "▫",
+    "white_square_button": "🔳",
+    "wilted_flower": "🥀",
+    "wind_chime": "🎐",
+    "wind_face": "🌬",
+    "wine_glass": "🍷",
+    "winking_face": "😉",
+    "winking_face_with_tongue": "😜",
+    "wolf_face": "🐺",
+    "woman": "👩",
+    "woman_artist": "👩\u200d🎨",
+    "woman_artist_dark_skin_tone": "👩🏿\u200d🎨",
+    "woman_artist_light_skin_tone": "👩🏻\u200d🎨",
+    "woman_artist_medium-dark_skin_tone": "👩🏾\u200d🎨",
+    "woman_artist_medium-light_skin_tone": "👩🏼\u200d🎨",
+    "woman_artist_medium_skin_tone": "👩🏽\u200d🎨",
+    "woman_astronaut": "👩\u200d🚀",
+    "woman_astronaut_dark_skin_tone": "👩🏿\u200d🚀",
+    "woman_astronaut_light_skin_tone": "👩🏻\u200d🚀",
+    "woman_astronaut_medium-dark_skin_tone": "👩🏾\u200d🚀",
+    "woman_astronaut_medium-light_skin_tone": "👩🏼\u200d🚀",
+    "woman_astronaut_medium_skin_tone": "👩🏽\u200d🚀",
+    "woman_biking": "🚴\u200d♀️",
+    "woman_biking_dark_skin_tone": "🚴🏿\u200d♀️",
+    "woman_biking_light_skin_tone": "🚴🏻\u200d♀️",
+    "woman_biking_medium-dark_skin_tone": "🚴🏾\u200d♀️",
+    "woman_biking_medium-light_skin_tone": "🚴🏼\u200d♀️",
+    "woman_biking_medium_skin_tone": "🚴🏽\u200d♀️",
+    "woman_bouncing_ball": "⛹️\u200d♀️",
+    "woman_bouncing_ball_dark_skin_tone": "⛹🏿\u200d♀️",
+    "woman_bouncing_ball_light_skin_tone": "⛹🏻\u200d♀️",
+    "woman_bouncing_ball_medium-dark_skin_tone": "⛹🏾\u200d♀️",
+    "woman_bouncing_ball_medium-light_skin_tone": "⛹🏼\u200d♀️",
+    "woman_bouncing_ball_medium_skin_tone": "⛹🏽\u200d♀️",
+    "woman_bowing": "🙇\u200d♀️",
+    "woman_bowing_dark_skin_tone": "🙇🏿\u200d♀️",
+    "woman_bowing_light_skin_tone": "🙇🏻\u200d♀️",
+    "woman_bowing_medium-dark_skin_tone": "🙇🏾\u200d♀️",
+    "woman_bowing_medium-light_skin_tone": "🙇🏼\u200d♀️",
+    "woman_bowing_medium_skin_tone": "🙇🏽\u200d♀️",
+    "woman_cartwheeling": "🤸\u200d♀️",
+    "woman_cartwheeling_dark_skin_tone": "🤸🏿\u200d♀️",
+    "woman_cartwheeling_light_skin_tone": "🤸🏻\u200d♀️",
+    "woman_cartwheeling_medium-dark_skin_tone": "🤸🏾\u200d♀️",
+    "woman_cartwheeling_medium-light_skin_tone": "🤸🏼\u200d♀️",
+    "woman_cartwheeling_medium_skin_tone": "🤸🏽\u200d♀️",
+    "woman_climbing": "🧗\u200d♀️",
+    "woman_climbing_dark_skin_tone": "🧗🏿\u200d♀️",
+    "woman_climbing_light_skin_tone": "🧗🏻\u200d♀️",
+    "woman_climbing_medium-dark_skin_tone": "🧗🏾\u200d♀️",
+    "woman_climbing_medium-light_skin_tone": "🧗🏼\u200d♀️",
+    "woman_climbing_medium_skin_tone": "🧗🏽\u200d♀️",
+    "woman_construction_worker": "👷\u200d♀️",
+    "woman_construction_worker_dark_skin_tone": "👷🏿\u200d♀️",
+    "woman_construction_worker_light_skin_tone": "👷🏻\u200d♀️",
+    "woman_construction_worker_medium-dark_skin_tone": "👷🏾\u200d♀️",
+    "woman_construction_worker_medium-light_skin_tone": "👷🏼\u200d♀️",
+    "woman_construction_worker_medium_skin_tone": "👷🏽\u200d♀️",
+    "woman_cook": "👩\u200d🍳",
+    "woman_cook_dark_skin_tone": "👩🏿\u200d🍳",
+    "woman_cook_light_skin_tone": "👩🏻\u200d🍳",
+    "woman_cook_medium-dark_skin_tone": "👩🏾\u200d🍳",
+    "woman_cook_medium-light_skin_tone": "👩🏼\u200d🍳",
+    "woman_cook_medium_skin_tone": "👩🏽\u200d🍳",
+    "woman_dancing": "💃",
+    "woman_dancing_dark_skin_tone": "💃🏿",
+    "woman_dancing_light_skin_tone": "💃🏻",
+    "woman_dancing_medium-dark_skin_tone": "💃🏾",
+    "woman_dancing_medium-light_skin_tone": "💃🏼",
+    "woman_dancing_medium_skin_tone": "💃🏽",
+    "woman_dark_skin_tone": "👩🏿",
+    "woman_detective": "🕵️\u200d♀️",
+    "woman_detective_dark_skin_tone": "🕵🏿\u200d♀️",
+    "woman_detective_light_skin_tone": "🕵🏻\u200d♀️",
+    "woman_detective_medium-dark_skin_tone": "🕵🏾\u200d♀️",
+    "woman_detective_medium-light_skin_tone": "🕵🏼\u200d♀️",
+    "woman_detective_medium_skin_tone": "🕵🏽\u200d♀️",
+    "woman_elf": "🧝\u200d♀️",
+    "woman_elf_dark_skin_tone": "🧝🏿\u200d♀️",
+    "woman_elf_light_skin_tone": "🧝🏻\u200d♀️",
+    "woman_elf_medium-dark_skin_tone": "🧝🏾\u200d♀️",
+    "woman_elf_medium-light_skin_tone": "🧝🏼\u200d♀️",
+    "woman_elf_medium_skin_tone": "🧝🏽\u200d♀️",
+    "woman_facepalming": "🤦\u200d♀️",
+    "woman_facepalming_dark_skin_tone": "🤦🏿\u200d♀️",
+    "woman_facepalming_light_skin_tone": "🤦🏻\u200d♀️",
+    "woman_facepalming_medium-dark_skin_tone": "🤦🏾\u200d♀️",
+    "woman_facepalming_medium-light_skin_tone": "🤦🏼\u200d♀️",
+    "woman_facepalming_medium_skin_tone": "🤦🏽\u200d♀️",
+    "woman_factory_worker": "👩\u200d🏭",
+    "woman_factory_worker_dark_skin_tone": "👩🏿\u200d🏭",
+    "woman_factory_worker_light_skin_tone": "👩🏻\u200d🏭",
+    "woman_factory_worker_medium-dark_skin_tone": "👩🏾\u200d🏭",
+    "woman_factory_worker_medium-light_skin_tone": "👩🏼\u200d🏭",
+    "woman_factory_worker_medium_skin_tone": "👩🏽\u200d🏭",
+    "woman_fairy": "🧚\u200d♀️",
+    "woman_fairy_dark_skin_tone": "🧚🏿\u200d♀️",
+    "woman_fairy_light_skin_tone": "🧚🏻\u200d♀️",
+    "woman_fairy_medium-dark_skin_tone": "🧚🏾\u200d♀️",
+    "woman_fairy_medium-light_skin_tone": "🧚🏼\u200d♀️",
+    "woman_fairy_medium_skin_tone": "🧚🏽\u200d♀️",
+    "woman_farmer": "👩\u200d🌾",
+    "woman_farmer_dark_skin_tone": "👩🏿\u200d🌾",
+    "woman_farmer_light_skin_tone": "👩🏻\u200d🌾",
+    "woman_farmer_medium-dark_skin_tone": "👩🏾\u200d🌾",
+    "woman_farmer_medium-light_skin_tone": "👩🏼\u200d🌾",
+    "woman_farmer_medium_skin_tone": "👩🏽\u200d🌾",
+    "woman_firefighter": "👩\u200d🚒",
+    "woman_firefighter_dark_skin_tone": "👩🏿\u200d🚒",
+    "woman_firefighter_light_skin_tone": "👩🏻\u200d🚒",
+    "woman_firefighter_medium-dark_skin_tone": "👩🏾\u200d🚒",
+    "woman_firefighter_medium-light_skin_tone": "👩🏼\u200d🚒",
+    "woman_firefighter_medium_skin_tone": "👩🏽\u200d🚒",
+    "woman_frowning": "🙍\u200d♀️",
+    "woman_frowning_dark_skin_tone": "🙍🏿\u200d♀️",
+    "woman_frowning_light_skin_tone": "🙍🏻\u200d♀️",
+    "woman_frowning_medium-dark_skin_tone": "🙍🏾\u200d♀️",
+    "woman_frowning_medium-light_skin_tone": "🙍🏼\u200d♀️",
+    "woman_frowning_medium_skin_tone": "🙍🏽\u200d♀️",
+    "woman_genie": "🧞\u200d♀️",
+    "woman_gesturing_no": "🙅\u200d♀️",
+    "woman_gesturing_no_dark_skin_tone": "🙅🏿\u200d♀️",
+    "woman_gesturing_no_light_skin_tone": "🙅🏻\u200d♀️",
+    "woman_gesturing_no_medium-dark_skin_tone": "🙅🏾\u200d♀️",
+    "woman_gesturing_no_medium-light_skin_tone": "🙅🏼\u200d♀️",
+    "woman_gesturing_no_medium_skin_tone": "🙅🏽\u200d♀️",
+    "woman_gesturing_ok": "🙆\u200d♀️",
+    "woman_gesturing_ok_dark_skin_tone": "🙆🏿\u200d♀️",
+    "woman_gesturing_ok_light_skin_tone": "🙆🏻\u200d♀️",
+    "woman_gesturing_ok_medium-dark_skin_tone": "🙆🏾\u200d♀️",
+    "woman_gesturing_ok_medium-light_skin_tone": "🙆🏼\u200d♀️",
+    "woman_gesturing_ok_medium_skin_tone": "🙆🏽\u200d♀️",
+    "woman_getting_haircut": "💇\u200d♀️",
+    "woman_getting_haircut_dark_skin_tone": "💇🏿\u200d♀️",
+    "woman_getting_haircut_light_skin_tone": "💇🏻\u200d♀️",
+    "woman_getting_haircut_medium-dark_skin_tone": "💇🏾\u200d♀️",
+    "woman_getting_haircut_medium-light_skin_tone": "💇🏼\u200d♀️",
+    "woman_getting_haircut_medium_skin_tone": "💇🏽\u200d♀️",
+    "woman_getting_massage": "💆\u200d♀️",
+    "woman_getting_massage_dark_skin_tone": "💆🏿\u200d♀️",
+    "woman_getting_massage_light_skin_tone": "💆🏻\u200d♀️",
+    "woman_getting_massage_medium-dark_skin_tone": "💆🏾\u200d♀️",
+    "woman_getting_massage_medium-light_skin_tone": "💆🏼\u200d♀️",
+    "woman_getting_massage_medium_skin_tone": "💆🏽\u200d♀️",
+    "woman_golfing": "🏌️\u200d♀️",
+    "woman_golfing_dark_skin_tone": "🏌🏿\u200d♀️",
+    "woman_golfing_light_skin_tone": "🏌🏻\u200d♀️",
+    "woman_golfing_medium-dark_skin_tone": "🏌🏾\u200d♀️",
+    "woman_golfing_medium-light_skin_tone": "🏌🏼\u200d♀️",
+    "woman_golfing_medium_skin_tone": "🏌🏽\u200d♀️",
+    "woman_guard": "💂\u200d♀️",
+    "woman_guard_dark_skin_tone": "💂🏿\u200d♀️",
+    "woman_guard_light_skin_tone": "💂🏻\u200d♀️",
+    "woman_guard_medium-dark_skin_tone": "💂🏾\u200d♀️",
+    "woman_guard_medium-light_skin_tone": "💂🏼\u200d♀️",
+    "woman_guard_medium_skin_tone": "💂🏽\u200d♀️",
+    "woman_health_worker": "👩\u200d⚕️",
+    "woman_health_worker_dark_skin_tone": "👩🏿\u200d⚕️",
+    "woman_health_worker_light_skin_tone": "👩🏻\u200d⚕️",
+    "woman_health_worker_medium-dark_skin_tone": "👩🏾\u200d⚕️",
+    "woman_health_worker_medium-light_skin_tone": "👩🏼\u200d⚕️",
+    "woman_health_worker_medium_skin_tone": "👩🏽\u200d⚕️",
+    "woman_in_lotus_position": "🧘\u200d♀️",
+    "woman_in_lotus_position_dark_skin_tone": "🧘🏿\u200d♀️",
+    "woman_in_lotus_position_light_skin_tone": "🧘🏻\u200d♀️",
+    "woman_in_lotus_position_medium-dark_skin_tone": "🧘🏾\u200d♀️",
+    "woman_in_lotus_position_medium-light_skin_tone": "🧘🏼\u200d♀️",
+    "woman_in_lotus_position_medium_skin_tone": "🧘🏽\u200d♀️",
+    "woman_in_manual_wheelchair": "👩\u200d🦽",
+    "woman_in_motorized_wheelchair": "👩\u200d🦼",
+    "woman_in_steamy_room": "🧖\u200d♀️",
+    "woman_in_steamy_room_dark_skin_tone": "🧖🏿\u200d♀️",
+    "woman_in_steamy_room_light_skin_tone": "🧖🏻\u200d♀️",
+    "woman_in_steamy_room_medium-dark_skin_tone": "🧖🏾\u200d♀️",
+    "woman_in_steamy_room_medium-light_skin_tone": "🧖🏼\u200d♀️",
+    "woman_in_steamy_room_medium_skin_tone": "🧖🏽\u200d♀️",
+    "woman_judge": "👩\u200d⚖️",
+    "woman_judge_dark_skin_tone": "👩🏿\u200d⚖️",
+    "woman_judge_light_skin_tone": "👩🏻\u200d⚖️",
+    "woman_judge_medium-dark_skin_tone": "👩🏾\u200d⚖️",
+    "woman_judge_medium-light_skin_tone": "👩🏼\u200d⚖️",
+    "woman_judge_medium_skin_tone": "👩🏽\u200d⚖️",
+    "woman_juggling": "🤹\u200d♀️",
+    "woman_juggling_dark_skin_tone": "🤹🏿\u200d♀️",
+    "woman_juggling_light_skin_tone": "🤹🏻\u200d♀️",
+    "woman_juggling_medium-dark_skin_tone": "🤹🏾\u200d♀️",
+    "woman_juggling_medium-light_skin_tone": "🤹🏼\u200d♀️",
+    "woman_juggling_medium_skin_tone": "🤹🏽\u200d♀️",
+    "woman_lifting_weights": "🏋️\u200d♀️",
+    "woman_lifting_weights_dark_skin_tone": "🏋🏿\u200d♀️",
+    "woman_lifting_weights_light_skin_tone": "🏋🏻\u200d♀️",
+    "woman_lifting_weights_medium-dark_skin_tone": "🏋🏾\u200d♀️",
+    "woman_lifting_weights_medium-light_skin_tone": "🏋🏼\u200d♀️",
+    "woman_lifting_weights_medium_skin_tone": "🏋🏽\u200d♀️",
+    "woman_light_skin_tone": "👩🏻",
+    "woman_mage": "🧙\u200d♀️",
+    "woman_mage_dark_skin_tone": "🧙🏿\u200d♀️",
+    "woman_mage_light_skin_tone": "🧙🏻\u200d♀️",
+    "woman_mage_medium-dark_skin_tone": "🧙🏾\u200d♀️",
+    "woman_mage_medium-light_skin_tone": "🧙🏼\u200d♀️",
+    "woman_mage_medium_skin_tone": "🧙🏽\u200d♀️",
+    "woman_mechanic": "👩\u200d🔧",
+    "woman_mechanic_dark_skin_tone": "👩🏿\u200d🔧",
+    "woman_mechanic_light_skin_tone": "👩🏻\u200d🔧",
+    "woman_mechanic_medium-dark_skin_tone": "👩🏾\u200d🔧",
+    "woman_mechanic_medium-light_skin_tone": "👩🏼\u200d🔧",
+    "woman_mechanic_medium_skin_tone": "👩🏽\u200d🔧",
+    "woman_medium-dark_skin_tone": "👩🏾",
+    "woman_medium-light_skin_tone": "👩🏼",
+    "woman_medium_skin_tone": "👩🏽",
+    "woman_mountain_biking": "🚵\u200d♀️",
+    "woman_mountain_biking_dark_skin_tone": "🚵🏿\u200d♀️",
+    "woman_mountain_biking_light_skin_tone": "🚵🏻\u200d♀️",
+    "woman_mountain_biking_medium-dark_skin_tone": "🚵🏾\u200d♀️",
+    "woman_mountain_biking_medium-light_skin_tone": "🚵🏼\u200d♀️",
+    "woman_mountain_biking_medium_skin_tone": "🚵🏽\u200d♀️",
+    "woman_office_worker": "👩\u200d💼",
+    "woman_office_worker_dark_skin_tone": "👩🏿\u200d💼",
+    "woman_office_worker_light_skin_tone": "👩🏻\u200d💼",
+    "woman_office_worker_medium-dark_skin_tone": "👩🏾\u200d💼",
+    "woman_office_worker_medium-light_skin_tone": "👩🏼\u200d💼",
+    "woman_office_worker_medium_skin_tone": "👩🏽\u200d💼",
+    "woman_pilot": "👩\u200d✈️",
+    "woman_pilot_dark_skin_tone": "👩🏿\u200d✈️",
+    "woman_pilot_light_skin_tone": "👩🏻\u200d✈️",
+    "woman_pilot_medium-dark_skin_tone": "👩🏾\u200d✈️",
+    "woman_pilot_medium-light_skin_tone": "👩🏼\u200d✈️",
+    "woman_pilot_medium_skin_tone": "👩🏽\u200d✈️",
+    "woman_playing_handball": "🤾\u200d♀️",
+    "woman_playing_handball_dark_skin_tone": "🤾🏿\u200d♀️",
+    "woman_playing_handball_light_skin_tone": "🤾🏻\u200d♀️",
+    "woman_playing_handball_medium-dark_skin_tone": "🤾🏾\u200d♀️",
+    "woman_playing_handball_medium-light_skin_tone": "🤾🏼\u200d♀️",
+    "woman_playing_handball_medium_skin_tone": "🤾🏽\u200d♀️",
+    "woman_playing_water_polo": "🤽\u200d♀️",
+    "woman_playing_water_polo_dark_skin_tone": "🤽🏿\u200d♀️",
+    "woman_playing_water_polo_light_skin_tone": "🤽🏻\u200d♀️",
+    "woman_playing_water_polo_medium-dark_skin_tone": "🤽🏾\u200d♀️",
+    "woman_playing_water_polo_medium-light_skin_tone": "🤽🏼\u200d♀️",
+    "woman_playing_water_polo_medium_skin_tone": "🤽🏽\u200d♀️",
+    "woman_police_officer": "👮\u200d♀️",
+    "woman_police_officer_dark_skin_tone": "👮🏿\u200d♀️",
+    "woman_police_officer_light_skin_tone": "👮🏻\u200d♀️",
+    "woman_police_officer_medium-dark_skin_tone": "👮🏾\u200d♀️",
+    "woman_police_officer_medium-light_skin_tone": "👮🏼\u200d♀️",
+    "woman_police_officer_medium_skin_tone": "👮🏽\u200d♀️",
+    "woman_pouting": "🙎\u200d♀️",
+    "woman_pouting_dark_skin_tone": "🙎🏿\u200d♀️",
+    "woman_pouting_light_skin_tone": "🙎🏻\u200d♀️",
+    "woman_pouting_medium-dark_skin_tone": "🙎🏾\u200d♀️",
+    "woman_pouting_medium-light_skin_tone": "🙎🏼\u200d♀️",
+    "woman_pouting_medium_skin_tone": "🙎🏽\u200d♀️",
+    "woman_raising_hand": "🙋\u200d♀️",
+    "woman_raising_hand_dark_skin_tone": "🙋🏿\u200d♀️",
+    "woman_raising_hand_light_skin_tone": "🙋🏻\u200d♀️",
+    "woman_raising_hand_medium-dark_skin_tone": "🙋🏾\u200d♀️",
+    "woman_raising_hand_medium-light_skin_tone": "🙋🏼\u200d♀️",
+    "woman_raising_hand_medium_skin_tone": "🙋🏽\u200d♀️",
+    "woman_rowing_boat": "🚣\u200d♀️",
+    "woman_rowing_boat_dark_skin_tone": "🚣🏿\u200d♀️",
+    "woman_rowing_boat_light_skin_tone": "🚣🏻\u200d♀️",
+    "woman_rowing_boat_medium-dark_skin_tone": "🚣🏾\u200d♀️",
+    "woman_rowing_boat_medium-light_skin_tone": "🚣🏼\u200d♀️",
+    "woman_rowing_boat_medium_skin_tone": "🚣🏽\u200d♀️",
+    "woman_running": "🏃\u200d♀️",
+    "woman_running_dark_skin_tone": "🏃🏿\u200d♀️",
+    "woman_running_light_skin_tone": "🏃🏻\u200d♀️",
+    "woman_running_medium-dark_skin_tone": "🏃🏾\u200d♀️",
+    "woman_running_medium-light_skin_tone": "🏃🏼\u200d♀️",
+    "woman_running_medium_skin_tone": "🏃🏽\u200d♀️",
+    "woman_scientist": "👩\u200d🔬",
+    "woman_scientist_dark_skin_tone": "👩🏿\u200d🔬",
+    "woman_scientist_light_skin_tone": "👩🏻\u200d🔬",
+    "woman_scientist_medium-dark_skin_tone": "👩🏾\u200d🔬",
+    "woman_scientist_medium-light_skin_tone": "👩🏼\u200d🔬",
+    "woman_scientist_medium_skin_tone": "👩🏽\u200d🔬",
+    "woman_shrugging": "🤷\u200d♀️",
+    "woman_shrugging_dark_skin_tone": "🤷🏿\u200d♀️",
+    "woman_shrugging_light_skin_tone": "🤷🏻\u200d♀️",
+    "woman_shrugging_medium-dark_skin_tone": "🤷🏾\u200d♀️",
+    "woman_shrugging_medium-light_skin_tone": "🤷🏼\u200d♀️",
+    "woman_shrugging_medium_skin_tone": "🤷🏽\u200d♀️",
+    "woman_singer": "👩\u200d🎤",
+    "woman_singer_dark_skin_tone": "👩🏿\u200d🎤",
+    "woman_singer_light_skin_tone": "👩🏻\u200d🎤",
+    "woman_singer_medium-dark_skin_tone": "👩🏾\u200d🎤",
+    "woman_singer_medium-light_skin_tone": "👩🏼\u200d🎤",
+    "woman_singer_medium_skin_tone": "👩🏽\u200d🎤",
+    "woman_student": "👩\u200d🎓",
+    "woman_student_dark_skin_tone": "👩🏿\u200d🎓",
+    "woman_student_light_skin_tone": "👩🏻\u200d🎓",
+    "woman_student_medium-dark_skin_tone": "👩🏾\u200d🎓",
+    "woman_student_medium-light_skin_tone": "👩🏼\u200d🎓",
+    "woman_student_medium_skin_tone": "👩🏽\u200d🎓",
+    "woman_surfing": "🏄\u200d♀️",
+    "woman_surfing_dark_skin_tone": "🏄🏿\u200d♀️",
+    "woman_surfing_light_skin_tone": "🏄🏻\u200d♀️",
+    "woman_surfing_medium-dark_skin_tone": "🏄🏾\u200d♀️",
+    "woman_surfing_medium-light_skin_tone": "🏄🏼\u200d♀️",
+    "woman_surfing_medium_skin_tone": "🏄🏽\u200d♀️",
+    "woman_swimming": "🏊\u200d♀️",
+    "woman_swimming_dark_skin_tone": "🏊🏿\u200d♀️",
+    "woman_swimming_light_skin_tone": "🏊🏻\u200d♀️",
+    "woman_swimming_medium-dark_skin_tone": "🏊🏾\u200d♀️",
+    "woman_swimming_medium-light_skin_tone": "🏊🏼\u200d♀️",
+    "woman_swimming_medium_skin_tone": "🏊🏽\u200d♀️",
+    "woman_teacher": "👩\u200d🏫",
+    "woman_teacher_dark_skin_tone": "👩🏿\u200d🏫",
+    "woman_teacher_light_skin_tone": "👩🏻\u200d🏫",
+    "woman_teacher_medium-dark_skin_tone": "👩🏾\u200d🏫",
+    "woman_teacher_medium-light_skin_tone": "👩🏼\u200d🏫",
+    "woman_teacher_medium_skin_tone": "👩🏽\u200d🏫",
+    "woman_technologist": "👩\u200d💻",
+    "woman_technologist_dark_skin_tone": "👩🏿\u200d💻",
+    "woman_technologist_light_skin_tone": "👩🏻\u200d💻",
+    "woman_technologist_medium-dark_skin_tone": "👩🏾\u200d💻",
+    "woman_technologist_medium-light_skin_tone": "👩🏼\u200d💻",
+    "woman_technologist_medium_skin_tone": "👩🏽\u200d💻",
+    "woman_tipping_hand": "💁\u200d♀️",
+    "woman_tipping_hand_dark_skin_tone": "💁🏿\u200d♀️",
+    "woman_tipping_hand_light_skin_tone": "💁🏻\u200d♀️",
+    "woman_tipping_hand_medium-dark_skin_tone": "💁🏾\u200d♀️",
+    "woman_tipping_hand_medium-light_skin_tone": "💁🏼\u200d♀️",
+    "woman_tipping_hand_medium_skin_tone": "💁🏽\u200d♀️",
+    "woman_vampire": "🧛\u200d♀️",
+    "woman_vampire_dark_skin_tone": "🧛🏿\u200d♀️",
+    "woman_vampire_light_skin_tone": "🧛🏻\u200d♀️",
+    "woman_vampire_medium-dark_skin_tone": "🧛🏾\u200d♀️",
+    "woman_vampire_medium-light_skin_tone": "🧛🏼\u200d♀️",
+    "woman_vampire_medium_skin_tone": "🧛🏽\u200d♀️",
+    "woman_walking": "🚶\u200d♀️",
+    "woman_walking_dark_skin_tone": "🚶🏿\u200d♀️",
+    "woman_walking_light_skin_tone": "🚶🏻\u200d♀️",
+    "woman_walking_medium-dark_skin_tone": "🚶🏾\u200d♀️",
+    "woman_walking_medium-light_skin_tone": "🚶🏼\u200d♀️",
+    "woman_walking_medium_skin_tone": "🚶🏽\u200d♀️",
+    "woman_wearing_turban": "👳\u200d♀️",
+    "woman_wearing_turban_dark_skin_tone": "👳🏿\u200d♀️",
+    "woman_wearing_turban_light_skin_tone": "👳🏻\u200d♀️",
+    "woman_wearing_turban_medium-dark_skin_tone": "👳🏾\u200d♀️",
+    "woman_wearing_turban_medium-light_skin_tone": "👳🏼\u200d♀️",
+    "woman_wearing_turban_medium_skin_tone": "👳🏽\u200d♀️",
+    "woman_with_headscarf": "🧕",
+    "woman_with_headscarf_dark_skin_tone": "🧕🏿",
+    "woman_with_headscarf_light_skin_tone": "🧕🏻",
+    "woman_with_headscarf_medium-dark_skin_tone": "🧕🏾",
+    "woman_with_headscarf_medium-light_skin_tone": "🧕🏼",
+    "woman_with_headscarf_medium_skin_tone": "🧕🏽",
+    "woman_with_probing_cane": "👩\u200d🦯",
+    "woman_zombie": "🧟\u200d♀️",
+    "woman’s_boot": "👢",
+    "woman’s_clothes": "👚",
+    "woman’s_hat": "👒",
+    "woman’s_sandal": "👡",
+    "women_with_bunny_ears": "👯\u200d♀️",
+    "women_wrestling": "🤼\u200d♀️",
+    "women’s_room": "🚺",
+    "woozy_face": "🥴",
+    "world_map": "🗺",
+    "worried_face": "😟",
+    "wrapped_gift": "🎁",
+    "wrench": "🔧",
+    "writing_hand": "✍",
+    "writing_hand_dark_skin_tone": "✍🏿",
+    "writing_hand_light_skin_tone": "✍🏻",
+    "writing_hand_medium-dark_skin_tone": "✍🏾",
+    "writing_hand_medium-light_skin_tone": "✍🏼",
+    "writing_hand_medium_skin_tone": "✍🏽",
+    "yarn": "🧶",
+    "yawning_face": "🥱",
+    "yellow_circle": "🟡",
+    "yellow_heart": "💛",
+    "yellow_square": "🟨",
+    "yen_banknote": "💴",
+    "yo-yo": "🪀",
+    "yin_yang": "☯",
+    "zany_face": "🤪",
+    "zebra": "🦓",
+    "zipper-mouth_face": "🤐",
+    "zombie": "🧟",
+    "zzz": "💤",
+    "åland_islands": "🇦🇽",
+    "keycap_asterisk": "*⃣",
+    "keycap_digit_eight": "8⃣",
+    "keycap_digit_five": "5⃣",
+    "keycap_digit_four": "4⃣",
+    "keycap_digit_nine": "9⃣",
+    "keycap_digit_one": "1⃣",
+    "keycap_digit_seven": "7⃣",
+    "keycap_digit_six": "6⃣",
+    "keycap_digit_three": "3⃣",
+    "keycap_digit_two": "2⃣",
+    "keycap_digit_zero": "0⃣",
+    "keycap_number_sign": "#⃣",
+    "light_skin_tone": "🏻",
+    "medium_light_skin_tone": "🏼",
+    "medium_skin_tone": "🏽",
+    "medium_dark_skin_tone": "🏾",
+    "dark_skin_tone": "🏿",
+    "regional_indicator_symbol_letter_a": "🇦",
+    "regional_indicator_symbol_letter_b": "🇧",
+    "regional_indicator_symbol_letter_c": "🇨",
+    "regional_indicator_symbol_letter_d": "🇩",
+    "regional_indicator_symbol_letter_e": "🇪",
+    "regional_indicator_symbol_letter_f": "🇫",
+    "regional_indicator_symbol_letter_g": "🇬",
+    "regional_indicator_symbol_letter_h": "🇭",
+    "regional_indicator_symbol_letter_i": "🇮",
+    "regional_indicator_symbol_letter_j": "🇯",
+    "regional_indicator_symbol_letter_k": "🇰",
+    "regional_indicator_symbol_letter_l": "🇱",
+    "regional_indicator_symbol_letter_m": "🇲",
+    "regional_indicator_symbol_letter_n": "🇳",
+    "regional_indicator_symbol_letter_o": "🇴",
+    "regional_indicator_symbol_letter_p": "🇵",
+    "regional_indicator_symbol_letter_q": "🇶",
+    "regional_indicator_symbol_letter_r": "🇷",
+    "regional_indicator_symbol_letter_s": "🇸",
+    "regional_indicator_symbol_letter_t": "🇹",
+    "regional_indicator_symbol_letter_u": "🇺",
+    "regional_indicator_symbol_letter_v": "🇻",
+    "regional_indicator_symbol_letter_w": "🇼",
+    "regional_indicator_symbol_letter_x": "🇽",
+    "regional_indicator_symbol_letter_y": "🇾",
+    "regional_indicator_symbol_letter_z": "🇿",
+    "airplane_arriving": "🛬",
+    "space_invader": "👾",
+    "football": "🏈",
+    "anger": "💢",
+    "angry": "😠",
+    "anguished": "😧",
+    "signal_strength": "📶",
+    "arrows_counterclockwise": "🔄",
+    "arrow_heading_down": "⤵",
+    "arrow_heading_up": "⤴",
+    "art": "🎨",
+    "astonished": "😲",
+    "athletic_shoe": "👟",
+    "atm": "🏧",
+    "car": "🚗",
+    "red_car": "🚗",
+    "angel": "👼",
+    "back": "🔙",
+    "badminton_racquet_and_shuttlecock": "🏸",
+    "dollar": "💵",
+    "euro": "💶",
+    "pound": "💷",
+    "yen": "💴",
+    "barber": "💈",
+    "bath": "🛀",
+    "bear": "🐻",
+    "heartbeat": "💓",
+    "beer": "🍺",
+    "no_bell": "🔕",
+    "bento": "🍱",
+    "bike": "🚲",
+    "bicyclist": "🚴",
+    "8ball": "🎱",
+    "biohazard_sign": "☣",
+    "birthday": "🎂",
+    "black_circle_for_record": "⏺",
+    "clubs": "♣",
+    "diamonds": "♦",
+    "arrow_double_down": "⏬",
+    "hearts": "♥",
+    "rewind": "⏪",
+    "black_left__pointing_double_triangle_with_vertical_bar": "⏮",
+    "arrow_backward": "◀",
+    "black_medium_small_square": "◾",
+    "question": "❓",
+    "fast_forward": "⏩",
+    "black_right__pointing_double_triangle_with_vertical_bar": "⏭",
+    "arrow_forward": "▶",
+    "black_right__pointing_triangle_with_double_vertical_bar": "⏯",
+    "arrow_right": "➡",
+    "spades": "♠",
+    "black_square_for_stop": "⏹",
+    "sunny": "☀",
+    "phone": "☎",
+    "recycle": "♻",
+    "arrow_double_up": "⏫",
+    "busstop": "🚏",
+    "date": "📅",
+    "flags": "🎏",
+    "cat2": "🐈",
+    "joy_cat": "😹",
+    "smirk_cat": "😼",
+    "chart_with_downwards_trend": "📉",
+    "chart_with_upwards_trend": "📈",
+    "chart": "💹",
+    "mega": "📣",
+    "checkered_flag": "🏁",
+    "accept": "🉑",
+    "ideograph_advantage": "🉐",
+    "congratulations": "㊗",
+    "secret": "㊙",
+    "m": "Ⓜ",
+    "city_sunset": "🌆",
+    "clapper": "🎬",
+    "clap": "👏",
+    "beers": "🍻",
+    "clock830": "🕣",
+    "clock8": "🕗",
+    "clock1130": "🕦",
+    "clock11": "🕚",
+    "clock530": "🕠",
+    "clock5": "🕔",
+    "clock430": "🕟",
+    "clock4": "🕓",
+    "clock930": "🕤",
+    "clock9": "🕘",
+    "clock130": "🕜",
+    "clock1": "🕐",
+    "clock730": "🕢",
+    "clock7": "🕖",
+    "clock630": "🕡",
+    "clock6": "🕕",
+    "clock1030": "🕥",
+    "clock10": "🕙",
+    "clock330": "🕞",
+    "clock3": "🕒",
+    "clock1230": "🕧",
+    "clock12": "🕛",
+    "clock230": "🕝",
+    "clock2": "🕑",
+    "arrows_clockwise": "🔃",
+    "repeat": "🔁",
+    "repeat_one": "🔂",
+    "closed_lock_with_key": "🔐",
+    "mailbox_closed": "📪",
+    "mailbox": "📫",
+    "cloud_with_tornado": "🌪",
+    "cocktail": "🍸",
+    "boom": "💥",
+    "compression": "🗜",
+    "confounded": "😖",
+    "confused": "😕",
+    "rice": "🍚",
+    "cow2": "🐄",
+    "cricket_bat_and_ball": "🏏",
+    "x": "❌",
+    "cry": "😢",
+    "curry": "🍛",
+    "dagger_knife": "🗡",
+    "dancer": "💃",
+    "dark_sunglasses": "🕶",
+    "dash": "💨",
+    "truck": "🚚",
+    "derelict_house_building": "🏚",
+    "diamond_shape_with_a_dot_inside": "💠",
+    "dart": "🎯",
+    "disappointed_relieved": "😥",
+    "disappointed": "😞",
+    "do_not_litter": "🚯",
+    "dog2": "🐕",
+    "flipper": "🐬",
+    "loop": "➿",
+    "bangbang": "‼",
+    "double_vertical_bar": "⏸",
+    "dove_of_peace": "🕊",
+    "small_red_triangle_down": "🔻",
+    "arrow_down_small": "🔽",
+    "arrow_down": "⬇",
+    "dromedary_camel": "🐪",
+    "e__mail": "📧",
+    "corn": "🌽",
+    "ear_of_rice": "🌾",
+    "earth_americas": "🌎",
+    "earth_asia": "🌏",
+    "earth_africa": "🌍",
+    "eight_pointed_black_star": "✴",
+    "eight_spoked_asterisk": "✳",
+    "eject_symbol": "⏏",
+    "bulb": "💡",
+    "emoji_modifier_fitzpatrick_type__1__2": "🏻",
+    "emoji_modifier_fitzpatrick_type__3": "🏼",
+    "emoji_modifier_fitzpatrick_type__4": "🏽",
+    "emoji_modifier_fitzpatrick_type__5": "🏾",
+    "emoji_modifier_fitzpatrick_type__6": "🏿",
+    "end": "🔚",
+    "email": "✉",
+    "european_castle": "🏰",
+    "european_post_office": "🏤",
+    "interrobang": "⁉",
+    "expressionless": "😑",
+    "eyeglasses": "👓",
+    "massage": "💆",
+    "yum": "😋",
+    "scream": "😱",
+    "kissing_heart": "😘",
+    "sweat": "😓",
+    "face_with_head__bandage": "🤕",
+    "triumph": "😤",
+    "mask": "😷",
+    "no_good": "🙅",
+    "ok_woman": "🙆",
+    "open_mouth": "😮",
+    "cold_sweat": "😰",
+    "stuck_out_tongue": "😛",
+    "stuck_out_tongue_closed_eyes": "😝",
+    "stuck_out_tongue_winking_eye": "😜",
+    "joy": "😂",
+    "no_mouth": "😶",
+    "santa": "🎅",
+    "fax": "📠",
+    "fearful": "😨",
+    "field_hockey_stick_and_ball": "🏑",
+    "first_quarter_moon_with_face": "🌛",
+    "fish_cake": "🍥",
+    "fishing_pole_and_fish": "🎣",
+    "facepunch": "👊",
+    "punch": "👊",
+    "flag_for_afghanistan": "🇦🇫",
+    "flag_for_albania": "🇦🇱",
+    "flag_for_algeria": "🇩🇿",
+    "flag_for_american_samoa": "🇦🇸",
+    "flag_for_andorra": "🇦🇩",
+    "flag_for_angola": "🇦🇴",
+    "flag_for_anguilla": "🇦🇮",
+    "flag_for_antarctica": "🇦🇶",
+    "flag_for_antigua_&_barbuda": "🇦🇬",
+    "flag_for_argentina": "🇦🇷",
+    "flag_for_armenia": "🇦🇲",
+    "flag_for_aruba": "🇦🇼",
+    "flag_for_ascension_island": "🇦🇨",
+    "flag_for_australia": "🇦🇺",
+    "flag_for_austria": "🇦🇹",
+    "flag_for_azerbaijan": "🇦🇿",
+    "flag_for_bahamas": "🇧🇸",
+    "flag_for_bahrain": "🇧🇭",
+    "flag_for_bangladesh": "🇧🇩",
+    "flag_for_barbados": "🇧🇧",
+    "flag_for_belarus": "🇧🇾",
+    "flag_for_belgium": "🇧🇪",
+    "flag_for_belize": "🇧🇿",
+    "flag_for_benin": "🇧🇯",
+    "flag_for_bermuda": "🇧🇲",
+    "flag_for_bhutan": "🇧🇹",
+    "flag_for_bolivia": "🇧🇴",
+    "flag_for_bosnia_&_herzegovina": "🇧🇦",
+    "flag_for_botswana": "🇧🇼",
+    "flag_for_bouvet_island": "🇧🇻",
+    "flag_for_brazil": "🇧🇷",
+    "flag_for_british_indian_ocean_territory": "🇮🇴",
+    "flag_for_british_virgin_islands": "🇻🇬",
+    "flag_for_brunei": "🇧🇳",
+    "flag_for_bulgaria": "🇧🇬",
+    "flag_for_burkina_faso": "🇧🇫",
+    "flag_for_burundi": "🇧🇮",
+    "flag_for_cambodia": "🇰🇭",
+    "flag_for_cameroon": "🇨🇲",
+    "flag_for_canada": "🇨🇦",
+    "flag_for_canary_islands": "🇮🇨",
+    "flag_for_cape_verde": "🇨🇻",
+    "flag_for_caribbean_netherlands": "🇧🇶",
+    "flag_for_cayman_islands": "🇰🇾",
+    "flag_for_central_african_republic": "🇨🇫",
+    "flag_for_ceuta_&_melilla": "🇪🇦",
+    "flag_for_chad": "🇹🇩",
+    "flag_for_chile": "🇨🇱",
+    "flag_for_china": "🇨🇳",
+    "flag_for_christmas_island": "🇨🇽",
+    "flag_for_clipperton_island": "🇨🇵",
+    "flag_for_cocos__islands": "🇨🇨",
+    "flag_for_colombia": "🇨🇴",
+    "flag_for_comoros": "🇰🇲",
+    "flag_for_congo____brazzaville": "🇨🇬",
+    "flag_for_congo____kinshasa": "🇨🇩",
+    "flag_for_cook_islands": "🇨🇰",
+    "flag_for_costa_rica": "🇨🇷",
+    "flag_for_croatia": "🇭🇷",
+    "flag_for_cuba": "🇨🇺",
+    "flag_for_curaçao": "🇨🇼",
+    "flag_for_cyprus": "🇨🇾",
+    "flag_for_czech_republic": "🇨🇿",
+    "flag_for_côte_d’ivoire": "🇨🇮",
+    "flag_for_denmark": "🇩🇰",
+    "flag_for_diego_garcia": "🇩🇬",
+    "flag_for_djibouti": "🇩🇯",
+    "flag_for_dominica": "🇩🇲",
+    "flag_for_dominican_republic": "🇩🇴",
+    "flag_for_ecuador": "🇪🇨",
+    "flag_for_egypt": "🇪🇬",
+    "flag_for_el_salvador": "🇸🇻",
+    "flag_for_equatorial_guinea": "🇬🇶",
+    "flag_for_eritrea": "🇪🇷",
+    "flag_for_estonia": "🇪🇪",
+    "flag_for_ethiopia": "🇪🇹",
+    "flag_for_european_union": "🇪🇺",
+    "flag_for_falkland_islands": "🇫🇰",
+    "flag_for_faroe_islands": "🇫🇴",
+    "flag_for_fiji": "🇫🇯",
+    "flag_for_finland": "🇫🇮",
+    "flag_for_france": "🇫🇷",
+    "flag_for_french_guiana": "🇬🇫",
+    "flag_for_french_polynesia": "🇵🇫",
+    "flag_for_french_southern_territories": "🇹🇫",
+    "flag_for_gabon": "🇬🇦",
+    "flag_for_gambia": "🇬🇲",
+    "flag_for_georgia": "🇬🇪",
+    "flag_for_germany": "🇩🇪",
+    "flag_for_ghana": "🇬🇭",
+    "flag_for_gibraltar": "🇬🇮",
+    "flag_for_greece": "🇬🇷",
+    "flag_for_greenland": "🇬🇱",
+    "flag_for_grenada": "🇬🇩",
+    "flag_for_guadeloupe": "🇬🇵",
+    "flag_for_guam": "🇬🇺",
+    "flag_for_guatemala": "🇬🇹",
+    "flag_for_guernsey": "🇬🇬",
+    "flag_for_guinea": "🇬🇳",
+    "flag_for_guinea__bissau": "🇬🇼",
+    "flag_for_guyana": "🇬🇾",
+    "flag_for_haiti": "🇭🇹",
+    "flag_for_heard_&_mcdonald_islands": "🇭🇲",
+    "flag_for_honduras": "🇭🇳",
+    "flag_for_hong_kong": "🇭🇰",
+    "flag_for_hungary": "🇭🇺",
+    "flag_for_iceland": "🇮🇸",
+    "flag_for_india": "🇮🇳",
+    "flag_for_indonesia": "🇮🇩",
+    "flag_for_iran": "🇮🇷",
+    "flag_for_iraq": "🇮🇶",
+    "flag_for_ireland": "🇮🇪",
+    "flag_for_isle_of_man": "🇮🇲",
+    "flag_for_israel": "🇮🇱",
+    "flag_for_italy": "🇮🇹",
+    "flag_for_jamaica": "🇯🇲",
+    "flag_for_japan": "🇯🇵",
+    "flag_for_jersey": "🇯🇪",
+    "flag_for_jordan": "🇯🇴",
+    "flag_for_kazakhstan": "🇰🇿",
+    "flag_for_kenya": "🇰🇪",
+    "flag_for_kiribati": "🇰🇮",
+    "flag_for_kosovo": "🇽🇰",
+    "flag_for_kuwait": "🇰🇼",
+    "flag_for_kyrgyzstan": "🇰🇬",
+    "flag_for_laos": "🇱🇦",
+    "flag_for_latvia": "🇱🇻",
+    "flag_for_lebanon": "🇱🇧",
+    "flag_for_lesotho": "🇱🇸",
+    "flag_for_liberia": "🇱🇷",
+    "flag_for_libya": "🇱🇾",
+    "flag_for_liechtenstein": "🇱🇮",
+    "flag_for_lithuania": "🇱🇹",
+    "flag_for_luxembourg": "🇱🇺",
+    "flag_for_macau": "🇲🇴",
+    "flag_for_macedonia": "🇲🇰",
+    "flag_for_madagascar": "🇲🇬",
+    "flag_for_malawi": "🇲🇼",
+    "flag_for_malaysia": "🇲🇾",
+    "flag_for_maldives": "🇲🇻",
+    "flag_for_mali": "🇲🇱",
+    "flag_for_malta": "🇲🇹",
+    "flag_for_marshall_islands": "🇲🇭",
+    "flag_for_martinique": "🇲🇶",
+    "flag_for_mauritania": "🇲🇷",
+    "flag_for_mauritius": "🇲🇺",
+    "flag_for_mayotte": "🇾🇹",
+    "flag_for_mexico": "🇲🇽",
+    "flag_for_micronesia": "🇫🇲",
+    "flag_for_moldova": "🇲🇩",
+    "flag_for_monaco": "🇲🇨",
+    "flag_for_mongolia": "🇲🇳",
+    "flag_for_montenegro": "🇲🇪",
+    "flag_for_montserrat": "🇲🇸",
+    "flag_for_morocco": "🇲🇦",
+    "flag_for_mozambique": "🇲🇿",
+    "flag_for_myanmar": "🇲🇲",
+    "flag_for_namibia": "🇳🇦",
+    "flag_for_nauru": "🇳🇷",
+    "flag_for_nepal": "🇳🇵",
+    "flag_for_netherlands": "🇳🇱",
+    "flag_for_new_caledonia": "🇳🇨",
+    "flag_for_new_zealand": "🇳🇿",
+    "flag_for_nicaragua": "🇳🇮",
+    "flag_for_niger": "🇳🇪",
+    "flag_for_nigeria": "🇳🇬",
+    "flag_for_niue": "🇳🇺",
+    "flag_for_norfolk_island": "🇳🇫",
+    "flag_for_north_korea": "🇰🇵",
+    "flag_for_northern_mariana_islands": "🇲🇵",
+    "flag_for_norway": "🇳🇴",
+    "flag_for_oman": "🇴🇲",
+    "flag_for_pakistan": "🇵🇰",
+    "flag_for_palau": "🇵🇼",
+    "flag_for_palestinian_territories": "🇵🇸",
+    "flag_for_panama": "🇵🇦",
+    "flag_for_papua_new_guinea": "🇵🇬",
+    "flag_for_paraguay": "🇵🇾",
+    "flag_for_peru": "🇵🇪",
+    "flag_for_philippines": "🇵🇭",
+    "flag_for_pitcairn_islands": "🇵🇳",
+    "flag_for_poland": "🇵🇱",
+    "flag_for_portugal": "🇵🇹",
+    "flag_for_puerto_rico": "🇵🇷",
+    "flag_for_qatar": "🇶🇦",
+    "flag_for_romania": "🇷🇴",
+    "flag_for_russia": "🇷🇺",
+    "flag_for_rwanda": "🇷🇼",
+    "flag_for_réunion": "🇷🇪",
+    "flag_for_samoa": "🇼🇸",
+    "flag_for_san_marino": "🇸🇲",
+    "flag_for_saudi_arabia": "🇸🇦",
+    "flag_for_senegal": "🇸🇳",
+    "flag_for_serbia": "🇷🇸",
+    "flag_for_seychelles": "🇸🇨",
+    "flag_for_sierra_leone": "🇸🇱",
+    "flag_for_singapore": "🇸🇬",
+    "flag_for_sint_maarten": "🇸🇽",
+    "flag_for_slovakia": "🇸🇰",
+    "flag_for_slovenia": "🇸🇮",
+    "flag_for_solomon_islands": "🇸🇧",
+    "flag_for_somalia": "🇸🇴",
+    "flag_for_south_africa": "🇿🇦",
+    "flag_for_south_georgia_&_south_sandwich_islands": "🇬🇸",
+    "flag_for_south_korea": "🇰🇷",
+    "flag_for_south_sudan": "🇸🇸",
+    "flag_for_spain": "🇪🇸",
+    "flag_for_sri_lanka": "🇱🇰",
+    "flag_for_st._barthélemy": "🇧🇱",
+    "flag_for_st._helena": "🇸🇭",
+    "flag_for_st._kitts_&_nevis": "🇰🇳",
+    "flag_for_st._lucia": "🇱🇨",
+    "flag_for_st._martin": "🇲🇫",
+    "flag_for_st._pierre_&_miquelon": "🇵🇲",
+    "flag_for_st._vincent_&_grenadines": "🇻🇨",
+    "flag_for_sudan": "🇸🇩",
+    "flag_for_suriname": "🇸🇷",
+    "flag_for_svalbard_&_jan_mayen": "🇸🇯",
+    "flag_for_swaziland": "🇸🇿",
+    "flag_for_sweden": "🇸🇪",
+    "flag_for_switzerland": "🇨🇭",
+    "flag_for_syria": "🇸🇾",
+    "flag_for_são_tomé_&_príncipe": "🇸🇹",
+    "flag_for_taiwan": "🇹🇼",
+    "flag_for_tajikistan": "🇹🇯",
+    "flag_for_tanzania": "🇹🇿",
+    "flag_for_thailand": "🇹🇭",
+    "flag_for_timor__leste": "🇹🇱",
+    "flag_for_togo": "🇹🇬",
+    "flag_for_tokelau": "🇹🇰",
+    "flag_for_tonga": "🇹🇴",
+    "flag_for_trinidad_&_tobago": "🇹🇹",
+    "flag_for_tristan_da_cunha": "🇹🇦",
+    "flag_for_tunisia": "🇹🇳",
+    "flag_for_turkey": "🇹🇷",
+    "flag_for_turkmenistan": "🇹🇲",
+    "flag_for_turks_&_caicos_islands": "🇹🇨",
+    "flag_for_tuvalu": "🇹🇻",
+    "flag_for_u.s._outlying_islands": "🇺🇲",
+    "flag_for_u.s._virgin_islands": "🇻🇮",
+    "flag_for_uganda": "🇺🇬",
+    "flag_for_ukraine": "🇺🇦",
+    "flag_for_united_arab_emirates": "🇦🇪",
+    "flag_for_united_kingdom": "🇬🇧",
+    "flag_for_united_states": "🇺🇸",
+    "flag_for_uruguay": "🇺🇾",
+    "flag_for_uzbekistan": "🇺🇿",
+    "flag_for_vanuatu": "🇻🇺",
+    "flag_for_vatican_city": "🇻🇦",
+    "flag_for_venezuela": "🇻🇪",
+    "flag_for_vietnam": "🇻🇳",
+    "flag_for_wallis_&_futuna": "🇼🇫",
+    "flag_for_western_sahara": "🇪🇭",
+    "flag_for_yemen": "🇾🇪",
+    "flag_for_zambia": "🇿🇲",
+    "flag_for_zimbabwe": "🇿🇼",
+    "flag_for_åland_islands": "🇦🇽",
+    "golf": "⛳",
+    "fleur__de__lis": "⚜",
+    "muscle": "💪",
+    "flushed": "😳",
+    "frame_with_picture": "🖼",
+    "fries": "🍟",
+    "frog": "🐸",
+    "hatched_chick": "🐥",
+    "frowning": "😦",
+    "fuelpump": "⛽",
+    "full_moon_with_face": "🌝",
+    "gem": "💎",
+    "star2": "🌟",
+    "golfer": "🏌",
+    "mortar_board": "🎓",
+    "grimacing": "😬",
+    "smile_cat": "😸",
+    "grinning": "😀",
+    "grin": "😁",
+    "heartpulse": "💗",
+    "guardsman": "💂",
+    "haircut": "💇",
+    "hamster": "🐹",
+    "raising_hand": "🙋",
+    "headphones": "🎧",
+    "hear_no_evil": "🙉",
+    "cupid": "💘",
+    "gift_heart": "💝",
+    "heart": "❤",
+    "exclamation": "❗",
+    "heavy_exclamation_mark": "❗",
+    "heavy_heart_exclamation_mark_ornament": "❣",
+    "o": "⭕",
+    "helm_symbol": "⎈",
+    "helmet_with_white_cross": "⛑",
+    "high_heel": "👠",
+    "bullettrain_side": "🚄",
+    "bullettrain_front": "🚅",
+    "high_brightness": "🔆",
+    "zap": "⚡",
+    "hocho": "🔪",
+    "knife": "🔪",
+    "bee": "🐝",
+    "traffic_light": "🚥",
+    "racehorse": "🐎",
+    "coffee": "☕",
+    "hotsprings": "♨",
+    "hourglass": "⌛",
+    "hourglass_flowing_sand": "⏳",
+    "house_buildings": "🏘",
+    "100": "💯",
+    "hushed": "😯",
+    "ice_hockey_stick_and_puck": "🏒",
+    "imp": "👿",
+    "information_desk_person": "💁",
+    "information_source": "ℹ",
+    "capital_abcd": "🔠",
+    "abc": "🔤",
+    "abcd": "🔡",
+    "1234": "🔢",
+    "symbols": "🔣",
+    "izakaya_lantern": "🏮",
+    "lantern": "🏮",
+    "jack_o_lantern": "🎃",
+    "dolls": "🎎",
+    "japanese_goblin": "👺",
+    "japanese_ogre": "👹",
+    "beginner": "🔰",
+    "zero": "0️⃣",
+    "one": "1️⃣",
+    "ten": "🔟",
+    "two": "2️⃣",
+    "three": "3️⃣",
+    "four": "4️⃣",
+    "five": "5️⃣",
+    "six": "6️⃣",
+    "seven": "7️⃣",
+    "eight": "8️⃣",
+    "nine": "9️⃣",
+    "couplekiss": "💏",
+    "kissing_cat": "😽",
+    "kissing": "😗",
+    "kissing_closed_eyes": "😚",
+    "kissing_smiling_eyes": "😙",
+    "beetle": "🐞",
+    "large_blue_circle": "🔵",
+    "last_quarter_moon_with_face": "🌜",
+    "leaves": "🍃",
+    "mag": "🔍",
+    "left_right_arrow": "↔",
+    "leftwards_arrow_with_hook": "↩",
+    "arrow_left": "⬅",
+    "lock": "🔒",
+    "lock_with_ink_pen": "🔏",
+    "sob": "😭",
+    "low_brightness": "🔅",
+    "lower_left_ballpoint_pen": "🖊",
+    "lower_left_crayon": "🖍",
+    "lower_left_fountain_pen": "🖋",
+    "lower_left_paintbrush": "🖌",
+    "mahjong": "🀄",
+    "couple": "👫",
+    "man_in_business_suit_levitating": "🕴",
+    "man_with_gua_pi_mao": "👲",
+    "man_with_turban": "👳",
+    "mans_shoe": "👞",
+    "shoe": "👞",
+    "menorah_with_nine_branches": "🕎",
+    "mens": "🚹",
+    "minidisc": "💽",
+    "iphone": "📱",
+    "calling": "📲",
+    "money__mouth_face": "🤑",
+    "moneybag": "💰",
+    "rice_scene": "🎑",
+    "mountain_bicyclist": "🚵",
+    "mouse2": "🐁",
+    "lips": "👄",
+    "moyai": "🗿",
+    "notes": "🎶",
+    "nail_care": "💅",
+    "ab": "🆎",
+    "negative_squared_cross_mark": "❎",
+    "a": "🅰",
+    "b": "🅱",
+    "o2": "🅾",
+    "parking": "🅿",
+    "new_moon_with_face": "🌚",
+    "no_entry_sign": "🚫",
+    "underage": "🔞",
+    "non__potable_water": "🚱",
+    "arrow_upper_right": "↗",
+    "arrow_upper_left": "↖",
+    "office": "🏢",
+    "older_man": "👴",
+    "older_woman": "👵",
+    "om_symbol": "🕉",
+    "on": "🔛",
+    "book": "📖",
+    "unlock": "🔓",
+    "mailbox_with_no_mail": "📭",
+    "mailbox_with_mail": "📬",
+    "cd": "💿",
+    "tada": "🎉",
+    "feet": "🐾",
+    "walking": "🚶",
+    "pencil2": "✏",
+    "pensive": "😔",
+    "persevere": "😣",
+    "bow": "🙇",
+    "raised_hands": "🙌",
+    "person_with_ball": "⛹",
+    "person_with_blond_hair": "👱",
+    "pray": "🙏",
+    "person_with_pouting_face": "🙎",
+    "computer": "💻",
+    "pig2": "🐖",
+    "hankey": "💩",
+    "poop": "💩",
+    "shit": "💩",
+    "bamboo": "🎍",
+    "gun": "🔫",
+    "black_joker": "🃏",
+    "rotating_light": "🚨",
+    "cop": "👮",
+    "stew": "🍲",
+    "pouch": "👝",
+    "pouting_cat": "😾",
+    "rage": "😡",
+    "put_litter_in_its_place": "🚮",
+    "rabbit2": "🐇",
+    "racing_motorcycle": "🏍",
+    "radioactive_sign": "☢",
+    "fist": "✊",
+    "hand": "✋",
+    "raised_hand_with_fingers_splayed": "🖐",
+    "raised_hand_with_part_between_middle_and_ring_fingers": "🖖",
+    "blue_car": "🚙",
+    "apple": "🍎",
+    "relieved": "😌",
+    "reversed_hand_with_middle_finger_extended": "🖕",
+    "mag_right": "🔎",
+    "arrow_right_hook": "↪",
+    "sweet_potato": "🍠",
+    "robot": "🤖",
+    "rolled__up_newspaper": "🗞",
+    "rowboat": "🚣",
+    "runner": "🏃",
+    "running": "🏃",
+    "running_shirt_with_sash": "🎽",
+    "boat": "⛵",
+    "scales": "⚖",
+    "school_satchel": "🎒",
+    "scorpius": "♏",
+    "see_no_evil": "🙈",
+    "sheep": "🐑",
+    "stars": "🌠",
+    "cake": "🍰",
+    "six_pointed_star": "🔯",
+    "ski": "🎿",
+    "sleeping_accommodation": "🛌",
+    "sleeping": "😴",
+    "sleepy": "😪",
+    "sleuth_or_spy": "🕵",
+    "heart_eyes_cat": "😻",
+    "smiley_cat": "😺",
+    "innocent": "😇",
+    "heart_eyes": "😍",
+    "smiling_imp": "😈",
+    "smiley": "😃",
+    "sweat_smile": "😅",
+    "smile": "😄",
+    "laughing": "😆",
+    "satisfied": "😆",
+    "blush": "😊",
+    "smirk": "😏",
+    "smoking": "🚬",
+    "snow_capped_mountain": "🏔",
+    "soccer": "⚽",
+    "icecream": "🍦",
+    "soon": "🔜",
+    "arrow_lower_right": "↘",
+    "arrow_lower_left": "↙",
+    "speak_no_evil": "🙊",
+    "speaker": "🔈",
+    "mute": "🔇",
+    "sound": "🔉",
+    "loud_sound": "🔊",
+    "speaking_head_in_silhouette": "🗣",
+    "spiral_calendar_pad": "🗓",
+    "spiral_note_pad": "🗒",
+    "shell": "🐚",
+    "sweat_drops": "💦",
+    "u5272": "🈹",
+    "u5408": "🈴",
+    "u55b6": "🈺",
+    "u6307": "🈯",
+    "u6708": "🈷",
+    "u6709": "🈶",
+    "u6e80": "🈵",
+    "u7121": "🈚",
+    "u7533": "🈸",
+    "u7981": "🈲",
+    "u7a7a": "🈳",
+    "cl": "🆑",
+    "cool": "🆒",
+    "free": "🆓",
+    "id": "🆔",
+    "koko": "🈁",
+    "sa": "🈂",
+    "new": "🆕",
+    "ng": "🆖",
+    "ok": "🆗",
+    "sos": "🆘",
+    "up": "🆙",
+    "vs": "🆚",
+    "steam_locomotive": "🚂",
+    "ramen": "🍜",
+    "partly_sunny": "⛅",
+    "city_sunrise": "🌇",
+    "surfer": "🏄",
+    "swimmer": "🏊",
+    "shirt": "👕",
+    "tshirt": "👕",
+    "table_tennis_paddle_and_ball": "🏓",
+    "tea": "🍵",
+    "tv": "📺",
+    "three_button_mouse": "🖱",
+    "+1": "👍",
+    "thumbsup": "👍",
+    "__1": "👎",
+    "-1": "👎",
+    "thumbsdown": "👎",
+    "thunder_cloud_and_rain": "⛈",
+    "tiger2": "🐅",
+    "tophat": "🎩",
+    "top": "🔝",
+    "tm": "™",
+    "train2": "🚆",
+    "triangular_flag_on_post": "🚩",
+    "trident": "🔱",
+    "twisted_rightwards_arrows": "🔀",
+    "unamused": "😒",
+    "small_red_triangle": "🔺",
+    "arrow_up_small": "🔼",
+    "arrow_up_down": "↕",
+    "upside__down_face": "🙃",
+    "arrow_up": "⬆",
+    "v": "✌",
+    "vhs": "📼",
+    "wc": "🚾",
+    "ocean": "🌊",
+    "waving_black_flag": "🏴",
+    "wave": "👋",
+    "waving_white_flag": "🏳",
+    "moon": "🌔",
+    "scream_cat": "🙀",
+    "weary": "😩",
+    "weight_lifter": "🏋",
+    "whale2": "🐋",
+    "wheelchair": "♿",
+    "point_down": "👇",
+    "grey_exclamation": "❕",
+    "white_frowning_face": "☹",
+    "white_check_mark": "✅",
+    "point_left": "👈",
+    "white_medium_small_square": "◽",
+    "star": "⭐",
+    "grey_question": "❔",
+    "point_right": "👉",
+    "relaxed": "☺",
+    "white_sun_behind_cloud": "🌥",
+    "white_sun_behind_cloud_with_rain": "🌦",
+    "white_sun_with_small_cloud": "🌤",
+    "point_up_2": "👆",
+    "point_up": "☝",
+    "wind_blowing_face": "🌬",
+    "wink": "😉",
+    "wolf": "🐺",
+    "dancers": "👯",
+    "boot": "👢",
+    "womans_clothes": "👚",
+    "womans_hat": "👒",
+    "sandal": "👡",
+    "womens": "🚺",
+    "worried": "😟",
+    "gift": "🎁",
+    "zipper__mouth_face": "🤐",
+    "regional_indicator_a": "🇦",
+    "regional_indicator_b": "🇧",
+    "regional_indicator_c": "🇨",
+    "regional_indicator_d": "🇩",
+    "regional_indicator_e": "🇪",
+    "regional_indicator_f": "🇫",
+    "regional_indicator_g": "🇬",
+    "regional_indicator_h": "🇭",
+    "regional_indicator_i": "🇮",
+    "regional_indicator_j": "🇯",
+    "regional_indicator_k": "🇰",
+    "regional_indicator_l": "🇱",
+    "regional_indicator_m": "🇲",
+    "regional_indicator_n": "🇳",
+    "regional_indicator_o": "🇴",
+    "regional_indicator_p": "🇵",
+    "regional_indicator_q": "🇶",
+    "regional_indicator_r": "🇷",
+    "regional_indicator_s": "🇸",
+    "regional_indicator_t": "🇹",
+    "regional_indicator_u": "🇺",
+    "regional_indicator_v": "🇻",
+    "regional_indicator_w": "🇼",
+    "regional_indicator_x": "🇽",
+    "regional_indicator_y": "🇾",
+    "regional_indicator_z": "🇿",
+}
diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_emoji_replace.py b/data/miniconda3/lib/python3.13/site-packages/rich/_emoji_replace.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb2cafa18011e7115773055338291c366f173d6f
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/rich/_emoji_replace.py
@@ -0,0 +1,32 @@
+from typing import Callable, Match, Optional
+import re
+
+from ._emoji_codes import EMOJI
+
+
+_ReStringMatch = Match[str]  # regex match object
+_ReSubCallable = Callable[[_ReStringMatch], str]  # Callable invoked by re.sub
+_EmojiSubMethod = Callable[[_ReSubCallable, str], str]  # Sub method of a compiled re
+
+
+def _emoji_replace(
+    text: str,
+    default_variant: Optional[str] = None,
+    _emoji_sub: _EmojiSubMethod = re.compile(r"(:(\S*?)(?:(?:\-)(emoji|text))?:)").sub,
+) -> str:
+    """Replace emoji code in text."""
+    get_emoji = EMOJI.__getitem__
+    variants = {"text": "\uFE0E", "emoji": "\uFE0F"}
+    get_variant = variants.get
+    default_variant_code = variants.get(default_variant, "") if default_variant else ""
+
+    def do_replace(match: Match[str]) -> str:
+        emoji_code, emoji_name, variant = match.groups()
+        try:
+            return get_emoji(emoji_name.lower()) + get_variant(
+                variant, default_variant_code
+            )
+        except KeyError:
+            return emoji_code
+
+    return _emoji_sub(do_replace, text)
diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_export_format.py b/data/miniconda3/lib/python3.13/site-packages/rich/_export_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7527e52f6613328630fc6305f957d9ea58027d8
--- /dev/null
+++ b/data/miniconda3/lib/python3.13/site-packages/rich/_export_format.py
@@ -0,0 +1,76 @@
+CONSOLE_HTML_FORMAT = """\
+
+
+
+
+
+
+
+    
{code}
+ + +""" + +CONSOLE_SVG_FORMAT = """\ + + + + + + + + + {lines} + + + {chrome} + + {backgrounds} + + {matrix} + + + +""" + +_SVG_FONT_FAMILY = "Rich Fira Code" +_SVG_CLASSES_PREFIX = "rich-svg" diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_extension.py b/data/miniconda3/lib/python3.13/site-packages/rich/_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..38658864eb1e9b9839e953e070af11c8bc0d1836 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_extension.py @@ -0,0 +1,10 @@ +from typing import Any + + +def load_ipython_extension(ip: Any) -> None: # pragma: no cover + # prevent circular import + from rich.pretty import install + from rich.traceback import install as tr_install + + install() + tr_install() diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_fileno.py b/data/miniconda3/lib/python3.13/site-packages/rich/_fileno.py new file mode 100644 index 0000000000000000000000000000000000000000..b17ee6511742d7a8d5950bf0ee57ced4d5fd45c2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_fileno.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing import IO, Callable + + +def get_fileno(file_like: IO[str]) -> int | None: + """Get fileno() from a file, accounting for poorly implemented file-like objects. + + Args: + file_like (IO): A file-like object. + + Returns: + int | None: The result of fileno if available, or None if operation failed. + """ + fileno: Callable[[], int] | None = getattr(file_like, "fileno", None) + if fileno is not None: + try: + return fileno() + except Exception: + # `fileno` is documented as potentially raising a OSError + # Alas, from the issues, there are so many poorly implemented file-like objects, + # that `fileno()` can raise just about anything. + return None + return None diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_inspect.py b/data/miniconda3/lib/python3.13/site-packages/rich/_inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..27d65cec93bda5c7a97c2bb2117938dc0142ff8b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_inspect.py @@ -0,0 +1,268 @@ +import inspect +from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature +from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union + +from .console import Group, RenderableType +from .control import escape_control_codes +from .highlighter import ReprHighlighter +from .jupyter import JupyterMixin +from .panel import Panel +from .pretty import Pretty +from .table import Table +from .text import Text, TextType + + +def _first_paragraph(doc: str) -> str: + """Get the first paragraph from a docstring.""" + paragraph, _, _ = doc.partition("\n\n") + return paragraph + + +class Inspect(JupyterMixin): + """A renderable to inspect any Python Object. + + Args: + obj (Any): An object to inspect. + title (str, optional): Title to display over inspect result, or None use type. Defaults to None. + help (bool, optional): Show full help text rather than just first paragraph. Defaults to False. + methods (bool, optional): Enable inspection of callables. Defaults to False. + docs (bool, optional): Also render doc strings. Defaults to True. + private (bool, optional): Show private attributes (beginning with underscore). Defaults to False. + dunder (bool, optional): Show attributes starting with double underscore. Defaults to False. + sort (bool, optional): Sort attributes alphabetically. Defaults to True. + all (bool, optional): Show all attributes. Defaults to False. + value (bool, optional): Pretty print value of object. Defaults to True. + """ + + def __init__( + self, + obj: Any, + *, + title: Optional[TextType] = None, + help: bool = False, + methods: bool = False, + docs: bool = True, + private: bool = False, + dunder: bool = False, + sort: bool = True, + all: bool = True, + value: bool = True, + ) -> None: + self.highlighter = ReprHighlighter() + self.obj = obj + self.title = title or self._make_title(obj) + if all: + methods = private = dunder = True + self.help = help + self.methods = methods + self.docs = docs or help + self.private = private or dunder + self.dunder = dunder + self.sort = sort + self.value = value + + def _make_title(self, obj: Any) -> Text: + """Make a default title.""" + title_str = ( + str(obj) + if (isclass(obj) or callable(obj) or ismodule(obj)) + else str(type(obj)) + ) + title_text = self.highlighter(title_str) + return title_text + + def __rich__(self) -> Panel: + return Panel.fit( + Group(*self._render()), + title=self.title, + border_style="scope.border", + padding=(0, 1), + ) + + def _get_signature(self, name: str, obj: Any) -> Optional[Text]: + """Get a signature for a callable.""" + try: + _signature = str(signature(obj)) + ":" + except ValueError: + _signature = "(...)" + except TypeError: + return None + + source_filename: Optional[str] = None + try: + source_filename = getfile(obj) + except (OSError, TypeError): + # OSError is raised if obj has no source file, e.g. when defined in REPL. + pass + + callable_name = Text(name, style="inspect.callable") + if source_filename: + callable_name.stylize(f"link file://{source_filename}") + signature_text = self.highlighter(_signature) + + qualname = name or getattr(obj, "__qualname__", name) + + # If obj is a module, there may be classes (which are callable) to display + if inspect.isclass(obj): + prefix = "class" + elif inspect.iscoroutinefunction(obj): + prefix = "async def" + else: + prefix = "def" + + qual_signature = Text.assemble( + (f"{prefix} ", f"inspect.{prefix.replace(' ', '_')}"), + (qualname, "inspect.callable"), + signature_text, + ) + + return qual_signature + + def _render(self) -> Iterable[RenderableType]: + """Render object.""" + + def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]: + key, (_error, value) = item + return (callable(value), key.strip("_").lower()) + + def safe_getattr(attr_name: str) -> Tuple[Any, Any]: + """Get attribute or any exception.""" + try: + return (None, getattr(obj, attr_name)) + except Exception as error: + return (error, None) + + obj = self.obj + keys = dir(obj) + total_items = len(keys) + if not self.dunder: + keys = [key for key in keys if not key.startswith("__")] + if not self.private: + keys = [key for key in keys if not key.startswith("_")] + not_shown_count = total_items - len(keys) + items = [(key, safe_getattr(key)) for key in keys] + if self.sort: + items.sort(key=sort_items) + + items_table = Table.grid(padding=(0, 1), expand=False) + items_table.add_column(justify="right") + add_row = items_table.add_row + highlighter = self.highlighter + + if callable(obj): + signature = self._get_signature("", obj) + if signature is not None: + yield signature + yield "" + + if self.docs: + _doc = self._get_formatted_doc(obj) + if _doc is not None: + doc_text = Text(_doc, style="inspect.help") + doc_text = highlighter(doc_text) + yield doc_text + yield "" + + if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)): + yield Panel( + Pretty(obj, indent_guides=True, max_length=10, max_string=60), + border_style="inspect.value.border", + ) + yield "" + + for key, (error, value) in items: + key_text = Text.assemble( + ( + key, + "inspect.attr.dunder" if key.startswith("__") else "inspect.attr", + ), + (" =", "inspect.equals"), + ) + if error is not None: + warning = key_text.copy() + warning.stylize("inspect.error") + add_row(warning, highlighter(repr(error))) + continue + + if callable(value): + if not self.methods: + continue + + _signature_text = self._get_signature(key, value) + if _signature_text is None: + add_row(key_text, Pretty(value, highlighter=highlighter)) + else: + if self.docs: + docs = self._get_formatted_doc(value) + if docs is not None: + _signature_text.append("\n" if "\n" in docs else " ") + doc = highlighter(docs) + doc.stylize("inspect.doc") + _signature_text.append(doc) + + add_row(key_text, _signature_text) + else: + add_row(key_text, Pretty(value, highlighter=highlighter)) + if items_table.row_count: + yield items_table + elif not_shown_count: + yield Text.from_markup( + f"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] " + f"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options." + ) + + def _get_formatted_doc(self, object_: Any) -> Optional[str]: + """ + Extract the docstring of an object, process it and returns it. + The processing consists in cleaning up the docstring's indentation, + taking only its 1st paragraph if `self.help` is not True, + and escape its control codes. + + Args: + object_ (Any): the object to get the docstring from. + + Returns: + Optional[str]: the processed docstring, or None if no docstring was found. + """ + docs = getdoc(object_) + if docs is None: + return None + docs = cleandoc(docs).strip() + if not self.help: + docs = _first_paragraph(docs) + return escape_control_codes(docs) + + +def get_object_types_mro(obj: Union[object, Type[Any]]) -> Tuple[type, ...]: + """Returns the MRO of an object's class, or of the object itself if it's a class.""" + if not hasattr(obj, "__mro__"): + # N.B. we cannot use `if type(obj) is type` here because it doesn't work with + # some types of classes, such as the ones that use abc.ABCMeta. + obj = type(obj) + return getattr(obj, "__mro__", ()) + + +def get_object_types_mro_as_strings(obj: object) -> Collection[str]: + """ + Returns the MRO of an object's class as full qualified names, or of the object itself if it's a class. + + Examples: + `object_types_mro_as_strings(JSONDecoder)` will return `['json.decoder.JSONDecoder', 'builtins.object']` + """ + return [ + f'{getattr(type_, "__module__", "")}.{getattr(type_, "__qualname__", "")}' + for type_ in get_object_types_mro(obj) + ] + + +def is_object_one_of_types( + obj: object, fully_qualified_types_names: Collection[str] +) -> bool: + """ + Returns `True` if the given object's class (or the object itself, if it's a class) has one of the + fully qualified names in its MRO. + """ + for type_name in get_object_types_mro_as_strings(obj): + if type_name in fully_qualified_types_names: + return True + return False diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_log_render.py b/data/miniconda3/lib/python3.13/site-packages/rich/_log_render.py new file mode 100644 index 0000000000000000000000000000000000000000..e8810100b323450c63507e16629a09bb2e9dc97f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_log_render.py @@ -0,0 +1,94 @@ +from datetime import datetime +from typing import Iterable, List, Optional, TYPE_CHECKING, Union, Callable + + +from .text import Text, TextType + +if TYPE_CHECKING: + from .console import Console, ConsoleRenderable, RenderableType + from .table import Table + +FormatTimeCallable = Callable[[datetime], Text] + + +class LogRender: + def __init__( + self, + show_time: bool = True, + show_level: bool = False, + show_path: bool = True, + time_format: Union[str, FormatTimeCallable] = "[%x %X]", + omit_repeated_times: bool = True, + level_width: Optional[int] = 8, + ) -> None: + self.show_time = show_time + self.show_level = show_level + self.show_path = show_path + self.time_format = time_format + self.omit_repeated_times = omit_repeated_times + self.level_width = level_width + self._last_time: Optional[Text] = None + + def __call__( + self, + console: "Console", + renderables: Iterable["ConsoleRenderable"], + log_time: Optional[datetime] = None, + time_format: Optional[Union[str, FormatTimeCallable]] = None, + level: TextType = "", + path: Optional[str] = None, + line_no: Optional[int] = None, + link_path: Optional[str] = None, + ) -> "Table": + from .containers import Renderables + from .table import Table + + output = Table.grid(padding=(0, 1)) + output.expand = True + if self.show_time: + output.add_column(style="log.time") + if self.show_level: + output.add_column(style="log.level", width=self.level_width) + output.add_column(ratio=1, style="log.message", overflow="fold") + if self.show_path and path: + output.add_column(style="log.path") + row: List["RenderableType"] = [] + if self.show_time: + log_time = log_time or console.get_datetime() + time_format = time_format or self.time_format + if callable(time_format): + log_time_display = time_format(log_time) + else: + log_time_display = Text(log_time.strftime(time_format)) + if log_time_display == self._last_time and self.omit_repeated_times: + row.append(Text(" " * len(log_time_display))) + else: + row.append(log_time_display) + self._last_time = log_time_display + if self.show_level: + row.append(level) + + row.append(Renderables(renderables)) + if self.show_path and path: + path_text = Text() + path_text.append( + path, style=f"link file://{link_path}" if link_path else "" + ) + if line_no: + path_text.append(":") + path_text.append( + f"{line_no}", + style=f"link file://{link_path}#{line_no}" if link_path else "", + ) + row.append(path_text) + + output.add_row(*row) + return output + + +if __name__ == "__main__": # pragma: no cover + from rich.console import Console + + c = Console() + c.print("[on blue]Hello", justify="right") + c.log("[on blue]hello", justify="right") diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_loop.py b/data/miniconda3/lib/python3.13/site-packages/rich/_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..01c6cafbe53f1fcb12f7b382b2b35e2fd2c69933 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_loop.py @@ -0,0 +1,43 @@ +from typing import Iterable, Tuple, TypeVar + +T = TypeVar("T") + + +def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: + """Iterate and generate a tuple with a flag for first value.""" + iter_values = iter(values) + try: + value = next(iter_values) + except StopIteration: + return + yield True, value + for value in iter_values: + yield False, value + + +def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]: + """Iterate and generate a tuple with a flag for last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + for value in iter_values: + yield False, previous_value + previous_value = value + yield True, previous_value + + +def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_null_file.py b/data/miniconda3/lib/python3.13/site-packages/rich/_null_file.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae05d3e2a901af754b1626d911ebc3c45e22a40 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_null_file.py @@ -0,0 +1,69 @@ +from types import TracebackType +from typing import IO, Iterable, Iterator, List, Optional, Type + + +class NullFile(IO[str]): + def close(self) -> None: + pass + + def isatty(self) -> bool: + return False + + def read(self, __n: int = 1) -> str: + return "" + + def readable(self) -> bool: + return False + + def readline(self, __limit: int = 1) -> str: + return "" + + def readlines(self, __hint: int = 1) -> List[str]: + return [] + + def seek(self, __offset: int, __whence: int = 1) -> int: + return 0 + + def seekable(self) -> bool: + return False + + def tell(self) -> int: + return 0 + + def truncate(self, __size: Optional[int] = 1) -> int: + return 0 + + def writable(self) -> bool: + return False + + def writelines(self, __lines: Iterable[str]) -> None: + pass + + def __next__(self) -> str: + return "" + + def __iter__(self) -> Iterator[str]: + return iter([""]) + + def __enter__(self) -> IO[str]: + return self + + def __exit__( + self, + __t: Optional[Type[BaseException]], + __value: Optional[BaseException], + __traceback: Optional[TracebackType], + ) -> None: + pass + + def write(self, text: str) -> int: + return 0 + + def flush(self) -> None: + pass + + def fileno(self) -> int: + return -1 + + +NULL_FILE = NullFile() diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_palettes.py b/data/miniconda3/lib/python3.13/site-packages/rich/_palettes.py new file mode 100644 index 0000000000000000000000000000000000000000..3c748d33e45bfcdc690ceee490cbb50b516cd2b3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_palettes.py @@ -0,0 +1,309 @@ +from .palette import Palette + + +# Taken from https://en.wikipedia.org/wiki/ANSI_escape_code (Windows 10 column) +WINDOWS_PALETTE = Palette( + [ + (12, 12, 12), + (197, 15, 31), + (19, 161, 14), + (193, 156, 0), + (0, 55, 218), + (136, 23, 152), + (58, 150, 221), + (204, 204, 204), + (118, 118, 118), + (231, 72, 86), + (22, 198, 12), + (249, 241, 165), + (59, 120, 255), + (180, 0, 158), + (97, 214, 214), + (242, 242, 242), + ] +) + +# # The standard ansi colors (including bright variants) +STANDARD_PALETTE = Palette( + [ + (0, 0, 0), + (170, 0, 0), + (0, 170, 0), + (170, 85, 0), + (0, 0, 170), + (170, 0, 170), + (0, 170, 170), + (170, 170, 170), + (85, 85, 85), + (255, 85, 85), + (85, 255, 85), + (255, 255, 85), + (85, 85, 255), + (255, 85, 255), + (85, 255, 255), + (255, 255, 255), + ] +) + + +# The 256 color palette +EIGHT_BIT_PALETTE = Palette( + [ + (0, 0, 0), + (128, 0, 0), + (0, 128, 0), + (128, 128, 0), + (0, 0, 128), + (128, 0, 128), + (0, 128, 128), + (192, 192, 192), + (128, 128, 128), + (255, 0, 0), + (0, 255, 0), + (255, 255, 0), + (0, 0, 255), + (255, 0, 255), + (0, 255, 255), + (255, 255, 255), + (0, 0, 0), + (0, 0, 95), + (0, 0, 135), + (0, 0, 175), + (0, 0, 215), + (0, 0, 255), + (0, 95, 0), + (0, 95, 95), + (0, 95, 135), + (0, 95, 175), + (0, 95, 215), + (0, 95, 255), + (0, 135, 0), + (0, 135, 95), + (0, 135, 135), + (0, 135, 175), + (0, 135, 215), + (0, 135, 255), + (0, 175, 0), + (0, 175, 95), + (0, 175, 135), + (0, 175, 175), + (0, 175, 215), + (0, 175, 255), + (0, 215, 0), + (0, 215, 95), + (0, 215, 135), + (0, 215, 175), + (0, 215, 215), + (0, 215, 255), + (0, 255, 0), + (0, 255, 95), + (0, 255, 135), + (0, 255, 175), + (0, 255, 215), + (0, 255, 255), + (95, 0, 0), + (95, 0, 95), + (95, 0, 135), + (95, 0, 175), + (95, 0, 215), + (95, 0, 255), + (95, 95, 0), + (95, 95, 95), + (95, 95, 135), + (95, 95, 175), + (95, 95, 215), + (95, 95, 255), + (95, 135, 0), + (95, 135, 95), + (95, 135, 135), + (95, 135, 175), + (95, 135, 215), + (95, 135, 255), + (95, 175, 0), + (95, 175, 95), + (95, 175, 135), + (95, 175, 175), + (95, 175, 215), + (95, 175, 255), + (95, 215, 0), + (95, 215, 95), + (95, 215, 135), + (95, 215, 175), + (95, 215, 215), + (95, 215, 255), + (95, 255, 0), + (95, 255, 95), + (95, 255, 135), + (95, 255, 175), + (95, 255, 215), + (95, 255, 255), + (135, 0, 0), + (135, 0, 95), + (135, 0, 135), + (135, 0, 175), + (135, 0, 215), + (135, 0, 255), + (135, 95, 0), + (135, 95, 95), + (135, 95, 135), + (135, 95, 175), + (135, 95, 215), + (135, 95, 255), + (135, 135, 0), + (135, 135, 95), + (135, 135, 135), + (135, 135, 175), + (135, 135, 215), + (135, 135, 255), + (135, 175, 0), + (135, 175, 95), + (135, 175, 135), + (135, 175, 175), + (135, 175, 215), + (135, 175, 255), + (135, 215, 0), + (135, 215, 95), + (135, 215, 135), + (135, 215, 175), + (135, 215, 215), + (135, 215, 255), + (135, 255, 0), + (135, 255, 95), + (135, 255, 135), + (135, 255, 175), + (135, 255, 215), + (135, 255, 255), + (175, 0, 0), + (175, 0, 95), + (175, 0, 135), + (175, 0, 175), + (175, 0, 215), + (175, 0, 255), + (175, 95, 0), + (175, 95, 95), + (175, 95, 135), + (175, 95, 175), + (175, 95, 215), + (175, 95, 255), + (175, 135, 0), + (175, 135, 95), + (175, 135, 135), + (175, 135, 175), + (175, 135, 215), + (175, 135, 255), + (175, 175, 0), + (175, 175, 95), + (175, 175, 135), + (175, 175, 175), + (175, 175, 215), + (175, 175, 255), + (175, 215, 0), + (175, 215, 95), + (175, 215, 135), + (175, 215, 175), + (175, 215, 215), + (175, 215, 255), + (175, 255, 0), + (175, 255, 95), + (175, 255, 135), + (175, 255, 175), + (175, 255, 215), + (175, 255, 255), + (215, 0, 0), + (215, 0, 95), + (215, 0, 135), + (215, 0, 175), + (215, 0, 215), + (215, 0, 255), + (215, 95, 0), + (215, 95, 95), + (215, 95, 135), + (215, 95, 175), + (215, 95, 215), + (215, 95, 255), + (215, 135, 0), + (215, 135, 95), + (215, 135, 135), + (215, 135, 175), + (215, 135, 215), + (215, 135, 255), + (215, 175, 0), + (215, 175, 95), + (215, 175, 135), + (215, 175, 175), + (215, 175, 215), + (215, 175, 255), + (215, 215, 0), + (215, 215, 95), + (215, 215, 135), + (215, 215, 175), + (215, 215, 215), + (215, 215, 255), + (215, 255, 0), + (215, 255, 95), + (215, 255, 135), + (215, 255, 175), + (215, 255, 215), + (215, 255, 255), + (255, 0, 0), + (255, 0, 95), + (255, 0, 135), + (255, 0, 175), + (255, 0, 215), + (255, 0, 255), + (255, 95, 0), + (255, 95, 95), + (255, 95, 135), + (255, 95, 175), + (255, 95, 215), + (255, 95, 255), + (255, 135, 0), + (255, 135, 95), + (255, 135, 135), + (255, 135, 175), + (255, 135, 215), + (255, 135, 255), + (255, 175, 0), + (255, 175, 95), + (255, 175, 135), + (255, 175, 175), + (255, 175, 215), + (255, 175, 255), + (255, 215, 0), + (255, 215, 95), + (255, 215, 135), + (255, 215, 175), + (255, 215, 215), + (255, 215, 255), + (255, 255, 0), + (255, 255, 95), + (255, 255, 135), + (255, 255, 175), + (255, 255, 215), + (255, 255, 255), + (8, 8, 8), + (18, 18, 18), + (28, 28, 28), + (38, 38, 38), + (48, 48, 48), + (58, 58, 58), + (68, 68, 68), + (78, 78, 78), + (88, 88, 88), + (98, 98, 98), + (108, 108, 108), + (118, 118, 118), + (128, 128, 128), + (138, 138, 138), + (148, 148, 148), + (158, 158, 158), + (168, 168, 168), + (178, 178, 178), + (188, 188, 188), + (198, 198, 198), + (208, 208, 208), + (218, 218, 218), + (228, 228, 228), + (238, 238, 238), + ] +) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_pick.py b/data/miniconda3/lib/python3.13/site-packages/rich/_pick.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6d8b2d79406012c5f8bae9c289ed5bf4d179cc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_pick.py @@ -0,0 +1,17 @@ +from typing import Optional + + +def pick_bool(*values: Optional[bool]) -> bool: + """Pick the first non-none bool or return the last value. + + Args: + *values (bool): Any number of boolean or None values. + + Returns: + bool: First non-none boolean. + """ + assert values, "1 or more values required" + for value in values: + if value is not None: + return value + return bool(value) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_ratio.py b/data/miniconda3/lib/python3.13/site-packages/rich/_ratio.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd5a383d22367f4167731465a12a74a20a8cda4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_ratio.py @@ -0,0 +1,153 @@ +from fractions import Fraction +from math import ceil +from typing import cast, List, Optional, Sequence, Protocol + + +class Edge(Protocol): + """Any object that defines an edge (such as Layout).""" + + size: Optional[int] = None + ratio: int = 1 + minimum_size: int = 1 + + +def ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]: + """Divide total space to satisfy size, ratio, and minimum_size, constraints. + + The returned list of integers should add up to total in most cases, unless it is + impossible to satisfy all the constraints. For instance, if there are two edges + with a minimum size of 20 each and `total` is 30 then the returned list will be + greater than total. In practice, this would mean that a Layout object would + clip the rows that would overflow the screen height. + + Args: + total (int): Total number of characters. + edges (List[Edge]): Edges within total space. + + Returns: + List[int]: Number of characters for each edge. + """ + # Size of edge or None for yet to be determined + sizes = [(edge.size or None) for edge in edges] + + _Fraction = Fraction + + # While any edges haven't been calculated + while None in sizes: + # Get flexible edges and index to map these back on to sizes list + flexible_edges = [ + (index, edge) + for index, (size, edge) in enumerate(zip(sizes, edges)) + if size is None + ] + # Remaining space in total + remaining = total - sum(size or 0 for size in sizes) + if remaining <= 0: + # No room for flexible edges + return [ + ((edge.minimum_size or 1) if size is None else size) + for size, edge in zip(sizes, edges) + ] + # Calculate number of characters in a ratio portion + portion = _Fraction( + remaining, sum((edge.ratio or 1) for _, edge in flexible_edges) + ) + + # If any edges will be less than their minimum, replace size with the minimum + for index, edge in flexible_edges: + if portion * edge.ratio <= edge.minimum_size: + sizes[index] = edge.minimum_size + # New fixed size will invalidate calculations, so we need to repeat the process + break + else: + # Distribute flexible space and compensate for rounding error + # Since edge sizes can only be integers we need to add the remainder + # to the following line + remainder = _Fraction(0) + for index, edge in flexible_edges: + size, remainder = divmod(portion * edge.ratio + remainder, 1) + sizes[index] = size + break + # Sizes now contains integers only + return cast(List[int], sizes) + + +def ratio_reduce( + total: int, ratios: List[int], maximums: List[int], values: List[int] +) -> List[int]: + """Divide an integer total in to parts based on ratios. + + Args: + total (int): The total to divide. + ratios (List[int]): A list of integer ratios. + maximums (List[int]): List of maximums values for each slot. + values (List[int]): List of values + + Returns: + List[int]: A list of integers guaranteed to sum to total. + """ + ratios = [ratio if _max else 0 for ratio, _max in zip(ratios, maximums)] + total_ratio = sum(ratios) + if not total_ratio: + return values[:] + total_remaining = total + result: List[int] = [] + append = result.append + for ratio, maximum, value in zip(ratios, maximums, values): + if ratio and total_ratio > 0: + distributed = min(maximum, round(ratio * total_remaining / total_ratio)) + append(value - distributed) + total_remaining -= distributed + total_ratio -= ratio + else: + append(value) + return result + + +def ratio_distribute( + total: int, ratios: List[int], minimums: Optional[List[int]] = None +) -> List[int]: + """Distribute an integer total in to parts based on ratios. + + Args: + total (int): The total to divide. + ratios (List[int]): A list of integer ratios. + minimums (List[int]): List of minimum values for each slot. + + Returns: + List[int]: A list of integers guaranteed to sum to total. + """ + if minimums: + ratios = [ratio if _min else 0 for ratio, _min in zip(ratios, minimums)] + total_ratio = sum(ratios) + assert total_ratio > 0, "Sum of ratios must be > 0" + + total_remaining = total + distributed_total: List[int] = [] + append = distributed_total.append + if minimums is None: + _minimums = [0] * len(ratios) + else: + _minimums = minimums + for ratio, minimum in zip(ratios, _minimums): + if total_ratio > 0: + distributed = max(minimum, ceil(ratio * total_remaining / total_ratio)) + else: + distributed = total_remaining + append(distributed) + total_ratio -= ratio + total_remaining -= distributed + return distributed_total + + +if __name__ == "__main__": + from dataclasses import dataclass + + @dataclass + class E: + size: Optional[int] = None + ratio: int = 1 + minimum_size: int = 1 + + resolved = ratio_resolve(110, [E(None, 1, 1), E(None, 1, 1), E(None, 1, 1)]) + print(sum(resolved)) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_spinners.py b/data/miniconda3/lib/python3.13/site-packages/rich/_spinners.py new file mode 100644 index 0000000000000000000000000000000000000000..d0bb1fe751677f0ee83fc6bb876ed72443fdcde7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_spinners.py @@ -0,0 +1,482 @@ +""" +Spinners are from: +* cli-spinners: + MIT License + Copyright (c) Sindre Sorhus (sindresorhus.com) + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE + FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. +""" + +SPINNERS = { + "dots": { + "interval": 80, + "frames": "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏", + }, + "dots2": {"interval": 80, "frames": "⣾⣽⣻⢿⡿⣟⣯⣷"}, + "dots3": { + "interval": 80, + "frames": "⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓", + }, + "dots4": { + "interval": 80, + "frames": "⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆", + }, + "dots5": { + "interval": 80, + "frames": "⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋", + }, + "dots6": { + "interval": 80, + "frames": "⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁", + }, + "dots7": { + "interval": 80, + "frames": "⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈", + }, + "dots8": { + "interval": 80, + "frames": "⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈", + }, + "dots9": {"interval": 80, "frames": "⢹⢺⢼⣸⣇⡧⡗⡏"}, + "dots10": {"interval": 80, "frames": "⢄⢂⢁⡁⡈⡐⡠"}, + "dots11": {"interval": 100, "frames": "⠁⠂⠄⡀⢀⠠⠐⠈"}, + "dots12": { + "interval": 80, + "frames": [ + "⢀⠀", + "⡀⠀", + "⠄⠀", + "⢂⠀", + "⡂⠀", + "⠅⠀", + "⢃⠀", + "⡃⠀", + "⠍⠀", + "⢋⠀", + "⡋⠀", + "⠍⠁", + "⢋⠁", + "⡋⠁", + "⠍⠉", + "⠋⠉", + "⠋⠉", + "⠉⠙", + "⠉⠙", + "⠉⠩", + "⠈⢙", + "⠈⡙", + "⢈⠩", + "⡀⢙", + "⠄⡙", + "⢂⠩", + "⡂⢘", + "⠅⡘", + "⢃⠨", + "⡃⢐", + "⠍⡐", + "⢋⠠", + "⡋⢀", + "⠍⡁", + "⢋⠁", + "⡋⠁", + "⠍⠉", + "⠋⠉", + "⠋⠉", + "⠉⠙", + "⠉⠙", + "⠉⠩", + "⠈⢙", + "⠈⡙", + "⠈⠩", + "⠀⢙", + "⠀⡙", + "⠀⠩", + "⠀⢘", + "⠀⡘", + "⠀⠨", + "⠀⢐", + "⠀⡐", + "⠀⠠", + "⠀⢀", + "⠀⡀", + ], + }, + "dots8Bit": { + "interval": 80, + "frames": "⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙" + "⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻" + "⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕" + "⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷" + "⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿", + }, + "line": {"interval": 130, "frames": ["-", "\\", "|", "/"]}, + "line2": {"interval": 100, "frames": "⠂-–—–-"}, + "pipe": {"interval": 100, "frames": "┤┘┴└├┌┬┐"}, + "simpleDots": {"interval": 400, "frames": [". ", ".. ", "...", " "]}, + "simpleDotsScrolling": { + "interval": 200, + "frames": [". ", ".. ", "...", " ..", " .", " "], + }, + "star": {"interval": 70, "frames": "✶✸✹✺✹✷"}, + "star2": {"interval": 80, "frames": "+x*"}, + "flip": { + "interval": 70, + "frames": "___-``'´-___", + }, + "hamburger": {"interval": 100, "frames": "☱☲☴"}, + "growVertical": { + "interval": 120, + "frames": "▁▃▄▅▆▇▆▅▄▃", + }, + "growHorizontal": { + "interval": 120, + "frames": "▏▎▍▌▋▊▉▊▋▌▍▎", + }, + "balloon": {"interval": 140, "frames": " .oO@* "}, + "balloon2": {"interval": 120, "frames": ".oO°Oo."}, + "noise": {"interval": 100, "frames": "▓▒░"}, + "bounce": {"interval": 120, "frames": "⠁⠂⠄⠂"}, + "boxBounce": {"interval": 120, "frames": "▖▘▝▗"}, + "boxBounce2": {"interval": 100, "frames": "▌▀▐▄"}, + "triangle": {"interval": 50, "frames": "◢◣◤◥"}, + "arc": {"interval": 100, "frames": "◜◠◝◞◡◟"}, + "circle": {"interval": 120, "frames": "◡⊙◠"}, + "squareCorners": {"interval": 180, "frames": "◰◳◲◱"}, + "circleQuarters": {"interval": 120, "frames": "◴◷◶◵"}, + "circleHalves": {"interval": 50, "frames": "◐◓◑◒"}, + "squish": {"interval": 100, "frames": "╫╪"}, + "toggle": {"interval": 250, "frames": "⊶⊷"}, + "toggle2": {"interval": 80, "frames": "▫▪"}, + "toggle3": {"interval": 120, "frames": "□■"}, + "toggle4": {"interval": 100, "frames": "■□▪▫"}, + "toggle5": {"interval": 100, "frames": "▮▯"}, + "toggle6": {"interval": 300, "frames": "ဝ၀"}, + "toggle7": {"interval": 80, "frames": "⦾⦿"}, + "toggle8": {"interval": 100, "frames": "◍◌"}, + "toggle9": {"interval": 100, "frames": "◉◎"}, + "toggle10": {"interval": 100, "frames": "㊂㊀㊁"}, + "toggle11": {"interval": 50, "frames": "⧇⧆"}, + "toggle12": {"interval": 120, "frames": "☗☖"}, + "toggle13": {"interval": 80, "frames": "=*-"}, + "arrow": {"interval": 100, "frames": "←↖↑↗→↘↓↙"}, + "arrow2": { + "interval": 80, + "frames": ["⬆️ ", "↗️ ", "➡️ ", "↘️ ", "⬇️ ", "↙️ ", "⬅️ ", "↖️ "], + }, + "arrow3": { + "interval": 120, + "frames": ["▹▹▹▹▹", "▸▹▹▹▹", "▹▸▹▹▹", "▹▹▸▹▹", "▹▹▹▸▹", "▹▹▹▹▸"], + }, + "bouncingBar": { + "interval": 80, + "frames": [ + "[ ]", + "[= ]", + "[== ]", + "[=== ]", + "[ ===]", + "[ ==]", + "[ =]", + "[ ]", + "[ =]", + "[ ==]", + "[ ===]", + "[====]", + "[=== ]", + "[== ]", + "[= ]", + ], + }, + "bouncingBall": { + "interval": 80, + "frames": [ + "( ● )", + "( ● )", + "( ● )", + "( ● )", + "( ●)", + "( ● )", + "( ● )", + "( ● )", + "( ● )", + "(● )", + ], + }, + "smiley": {"interval": 200, "frames": ["😄 ", "😝 "]}, + "monkey": {"interval": 300, "frames": ["🙈 ", "🙈 ", "🙉 ", "🙊 "]}, + "hearts": {"interval": 100, "frames": ["💛 ", "💙 ", "💜 ", "💚 ", "❤️ "]}, + "clock": { + "interval": 100, + "frames": [ + "🕛 ", + "🕐 ", + "🕑 ", + "🕒 ", + "🕓 ", + "🕔 ", + "🕕 ", + "🕖 ", + "🕗 ", + "🕘 ", + "🕙 ", + "🕚 ", + ], + }, + "earth": {"interval": 180, "frames": ["🌍 ", "🌎 ", "🌏 "]}, + "material": { + "interval": 17, + "frames": [ + "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "███████▁▁▁▁▁▁▁▁▁▁▁▁▁", + "████████▁▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "██████████▁▁▁▁▁▁▁▁▁▁", + "███████████▁▁▁▁▁▁▁▁▁", + "█████████████▁▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁▁██████████████▁▁▁▁", + "▁▁▁██████████████▁▁▁", + "▁▁▁▁█████████████▁▁▁", + "▁▁▁▁██████████████▁▁", + "▁▁▁▁██████████████▁▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁▁██████████████", + "▁▁▁▁▁▁██████████████", + "▁▁▁▁▁▁▁█████████████", + "▁▁▁▁▁▁▁█████████████", + "▁▁▁▁▁▁▁▁████████████", + "▁▁▁▁▁▁▁▁████████████", + "▁▁▁▁▁▁▁▁▁███████████", + "▁▁▁▁▁▁▁▁▁███████████", + "▁▁▁▁▁▁▁▁▁▁██████████", + "▁▁▁▁▁▁▁▁▁▁██████████", + "▁▁▁▁▁▁▁▁▁▁▁▁████████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "████████▁▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "███████████▁▁▁▁▁▁▁▁▁", + "████████████▁▁▁▁▁▁▁▁", + "████████████▁▁▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁▁▁█████████████▁▁▁▁", + "▁▁▁▁▁████████████▁▁▁", + "▁▁▁▁▁████████████▁▁▁", + "▁▁▁▁▁▁███████████▁▁▁", + "▁▁▁▁▁▁▁▁█████████▁▁▁", + "▁▁▁▁▁▁▁▁█████████▁▁▁", + "▁▁▁▁▁▁▁▁▁█████████▁▁", + "▁▁▁▁▁▁▁▁▁█████████▁▁", + "▁▁▁▁▁▁▁▁▁▁█████████▁", + "▁▁▁▁▁▁▁▁▁▁▁████████▁", + "▁▁▁▁▁▁▁▁▁▁▁████████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + ], + }, + "moon": { + "interval": 80, + "frames": ["🌑 ", "🌒 ", "🌓 ", "🌔 ", "🌕 ", "🌖 ", "🌗 ", "🌘 "], + }, + "runner": {"interval": 140, "frames": ["🚶 ", "🏃 "]}, + "pong": { + "interval": 80, + "frames": [ + "▐⠂ ▌", + "▐⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂▌", + "▐ ⠠▌", + "▐ ⡀▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐⠠ ▌", + ], + }, + "shark": { + "interval": 120, + "frames": [ + "▐|\\____________▌", + "▐_|\\___________▌", + "▐__|\\__________▌", + "▐___|\\_________▌", + "▐____|\\________▌", + "▐_____|\\_______▌", + "▐______|\\______▌", + "▐_______|\\_____▌", + "▐________|\\____▌", + "▐_________|\\___▌", + "▐__________|\\__▌", + "▐___________|\\_▌", + "▐____________|\\▌", + "▐____________/|▌", + "▐___________/|_▌", + "▐__________/|__▌", + "▐_________/|___▌", + "▐________/|____▌", + "▐_______/|_____▌", + "▐______/|______▌", + "▐_____/|_______▌", + "▐____/|________▌", + "▐___/|_________▌", + "▐__/|__________▌", + "▐_/|___________▌", + "▐/|____________▌", + ], + }, + "dqpb": {"interval": 100, "frames": "dqpb"}, + "weather": { + "interval": 100, + "frames": [ + "☀️ ", + "☀️ ", + "☀️ ", + "🌤 ", + "⛅️ ", + "🌥 ", + "☁️ ", + "🌧 ", + "🌨 ", + "🌧 ", + "🌨 ", + "🌧 ", + "🌨 ", + "⛈ ", + "🌨 ", + "🌧 ", + "🌨 ", + "☁️ ", + "🌥 ", + "⛅️ ", + "🌤 ", + "☀️ ", + "☀️ ", + ], + }, + "christmas": {"interval": 400, "frames": "🌲🎄"}, + "grenade": { + "interval": 80, + "frames": [ + "، ", + "′ ", + " ´ ", + " ‾ ", + " ⸌", + " ⸊", + " |", + " ⁎", + " ⁕", + " ෴ ", + " ⁓", + " ", + " ", + " ", + ], + }, + "point": {"interval": 125, "frames": ["∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"]}, + "layer": {"interval": 150, "frames": "-=≡"}, + "betaWave": { + "interval": 80, + "frames": [ + "ρββββββ", + "βρβββββ", + "ββρββββ", + "βββρβββ", + "ββββρββ", + "βββββρβ", + "ββββββρ", + ], + }, + "aesthetic": { + "interval": 80, + "frames": [ + "▰▱▱▱▱▱▱", + "▰▰▱▱▱▱▱", + "▰▰▰▱▱▱▱", + "▰▰▰▰▱▱▱", + "▰▰▰▰▰▱▱", + "▰▰▰▰▰▰▱", + "▰▰▰▰▰▰▰", + "▰▱▱▱▱▱▱", + ], + }, +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_stack.py b/data/miniconda3/lib/python3.13/site-packages/rich/_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..194564e761ddae165b39ef6598877e2e3820af0a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_stack.py @@ -0,0 +1,16 @@ +from typing import List, TypeVar + +T = TypeVar("T") + + +class Stack(List[T]): + """A small shim over builtin list.""" + + @property + def top(self) -> T: + """Get top of stack.""" + return self[-1] + + def push(self, item: T) -> None: + """Push an item on to the stack (append in stack nomenclature).""" + self.append(item) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_timer.py b/data/miniconda3/lib/python3.13/site-packages/rich/_timer.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ca6be03c43054caaa3660998273ebf704345dd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_timer.py @@ -0,0 +1,19 @@ +""" +Timer context manager, only used in debug. + +""" + +from time import time + +import contextlib +from typing import Generator + + +@contextlib.contextmanager +def timer(subject: str = "time") -> Generator[None, None, None]: + """print the elapsed time. (only used in debugging)""" + start = time() + yield + elapsed = time() - start + elapsed_ms = elapsed * 1000 + print(f"{subject} elapsed {elapsed_ms:.1f}ms") diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_win32_console.py b/data/miniconda3/lib/python3.13/site-packages/rich/_win32_console.py new file mode 100644 index 0000000000000000000000000000000000000000..371ec09fac6954e5fc2473543db4225f760450cb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_win32_console.py @@ -0,0 +1,661 @@ +"""Light wrapper around the Win32 Console API - this module should only be imported on Windows + +The API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions +""" + +import ctypes +import sys +from typing import Any + +windll: Any = None +if sys.platform == "win32": + windll = ctypes.LibraryLoader(ctypes.WinDLL) +else: + raise ImportError(f"{__name__} can only be imported on Windows") + +import time +from ctypes import Structure, byref, wintypes +from typing import IO, NamedTuple, Type, cast + +from rich.color import ColorSystem +from rich.style import Style + +STDOUT = -11 +ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 + +COORD = wintypes._COORD + + +class LegacyWindowsError(Exception): + pass + + +class WindowsCoordinates(NamedTuple): + """Coordinates in the Windows Console API are (y, x), not (x, y). + This class is intended to prevent that confusion. + Rows and columns are indexed from 0. + This class can be used in place of wintypes._COORD in arguments and argtypes. + """ + + row: int + col: int + + @classmethod + def from_param(cls, value: "WindowsCoordinates") -> COORD: + """Converts a WindowsCoordinates into a wintypes _COORD structure. + This classmethod is internally called by ctypes to perform the conversion. + + Args: + value (WindowsCoordinates): The input coordinates to convert. + + Returns: + wintypes._COORD: The converted coordinates struct. + """ + return COORD(value.col, value.row) + + +class CONSOLE_SCREEN_BUFFER_INFO(Structure): + _fields_ = [ + ("dwSize", COORD), + ("dwCursorPosition", COORD), + ("wAttributes", wintypes.WORD), + ("srWindow", wintypes.SMALL_RECT), + ("dwMaximumWindowSize", COORD), + ] + + +class CONSOLE_CURSOR_INFO(ctypes.Structure): + _fields_ = [("dwSize", wintypes.DWORD), ("bVisible", wintypes.BOOL)] + + +_GetStdHandle = windll.kernel32.GetStdHandle +_GetStdHandle.argtypes = [ + wintypes.DWORD, +] +_GetStdHandle.restype = wintypes.HANDLE + + +def GetStdHandle(handle: int = STDOUT) -> wintypes.HANDLE: + """Retrieves a handle to the specified standard device (standard input, standard output, or standard error). + + Args: + handle (int): Integer identifier for the handle. Defaults to -11 (stdout). + + Returns: + wintypes.HANDLE: The handle + """ + return cast(wintypes.HANDLE, _GetStdHandle(handle)) + + +_GetConsoleMode = windll.kernel32.GetConsoleMode +_GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD] +_GetConsoleMode.restype = wintypes.BOOL + + +def GetConsoleMode(std_handle: wintypes.HANDLE) -> int: + """Retrieves the current input mode of a console's input buffer + or the current output mode of a console screen buffer. + + Args: + std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. + + Raises: + LegacyWindowsError: If any error occurs while calling the Windows console API. + + Returns: + int: Value representing the current console mode as documented at + https://docs.microsoft.com/en-us/windows/console/getconsolemode#parameters + """ + + console_mode = wintypes.DWORD() + success = bool(_GetConsoleMode(std_handle, console_mode)) + if not success: + raise LegacyWindowsError("Unable to get legacy Windows Console Mode") + return console_mode.value + + +_FillConsoleOutputCharacterW = windll.kernel32.FillConsoleOutputCharacterW +_FillConsoleOutputCharacterW.argtypes = [ + wintypes.HANDLE, + ctypes.c_char, + wintypes.DWORD, + cast(Type[COORD], WindowsCoordinates), + ctypes.POINTER(wintypes.DWORD), +] +_FillConsoleOutputCharacterW.restype = wintypes.BOOL + + +def FillConsoleOutputCharacter( + std_handle: wintypes.HANDLE, + char: str, + length: int, + start: WindowsCoordinates, +) -> int: + """Writes a character to the console screen buffer a specified number of times, beginning at the specified coordinates. + + Args: + std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. + char (str): The character to write. Must be a string of length 1. + length (int): The number of times to write the character. + start (WindowsCoordinates): The coordinates to start writing at. + + Returns: + int: The number of characters written. + """ + character = ctypes.c_char(char.encode()) + num_characters = wintypes.DWORD(length) + num_written = wintypes.DWORD(0) + _FillConsoleOutputCharacterW( + std_handle, + character, + num_characters, + start, + byref(num_written), + ) + return num_written.value + + +_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute +_FillConsoleOutputAttribute.argtypes = [ + wintypes.HANDLE, + wintypes.WORD, + wintypes.DWORD, + cast(Type[COORD], WindowsCoordinates), + ctypes.POINTER(wintypes.DWORD), +] +_FillConsoleOutputAttribute.restype = wintypes.BOOL + + +def FillConsoleOutputAttribute( + std_handle: wintypes.HANDLE, + attributes: int, + length: int, + start: WindowsCoordinates, +) -> int: + """Sets the character attributes for a specified number of character cells, + beginning at the specified coordinates in a screen buffer. + + Args: + std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. + attributes (int): Integer value representing the foreground and background colours of the cells. + length (int): The number of cells to set the output attribute of. + start (WindowsCoordinates): The coordinates of the first cell whose attributes are to be set. + + Returns: + int: The number of cells whose attributes were actually set. + """ + num_cells = wintypes.DWORD(length) + style_attrs = wintypes.WORD(attributes) + num_written = wintypes.DWORD(0) + _FillConsoleOutputAttribute( + std_handle, style_attrs, num_cells, start, byref(num_written) + ) + return num_written.value + + +_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute +_SetConsoleTextAttribute.argtypes = [ + wintypes.HANDLE, + wintypes.WORD, +] +_SetConsoleTextAttribute.restype = wintypes.BOOL + + +def SetConsoleTextAttribute( + std_handle: wintypes.HANDLE, attributes: wintypes.WORD +) -> bool: + """Set the colour attributes for all text written after this function is called. + + Args: + std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. + attributes (int): Integer value representing the foreground and background colours. + + + Returns: + bool: True if the attribute was set successfully, otherwise False. + """ + return bool(_SetConsoleTextAttribute(std_handle, attributes)) + + +_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo +_GetConsoleScreenBufferInfo.argtypes = [ + wintypes.HANDLE, + ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO), +] +_GetConsoleScreenBufferInfo.restype = wintypes.BOOL + + +def GetConsoleScreenBufferInfo( + std_handle: wintypes.HANDLE, +) -> CONSOLE_SCREEN_BUFFER_INFO: + """Retrieves information about the specified console screen buffer. + + Args: + std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. + + Returns: + CONSOLE_SCREEN_BUFFER_INFO: A CONSOLE_SCREEN_BUFFER_INFO ctype struct contain information about + screen size, cursor position, colour attributes, and more.""" + console_screen_buffer_info = CONSOLE_SCREEN_BUFFER_INFO() + _GetConsoleScreenBufferInfo(std_handle, byref(console_screen_buffer_info)) + return console_screen_buffer_info + + +_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition +_SetConsoleCursorPosition.argtypes = [ + wintypes.HANDLE, + cast(Type[COORD], WindowsCoordinates), +] +_SetConsoleCursorPosition.restype = wintypes.BOOL + + +def SetConsoleCursorPosition( + std_handle: wintypes.HANDLE, coords: WindowsCoordinates +) -> bool: + """Set the position of the cursor in the console screen + + Args: + std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. + coords (WindowsCoordinates): The coordinates to move the cursor to. + + Returns: + bool: True if the function succeeds, otherwise False. + """ + return bool(_SetConsoleCursorPosition(std_handle, coords)) + + +_GetConsoleCursorInfo = windll.kernel32.GetConsoleCursorInfo +_GetConsoleCursorInfo.argtypes = [ + wintypes.HANDLE, + ctypes.POINTER(CONSOLE_CURSOR_INFO), +] +_GetConsoleCursorInfo.restype = wintypes.BOOL + + +def GetConsoleCursorInfo( + std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO +) -> bool: + """Get the cursor info - used to get cursor visibility and width + + Args: + std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. + cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct that receives information + about the console's cursor. + + Returns: + bool: True if the function succeeds, otherwise False. + """ + return bool(_GetConsoleCursorInfo(std_handle, byref(cursor_info))) + + +_SetConsoleCursorInfo = windll.kernel32.SetConsoleCursorInfo +_SetConsoleCursorInfo.argtypes = [ + wintypes.HANDLE, + ctypes.POINTER(CONSOLE_CURSOR_INFO), +] +_SetConsoleCursorInfo.restype = wintypes.BOOL + + +def SetConsoleCursorInfo( + std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO +) -> bool: + """Set the cursor info - used for adjusting cursor visibility and width + + Args: + std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer. + cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct containing the new cursor info. + + Returns: + bool: True if the function succeeds, otherwise False. + """ + return bool(_SetConsoleCursorInfo(std_handle, byref(cursor_info))) + + +_SetConsoleTitle = windll.kernel32.SetConsoleTitleW +_SetConsoleTitle.argtypes = [wintypes.LPCWSTR] +_SetConsoleTitle.restype = wintypes.BOOL + + +def SetConsoleTitle(title: str) -> bool: + """Sets the title of the current console window + + Args: + title (str): The new title of the console window. + + Returns: + bool: True if the function succeeds, otherwise False. + """ + return bool(_SetConsoleTitle(title)) + + +class LegacyWindowsTerm: + """This class allows interaction with the legacy Windows Console API. It should only be used in the context + of environments where virtual terminal processing is not available. However, if it is used in a Windows environment, + the entire API should work. + + Args: + file (IO[str]): The file which the Windows Console API HANDLE is retrieved from, defaults to sys.stdout. + """ + + BRIGHT_BIT = 8 + + # Indices are ANSI color numbers, values are the corresponding Windows Console API color numbers + ANSI_TO_WINDOWS = [ + 0, # black The Windows colours are defined in wincon.h as follows: + 4, # red define FOREGROUND_BLUE 0x0001 -- 0000 0001 + 2, # green define FOREGROUND_GREEN 0x0002 -- 0000 0010 + 6, # yellow define FOREGROUND_RED 0x0004 -- 0000 0100 + 1, # blue define FOREGROUND_INTENSITY 0x0008 -- 0000 1000 + 5, # magenta define BACKGROUND_BLUE 0x0010 -- 0001 0000 + 3, # cyan define BACKGROUND_GREEN 0x0020 -- 0010 0000 + 7, # white define BACKGROUND_RED 0x0040 -- 0100 0000 + 8, # bright black (grey) define BACKGROUND_INTENSITY 0x0080 -- 1000 0000 + 12, # bright red + 10, # bright green + 14, # bright yellow + 9, # bright blue + 13, # bright magenta + 11, # bright cyan + 15, # bright white + ] + + def __init__(self, file: "IO[str]") -> None: + handle = GetStdHandle(STDOUT) + self._handle = handle + default_text = GetConsoleScreenBufferInfo(handle).wAttributes + self._default_text = default_text + + self._default_fore = default_text & 7 + self._default_back = (default_text >> 4) & 7 + self._default_attrs = self._default_fore | (self._default_back << 4) + + self._file = file + self.write = file.write + self.flush = file.flush + + @property + def cursor_position(self) -> WindowsCoordinates: + """Returns the current position of the cursor (0-based) + + Returns: + WindowsCoordinates: The current cursor position. + """ + coord: COORD = GetConsoleScreenBufferInfo(self._handle).dwCursorPosition + return WindowsCoordinates(row=coord.Y, col=coord.X) + + @property + def screen_size(self) -> WindowsCoordinates: + """Returns the current size of the console screen buffer, in character columns and rows + + Returns: + WindowsCoordinates: The width and height of the screen as WindowsCoordinates. + """ + screen_size: COORD = GetConsoleScreenBufferInfo(self._handle).dwSize + return WindowsCoordinates(row=screen_size.Y, col=screen_size.X) + + def write_text(self, text: str) -> None: + """Write text directly to the terminal without any modification of styles + + Args: + text (str): The text to write to the console + """ + self.write(text) + self.flush() + + def write_styled(self, text: str, style: Style) -> None: + """Write styled text to the terminal. + + Args: + text (str): The text to write + style (Style): The style of the text + """ + color = style.color + bgcolor = style.bgcolor + if style.reverse: + color, bgcolor = bgcolor, color + + if color: + fore = color.downgrade(ColorSystem.WINDOWS).number + fore = fore if fore is not None else 7 # Default to ANSI 7: White + if style.bold: + fore = fore | self.BRIGHT_BIT + if style.dim: + fore = fore & ~self.BRIGHT_BIT + fore = self.ANSI_TO_WINDOWS[fore] + else: + fore = self._default_fore + + if bgcolor: + back = bgcolor.downgrade(ColorSystem.WINDOWS).number + back = back if back is not None else 0 # Default to ANSI 0: Black + back = self.ANSI_TO_WINDOWS[back] + else: + back = self._default_back + + assert fore is not None + assert back is not None + + SetConsoleTextAttribute( + self._handle, attributes=ctypes.c_ushort(fore | (back << 4)) + ) + self.write_text(text) + SetConsoleTextAttribute(self._handle, attributes=self._default_text) + + def move_cursor_to(self, new_position: WindowsCoordinates) -> None: + """Set the position of the cursor + + Args: + new_position (WindowsCoordinates): The WindowsCoordinates representing the new position of the cursor. + """ + if new_position.col < 0 or new_position.row < 0: + return + SetConsoleCursorPosition(self._handle, coords=new_position) + + def erase_line(self) -> None: + """Erase all content on the line the cursor is currently located at""" + screen_size = self.screen_size + cursor_position = self.cursor_position + cells_to_erase = screen_size.col + start_coordinates = WindowsCoordinates(row=cursor_position.row, col=0) + FillConsoleOutputCharacter( + self._handle, " ", length=cells_to_erase, start=start_coordinates + ) + FillConsoleOutputAttribute( + self._handle, + self._default_attrs, + length=cells_to_erase, + start=start_coordinates, + ) + + def erase_end_of_line(self) -> None: + """Erase all content from the cursor position to the end of that line""" + cursor_position = self.cursor_position + cells_to_erase = self.screen_size.col - cursor_position.col + FillConsoleOutputCharacter( + self._handle, " ", length=cells_to_erase, start=cursor_position + ) + FillConsoleOutputAttribute( + self._handle, + self._default_attrs, + length=cells_to_erase, + start=cursor_position, + ) + + def erase_start_of_line(self) -> None: + """Erase all content from the cursor position to the start of that line""" + row, col = self.cursor_position + start = WindowsCoordinates(row, 0) + FillConsoleOutputCharacter(self._handle, " ", length=col, start=start) + FillConsoleOutputAttribute( + self._handle, self._default_attrs, length=col, start=start + ) + + def move_cursor_up(self) -> None: + """Move the cursor up a single cell""" + cursor_position = self.cursor_position + SetConsoleCursorPosition( + self._handle, + coords=WindowsCoordinates( + row=cursor_position.row - 1, col=cursor_position.col + ), + ) + + def move_cursor_down(self) -> None: + """Move the cursor down a single cell""" + cursor_position = self.cursor_position + SetConsoleCursorPosition( + self._handle, + coords=WindowsCoordinates( + row=cursor_position.row + 1, + col=cursor_position.col, + ), + ) + + def move_cursor_forward(self) -> None: + """Move the cursor forward a single cell. Wrap to the next line if required.""" + row, col = self.cursor_position + if col == self.screen_size.col - 1: + row += 1 + col = 0 + else: + col += 1 + SetConsoleCursorPosition( + self._handle, coords=WindowsCoordinates(row=row, col=col) + ) + + def move_cursor_to_column(self, column: int) -> None: + """Move cursor to the column specified by the zero-based column index, staying on the same row + + Args: + column (int): The zero-based column index to move the cursor to. + """ + row, _ = self.cursor_position + SetConsoleCursorPosition(self._handle, coords=WindowsCoordinates(row, column)) + + def move_cursor_backward(self) -> None: + """Move the cursor backward a single cell. Wrap to the previous line if required.""" + row, col = self.cursor_position + if col == 0: + row -= 1 + col = self.screen_size.col - 1 + else: + col -= 1 + SetConsoleCursorPosition( + self._handle, coords=WindowsCoordinates(row=row, col=col) + ) + + def hide_cursor(self) -> None: + """Hide the cursor""" + current_cursor_size = self._get_cursor_size() + invisible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=0) + SetConsoleCursorInfo(self._handle, cursor_info=invisible_cursor) + + def show_cursor(self) -> None: + """Show the cursor""" + current_cursor_size = self._get_cursor_size() + visible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=1) + SetConsoleCursorInfo(self._handle, cursor_info=visible_cursor) + + def set_title(self, title: str) -> None: + """Set the title of the terminal window + + Args: + title (str): The new title of the console window + """ + assert len(title) < 255, "Console title must be less than 255 characters" + SetConsoleTitle(title) + + def _get_cursor_size(self) -> int: + """Get the percentage of the character cell that is filled by the cursor""" + cursor_info = CONSOLE_CURSOR_INFO() + GetConsoleCursorInfo(self._handle, cursor_info=cursor_info) + return int(cursor_info.dwSize) + + +if __name__ == "__main__": + handle = GetStdHandle() + + from rich.console import Console + + console = Console() + + term = LegacyWindowsTerm(sys.stdout) + term.set_title("Win32 Console Examples") + + style = Style(color="black", bgcolor="red") + + heading = Style.parse("black on green") + + # Check colour output + console.rule("Checking colour output") + console.print("[on red]on red!") + console.print("[blue]blue!") + console.print("[yellow]yellow!") + console.print("[bold yellow]bold yellow!") + console.print("[bright_yellow]bright_yellow!") + console.print("[dim bright_yellow]dim bright_yellow!") + console.print("[italic cyan]italic cyan!") + console.print("[bold white on blue]bold white on blue!") + console.print("[reverse bold white on blue]reverse bold white on blue!") + console.print("[bold black on cyan]bold black on cyan!") + console.print("[black on green]black on green!") + console.print("[blue on green]blue on green!") + console.print("[white on black]white on black!") + console.print("[black on white]black on white!") + console.print("[#1BB152 on #DA812D]#1BB152 on #DA812D!") + + # Check cursor movement + console.rule("Checking cursor movement") + console.print() + term.move_cursor_backward() + term.move_cursor_backward() + term.write_text("went back and wrapped to prev line") + time.sleep(1) + term.move_cursor_up() + term.write_text("we go up") + time.sleep(1) + term.move_cursor_down() + term.write_text("and down") + time.sleep(1) + term.move_cursor_up() + term.move_cursor_backward() + term.move_cursor_backward() + term.write_text("we went up and back 2") + time.sleep(1) + term.move_cursor_down() + term.move_cursor_backward() + term.move_cursor_backward() + term.write_text("we went down and back 2") + time.sleep(1) + + # Check erasing of lines + term.hide_cursor() + console.print() + console.rule("Checking line erasing") + console.print("\n...Deleting to the start of the line...") + term.write_text("The red arrow shows the cursor location, and direction of erase") + time.sleep(1) + term.move_cursor_to_column(16) + term.write_styled("<", Style.parse("black on red")) + term.move_cursor_backward() + time.sleep(1) + term.erase_start_of_line() + time.sleep(1) + + console.print("\n\n...And to the end of the line...") + term.write_text("The red arrow shows the cursor location, and direction of erase") + time.sleep(1) + + term.move_cursor_to_column(16) + term.write_styled(">", Style.parse("black on red")) + time.sleep(1) + term.erase_end_of_line() + time.sleep(1) + + console.print("\n\n...Now the whole line will be erased...") + term.write_styled("I'm going to disappear!", style=Style.parse("black on cyan")) + time.sleep(1) + term.erase_line() + + term.show_cursor() + print("\n") diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_windows.py b/data/miniconda3/lib/python3.13/site-packages/rich/_windows.py new file mode 100644 index 0000000000000000000000000000000000000000..e17c5c0fdcaeec4b2b0c007733970ae4ffa9c641 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_windows.py @@ -0,0 +1,71 @@ +import sys +from dataclasses import dataclass + + +@dataclass +class WindowsConsoleFeatures: + """Windows features available.""" + + vt: bool = False + """The console supports VT codes.""" + truecolor: bool = False + """The console supports truecolor.""" + + +try: + import ctypes + from ctypes import LibraryLoader + + if sys.platform == "win32": + windll = LibraryLoader(ctypes.WinDLL) + else: + windll = None + raise ImportError("Not windows") + + from rich._win32_console import ( + ENABLE_VIRTUAL_TERMINAL_PROCESSING, + GetConsoleMode, + GetStdHandle, + LegacyWindowsError, + ) + +except (AttributeError, ImportError, ValueError): + # Fallback if we can't load the Windows DLL + def get_windows_console_features() -> WindowsConsoleFeatures: + features = WindowsConsoleFeatures() + return features + +else: + + def get_windows_console_features() -> WindowsConsoleFeatures: + """Get windows console features. + + Returns: + WindowsConsoleFeatures: An instance of WindowsConsoleFeatures. + """ + handle = GetStdHandle() + try: + console_mode = GetConsoleMode(handle) + success = True + except LegacyWindowsError: + console_mode = 0 + success = False + vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) + truecolor = False + if vt: + win_version = sys.getwindowsversion() + truecolor = win_version.major > 10 or ( + win_version.major == 10 and win_version.build >= 15063 + ) + features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor) + return features + + +if __name__ == "__main__": + import platform + + features = get_windows_console_features() + from rich import print + + print(f'platform="{platform.system()}"') + print(repr(features)) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_windows_renderer.py b/data/miniconda3/lib/python3.13/site-packages/rich/_windows_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc2ba852a92a45ef510d27ca6ce5e5348bec8a1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_windows_renderer.py @@ -0,0 +1,56 @@ +from typing import Iterable, Sequence, Tuple, cast + +from rich._win32_console import LegacyWindowsTerm, WindowsCoordinates +from rich.segment import ControlCode, ControlType, Segment + + +def legacy_windows_render(buffer: Iterable[Segment], term: LegacyWindowsTerm) -> None: + """Makes appropriate Windows Console API calls based on the segments in the buffer. + + Args: + buffer (Iterable[Segment]): Iterable of Segments to convert to Win32 API calls. + term (LegacyWindowsTerm): Used to call the Windows Console API. + """ + for text, style, control in buffer: + if not control: + if style: + term.write_styled(text, style) + else: + term.write_text(text) + else: + control_codes: Sequence[ControlCode] = control + for control_code in control_codes: + control_type = control_code[0] + if control_type == ControlType.CURSOR_MOVE_TO: + _, x, y = cast(Tuple[ControlType, int, int], control_code) + term.move_cursor_to(WindowsCoordinates(row=y - 1, col=x - 1)) + elif control_type == ControlType.CARRIAGE_RETURN: + term.write_text("\r") + elif control_type == ControlType.HOME: + term.move_cursor_to(WindowsCoordinates(0, 0)) + elif control_type == ControlType.CURSOR_UP: + term.move_cursor_up() + elif control_type == ControlType.CURSOR_DOWN: + term.move_cursor_down() + elif control_type == ControlType.CURSOR_FORWARD: + term.move_cursor_forward() + elif control_type == ControlType.CURSOR_BACKWARD: + term.move_cursor_backward() + elif control_type == ControlType.CURSOR_MOVE_TO_COLUMN: + _, column = cast(Tuple[ControlType, int], control_code) + term.move_cursor_to_column(column - 1) + elif control_type == ControlType.HIDE_CURSOR: + term.hide_cursor() + elif control_type == ControlType.SHOW_CURSOR: + term.show_cursor() + elif control_type == ControlType.ERASE_IN_LINE: + _, mode = cast(Tuple[ControlType, int], control_code) + if mode == 0: + term.erase_end_of_line() + elif mode == 1: + term.erase_start_of_line() + elif mode == 2: + term.erase_line() + elif control_type == ControlType.SET_WINDOW_TITLE: + _, title = cast(Tuple[ControlType, str], control_code) + term.set_title(title) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/_wrap.py b/data/miniconda3/lib/python3.13/site-packages/rich/_wrap.py new file mode 100644 index 0000000000000000000000000000000000000000..2e94ff6f43adfb6a6900a3a2147781e91220b189 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/_wrap.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +import re +from typing import Iterable + +from ._loop import loop_last +from .cells import cell_len, chop_cells + +re_word = re.compile(r"\s*\S+\s*") + + +def words(text: str) -> Iterable[tuple[int, int, str]]: + """Yields each word from the text as a tuple + containing (start_index, end_index, word). A "word" in this context may + include the actual word and any whitespace to the right. + """ + position = 0 + word_match = re_word.match(text, position) + while word_match is not None: + start, end = word_match.span() + word = word_match.group(0) + yield start, end, word + word_match = re_word.match(text, end) + + +def divide_line(text: str, width: int, fold: bool = True) -> list[int]: + """Given a string of text, and a width (measured in cells), return a list + of cell offsets which the string should be split at in order for it to fit + within the given width. + + Args: + text: The text to examine. + width: The available cell width. + fold: If True, words longer than `width` will be folded onto a new line. + + Returns: + A list of indices to break the line at. + """ + break_positions: list[int] = [] # offsets to insert the breaks at + append = break_positions.append + cell_offset = 0 + _cell_len = cell_len + + for start, _end, word in words(text): + word_length = _cell_len(word.rstrip()) + remaining_space = width - cell_offset + word_fits_remaining_space = remaining_space >= word_length + + if word_fits_remaining_space: + # Simplest case - the word fits within the remaining width for this line. + cell_offset += _cell_len(word) + else: + # Not enough space remaining for this word on the current line. + if word_length > width: + # The word doesn't fit on any line, so we can't simply + # place it on the next line... + if fold: + # Fold the word across multiple lines. + folded_word = chop_cells(word, width=width) + for last, line in loop_last(folded_word): + if start: + append(start) + if last: + cell_offset = _cell_len(line) + else: + start += len(line) + else: + # Folding isn't allowed, so crop the word. + if start: + append(start) + cell_offset = _cell_len(word) + elif cell_offset and start: + # The word doesn't fit within the remaining space on the current + # line, but it *can* fit on to the next (empty) line. + append(start) + cell_offset = _cell_len(word) + + return break_positions + + +if __name__ == "__main__": # pragma: no cover + from .console import Console + + console = Console(width=10) + console.print("12345 abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ 12345") + print(chop_cells("abcdefghijklmnopqrstuvwxyz", 10)) + + console = Console(width=20) + console.rule() + console.print("TextualはPythonの高速アプリケーション開発フレームワークです") + + console.rule() + console.print("アプリケーションは1670万色を使用でき") diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/abc.py b/data/miniconda3/lib/python3.13/site-packages/rich/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..42db7c00202962561f5dfdb295b2cab54d4868c7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/abc.py @@ -0,0 +1,33 @@ +from abc import ABC + + +class RichRenderable(ABC): + """An abstract base class for Rich renderables. + + Note that there is no need to extend this class, the intended use is to check if an + object supports the Rich renderable protocol. For example:: + + if isinstance(my_object, RichRenderable): + console.print(my_object) + + """ + + @classmethod + def __subclasshook__(cls, other: type) -> bool: + """Check if this class supports the rich render protocol.""" + return hasattr(other, "__rich_console__") or hasattr(other, "__rich__") + + +if __name__ == "__main__": # pragma: no cover + from rich.text import Text + + t = Text() + print(isinstance(Text, RichRenderable)) + print(isinstance(t, RichRenderable)) + + class Foo: + pass + + f = Foo() + print(isinstance(f, RichRenderable)) + print(isinstance("", RichRenderable)) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/align.py b/data/miniconda3/lib/python3.13/site-packages/rich/align.py new file mode 100644 index 0000000000000000000000000000000000000000..cb5f31d63926d76a2934a8e4019b501f2260e132 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/align.py @@ -0,0 +1,306 @@ +from itertools import chain +from typing import TYPE_CHECKING, Iterable, Optional, Literal + +from .constrain import Constrain +from .jupyter import JupyterMixin +from .measure import Measurement +from .segment import Segment +from .style import StyleType + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderableType, RenderResult + +AlignMethod = Literal["left", "center", "right"] +VerticalAlignMethod = Literal["top", "middle", "bottom"] + + +class Align(JupyterMixin): + """Align a renderable by adding spaces if necessary. + + Args: + renderable (RenderableType): A console renderable. + align (AlignMethod): One of "left", "center", or "right"" + style (StyleType, optional): An optional style to apply to the background. + vertical (Optional[VerticalAlignMethod], optional): Optional vertical align, one of "top", "middle", or "bottom". Defaults to None. + pad (bool, optional): Pad the right with spaces. Defaults to True. + width (int, optional): Restrict contents to given width, or None to use default width. Defaults to None. + height (int, optional): Set height of align renderable, or None to fit to contents. Defaults to None. + + Raises: + ValueError: if ``align`` is not one of the expected values. + """ + + def __init__( + self, + renderable: "RenderableType", + align: AlignMethod = "left", + style: Optional[StyleType] = None, + *, + vertical: Optional[VerticalAlignMethod] = None, + pad: bool = True, + width: Optional[int] = None, + height: Optional[int] = None, + ) -> None: + if align not in ("left", "center", "right"): + raise ValueError( + f'invalid value for align, expected "left", "center", or "right" (not {align!r})' + ) + if vertical is not None and vertical not in ("top", "middle", "bottom"): + raise ValueError( + f'invalid value for vertical, expected "top", "middle", or "bottom" (not {vertical!r})' + ) + self.renderable = renderable + self.align = align + self.style = style + self.vertical = vertical + self.pad = pad + self.width = width + self.height = height + + def __repr__(self) -> str: + return f"Align({self.renderable!r}, {self.align!r})" + + @classmethod + def left( + cls, + renderable: "RenderableType", + style: Optional[StyleType] = None, + *, + vertical: Optional[VerticalAlignMethod] = None, + pad: bool = True, + width: Optional[int] = None, + height: Optional[int] = None, + ) -> "Align": + """Align a renderable to the left.""" + return cls( + renderable, + "left", + style=style, + vertical=vertical, + pad=pad, + width=width, + height=height, + ) + + @classmethod + def center( + cls, + renderable: "RenderableType", + style: Optional[StyleType] = None, + *, + vertical: Optional[VerticalAlignMethod] = None, + pad: bool = True, + width: Optional[int] = None, + height: Optional[int] = None, + ) -> "Align": + """Align a renderable to the center.""" + return cls( + renderable, + "center", + style=style, + vertical=vertical, + pad=pad, + width=width, + height=height, + ) + + @classmethod + def right( + cls, + renderable: "RenderableType", + style: Optional[StyleType] = None, + *, + vertical: Optional[VerticalAlignMethod] = None, + pad: bool = True, + width: Optional[int] = None, + height: Optional[int] = None, + ) -> "Align": + """Align a renderable to the right.""" + return cls( + renderable, + "right", + style=style, + vertical=vertical, + pad=pad, + width=width, + height=height, + ) + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + align = self.align + width = console.measure(self.renderable, options=options).maximum + rendered = console.render( + Constrain( + self.renderable, width if self.width is None else min(width, self.width) + ), + options.update(height=None), + ) + lines = list(Segment.split_lines(rendered)) + width, height = Segment.get_shape(lines) + lines = Segment.set_shape(lines, width, height) + new_line = Segment.line() + excess_space = options.max_width - width + style = console.get_style(self.style) if self.style is not None else None + + def generate_segments() -> Iterable[Segment]: + if excess_space <= 0: + # Exact fit + for line in lines: + yield from line + yield new_line + + elif align == "left": + # Pad on the right + pad = Segment(" " * excess_space, style) if self.pad else None + for line in lines: + yield from line + if pad: + yield pad + yield new_line + + elif align == "center": + # Pad left and right + left = excess_space // 2 + pad = Segment(" " * left, style) + pad_right = ( + Segment(" " * (excess_space - left), style) if self.pad else None + ) + for line in lines: + if left: + yield pad + yield from line + if pad_right: + yield pad_right + yield new_line + + elif align == "right": + # Padding on left + pad = Segment(" " * excess_space, style) + for line in lines: + yield pad + yield from line + yield new_line + + blank_line = ( + Segment(f"{' ' * (self.width or options.max_width)}\n", style) + if self.pad + else Segment("\n") + ) + + def blank_lines(count: int) -> Iterable[Segment]: + if count > 0: + for _ in range(count): + yield blank_line + + vertical_height = self.height or options.height + iter_segments: Iterable[Segment] + if self.vertical and vertical_height is not None: + if self.vertical == "top": + bottom_space = vertical_height - height + iter_segments = chain(generate_segments(), blank_lines(bottom_space)) + elif self.vertical == "middle": + top_space = (vertical_height - height) // 2 + bottom_space = vertical_height - top_space - height + iter_segments = chain( + blank_lines(top_space), + generate_segments(), + blank_lines(bottom_space), + ) + else: # self.vertical == "bottom": + top_space = vertical_height - height + iter_segments = chain(blank_lines(top_space), generate_segments()) + else: + iter_segments = generate_segments() + if self.style: + style = console.get_style(self.style) + iter_segments = Segment.apply_style(iter_segments, style) + yield from iter_segments + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> Measurement: + measurement = Measurement.get(console, options, self.renderable) + return measurement + + +class VerticalCenter(JupyterMixin): + """Vertically aligns a renderable. + + Warn: + This class is deprecated and may be removed in a future version. Use Align class with + `vertical="middle"`. + + Args: + renderable (RenderableType): A renderable object. + style (StyleType, optional): An optional style to apply to the background. Defaults to None. + """ + + def __init__( + self, + renderable: "RenderableType", + style: Optional[StyleType] = None, + ) -> None: + self.renderable = renderable + self.style = style + + def __repr__(self) -> str: + return f"VerticalCenter({self.renderable!r})" + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + style = console.get_style(self.style) if self.style is not None else None + lines = console.render_lines( + self.renderable, options.update(height=None), pad=False + ) + width, _height = Segment.get_shape(lines) + new_line = Segment.line() + height = options.height or options.size.height + top_space = (height - len(lines)) // 2 + bottom_space = height - top_space - len(lines) + blank_line = Segment(f"{' ' * width}", style) + + def blank_lines(count: int) -> Iterable[Segment]: + for _ in range(count): + yield blank_line + yield new_line + + if top_space > 0: + yield from blank_lines(top_space) + for line in lines: + yield from line + yield new_line + if bottom_space > 0: + yield from blank_lines(bottom_space) + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> Measurement: + measurement = Measurement.get(console, options, self.renderable) + return measurement + + +if __name__ == "__main__": # pragma: no cover + from rich.console import Console, Group + from rich.highlighter import ReprHighlighter + from rich.panel import Panel + + highlighter = ReprHighlighter() + console = Console() + + panel = Panel( + Group( + Align.left(highlighter("align='left'")), + Align.center(highlighter("align='center'")), + Align.right(highlighter("align='right'")), + ), + width=60, + style="on dark_blue", + title="Align", + ) + + console.print( + Align.center(panel, vertical="middle", style="on red", height=console.height) + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/ansi.py b/data/miniconda3/lib/python3.13/site-packages/rich/ansi.py new file mode 100644 index 0000000000000000000000000000000000000000..7de86ce5043feeee4b6c28302cc1e72c2ad4cfe1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/ansi.py @@ -0,0 +1,241 @@ +import re +import sys +from contextlib import suppress +from typing import Iterable, NamedTuple, Optional + +from .color import Color +from .style import Style +from .text import Text + +re_ansi = re.compile( + r""" +(?:\x1b[0-?])| +(?:\x1b\](.*?)\x1b\\)| +(?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~])) +""", + re.VERBOSE, +) + + +class _AnsiToken(NamedTuple): + """Result of ansi tokenized string.""" + + plain: str = "" + sgr: Optional[str] = "" + osc: Optional[str] = "" + + +def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]: + """Tokenize a string in to plain text and ANSI codes. + + Args: + ansi_text (str): A String containing ANSI codes. + + Yields: + AnsiToken: A named tuple of (plain, sgr, osc) + """ + + position = 0 + sgr: Optional[str] + osc: Optional[str] + for match in re_ansi.finditer(ansi_text): + start, end = match.span(0) + osc, sgr = match.groups() + if start > position: + yield _AnsiToken(ansi_text[position:start]) + if sgr: + if sgr == "(": + position = end + 1 + continue + if sgr.endswith("m"): + yield _AnsiToken("", sgr[1:-1], osc) + else: + yield _AnsiToken("", sgr, osc) + position = end + if position < len(ansi_text): + yield _AnsiToken(ansi_text[position:]) + + +SGR_STYLE_MAP = { + 1: "bold", + 2: "dim", + 3: "italic", + 4: "underline", + 5: "blink", + 6: "blink2", + 7: "reverse", + 8: "conceal", + 9: "strike", + 21: "underline2", + 22: "not dim not bold", + 23: "not italic", + 24: "not underline", + 25: "not blink", + 26: "not blink2", + 27: "not reverse", + 28: "not conceal", + 29: "not strike", + 30: "color(0)", + 31: "color(1)", + 32: "color(2)", + 33: "color(3)", + 34: "color(4)", + 35: "color(5)", + 36: "color(6)", + 37: "color(7)", + 39: "default", + 40: "on color(0)", + 41: "on color(1)", + 42: "on color(2)", + 43: "on color(3)", + 44: "on color(4)", + 45: "on color(5)", + 46: "on color(6)", + 47: "on color(7)", + 49: "on default", + 51: "frame", + 52: "encircle", + 53: "overline", + 54: "not frame not encircle", + 55: "not overline", + 90: "color(8)", + 91: "color(9)", + 92: "color(10)", + 93: "color(11)", + 94: "color(12)", + 95: "color(13)", + 96: "color(14)", + 97: "color(15)", + 100: "on color(8)", + 101: "on color(9)", + 102: "on color(10)", + 103: "on color(11)", + 104: "on color(12)", + 105: "on color(13)", + 106: "on color(14)", + 107: "on color(15)", +} + + +class AnsiDecoder: + """Translate ANSI code in to styled Text.""" + + def __init__(self) -> None: + self.style = Style.null() + + def decode(self, terminal_text: str) -> Iterable[Text]: + """Decode ANSI codes in an iterable of lines. + + Args: + lines (Iterable[str]): An iterable of lines of terminal output. + + Yields: + Text: Marked up Text. + """ + for line in terminal_text.splitlines(): + yield self.decode_line(line) + + def decode_line(self, line: str) -> Text: + """Decode a line containing ansi codes. + + Args: + line (str): A line of terminal output. + + Returns: + Text: A Text instance marked up according to ansi codes. + """ + from_ansi = Color.from_ansi + from_rgb = Color.from_rgb + _Style = Style + text = Text() + append = text.append + line = line.rsplit("\r", 1)[-1] + for plain_text, sgr, osc in _ansi_tokenize(line): + if plain_text: + append(plain_text, self.style or None) + elif osc is not None: + if osc.startswith("8;"): + _params, semicolon, link = osc[2:].partition(";") + if semicolon: + self.style = self.style.update_link(link or None) + elif sgr is not None: + # Translate in to semi-colon separated codes + # Ignore invalid codes, because we want to be lenient + codes = [ + min(255, int(_code) if _code else 0) + for _code in sgr.split(";") + if _code.isdigit() or _code == "" + ] + iter_codes = iter(codes) + for code in iter_codes: + if code == 0: + # reset + self.style = _Style.null() + elif code in SGR_STYLE_MAP: + # styles + self.style += _Style.parse(SGR_STYLE_MAP[code]) + elif code == 38: + #  Foreground + with suppress(StopIteration): + color_type = next(iter_codes) + if color_type == 5: + self.style += _Style.from_color( + from_ansi(next(iter_codes)) + ) + elif color_type == 2: + self.style += _Style.from_color( + from_rgb( + next(iter_codes), + next(iter_codes), + next(iter_codes), + ) + ) + elif code == 48: + # Background + with suppress(StopIteration): + color_type = next(iter_codes) + if color_type == 5: + self.style += _Style.from_color( + None, from_ansi(next(iter_codes)) + ) + elif color_type == 2: + self.style += _Style.from_color( + None, + from_rgb( + next(iter_codes), + next(iter_codes), + next(iter_codes), + ), + ) + + return text + + +if sys.platform != "win32" and __name__ == "__main__": # pragma: no cover + import io + import os + import pty + import sys + + decoder = AnsiDecoder() + + stdout = io.BytesIO() + + def read(fd: int) -> bytes: + data = os.read(fd, 1024) + stdout.write(data) + return data + + pty.spawn(sys.argv[1:], read) + + from .console import Console + + console = Console(record=True) + + stdout_result = stdout.getvalue().decode("utf-8") + print(stdout_result) + + for line in decoder.decode(stdout_result): + console.print(line) + + console.save_html("stdout.html") diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/bar.py b/data/miniconda3/lib/python3.13/site-packages/rich/bar.py new file mode 100644 index 0000000000000000000000000000000000000000..022284b57881d8b133aced5b5a843e6447bb4e0b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/bar.py @@ -0,0 +1,93 @@ +from typing import Optional, Union + +from .color import Color +from .console import Console, ConsoleOptions, RenderResult +from .jupyter import JupyterMixin +from .measure import Measurement +from .segment import Segment +from .style import Style + +# There are left-aligned characters for 1/8 to 7/8, but +# the right-aligned characters exist only for 1/8 and 4/8. +BEGIN_BLOCK_ELEMENTS = ["█", "█", "█", "▐", "▐", "▐", "▕", "▕"] +END_BLOCK_ELEMENTS = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"] +FULL_BLOCK = "█" + + +class Bar(JupyterMixin): + """Renders a solid block bar. + + Args: + size (float): Value for the end of the bar. + begin (float): Begin point (between 0 and size, inclusive). + end (float): End point (between 0 and size, inclusive). + width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None. + color (Union[Color, str], optional): Color of the bar. Defaults to "default". + bgcolor (Union[Color, str], optional): Color of bar background. Defaults to "default". + """ + + def __init__( + self, + size: float, + begin: float, + end: float, + *, + width: Optional[int] = None, + color: Union[Color, str] = "default", + bgcolor: Union[Color, str] = "default", + ): + self.size = size + self.begin = max(begin, 0) + self.end = min(end, size) + self.width = width + self.style = Style(color=color, bgcolor=bgcolor) + + def __repr__(self) -> str: + return f"Bar({self.size}, {self.begin}, {self.end})" + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + width = min( + self.width if self.width is not None else options.max_width, + options.max_width, + ) + + if self.begin >= self.end: + yield Segment(" " * width, self.style) + yield Segment.line() + return + + prefix_complete_eights = int(width * 8 * self.begin / self.size) + prefix_bar_count = prefix_complete_eights // 8 + prefix_eights_count = prefix_complete_eights % 8 + + body_complete_eights = int(width * 8 * self.end / self.size) + body_bar_count = body_complete_eights // 8 + body_eights_count = body_complete_eights % 8 + + # When start and end fall into the same cell, we ideally should render + # a symbol that's "center-aligned", but there is no good symbol in Unicode. + # In this case, we fall back to right-aligned block symbol for simplicity. + + prefix = " " * prefix_bar_count + if prefix_eights_count: + prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count] + + body = FULL_BLOCK * body_bar_count + if body_eights_count: + body += END_BLOCK_ELEMENTS[body_eights_count] + + suffix = " " * (width - len(body)) + + yield Segment(prefix + body[len(prefix) :] + suffix, self.style) + yield Segment.line() + + def __rich_measure__( + self, console: Console, options: ConsoleOptions + ) -> Measurement: + return ( + Measurement(self.width, self.width) + if self.width is not None + else Measurement(4, options.max_width) + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/box.py b/data/miniconda3/lib/python3.13/site-packages/rich/box.py new file mode 100644 index 0000000000000000000000000000000000000000..82555b61cd29efab220cf47b9fb3c26b80e8adde --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/box.py @@ -0,0 +1,474 @@ +from typing import TYPE_CHECKING, Iterable, List, Literal + + +from ._loop import loop_last + +if TYPE_CHECKING: + from rich.console import ConsoleOptions + + +class Box: + """Defines characters to render boxes. + + ┌─┬┐ top + │ ││ head + ├─┼┤ head_row + │ ││ mid + ├─┼┤ row + ├─┼┤ foot_row + │ ││ foot + └─┴┘ bottom + + Args: + box (str): Characters making up box. + ascii (bool, optional): True if this box uses ascii characters only. Default is False. + """ + + def __init__(self, box: str, *, ascii: bool = False) -> None: + self._box = box + self.ascii = ascii + line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines() + # top + self.top_left, self.top, self.top_divider, self.top_right = iter(line1) + # head + self.head_left, _, self.head_vertical, self.head_right = iter(line2) + # head_row + ( + self.head_row_left, + self.head_row_horizontal, + self.head_row_cross, + self.head_row_right, + ) = iter(line3) + + # mid + self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4) + # row + self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5) + # foot_row + ( + self.foot_row_left, + self.foot_row_horizontal, + self.foot_row_cross, + self.foot_row_right, + ) = iter(line6) + # foot + self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7) + # bottom + self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter( + line8 + ) + + def __repr__(self) -> str: + return "Box(...)" + + def __str__(self) -> str: + return self._box + + def substitute(self, options: "ConsoleOptions", safe: bool = True) -> "Box": + """Substitute this box for another if it won't render due to platform issues. + + Args: + options (ConsoleOptions): Console options used in rendering. + safe (bool, optional): Substitute this for another Box if there are known problems + displaying on the platform (currently only relevant on Windows). Default is True. + + Returns: + Box: A different Box or the same Box. + """ + box = self + if options.legacy_windows and safe: + box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box) + if options.ascii_only and not box.ascii: + box = ASCII + return box + + def get_plain_headed_box(self) -> "Box": + """If this box uses special characters for the borders of the header, then + return the equivalent box that does not. + + Returns: + Box: The most similar Box that doesn't use header-specific box characters. + If the current Box already satisfies this criterion, then it's returned. + """ + return PLAIN_HEADED_SUBSTITUTIONS.get(self, self) + + def get_top(self, widths: Iterable[int]) -> str: + """Get the top of a simple box. + + Args: + widths (List[int]): Widths of columns. + + Returns: + str: A string of box characters. + """ + + parts: List[str] = [] + append = parts.append + append(self.top_left) + for last, width in loop_last(widths): + append(self.top * width) + if not last: + append(self.top_divider) + append(self.top_right) + return "".join(parts) + + def get_row( + self, + widths: Iterable[int], + level: Literal["head", "row", "foot", "mid"] = "row", + edge: bool = True, + ) -> str: + """Get the top of a simple box. + + Args: + width (List[int]): Widths of columns. + + Returns: + str: A string of box characters. + """ + if level == "head": + left = self.head_row_left + horizontal = self.head_row_horizontal + cross = self.head_row_cross + right = self.head_row_right + elif level == "row": + left = self.row_left + horizontal = self.row_horizontal + cross = self.row_cross + right = self.row_right + elif level == "mid": + left = self.mid_left + horizontal = " " + cross = self.mid_vertical + right = self.mid_right + elif level == "foot": + left = self.foot_row_left + horizontal = self.foot_row_horizontal + cross = self.foot_row_cross + right = self.foot_row_right + else: + raise ValueError("level must be 'head', 'row' or 'foot'") + + parts: List[str] = [] + append = parts.append + if edge: + append(left) + for last, width in loop_last(widths): + append(horizontal * width) + if not last: + append(cross) + if edge: + append(right) + return "".join(parts) + + def get_bottom(self, widths: Iterable[int]) -> str: + """Get the bottom of a simple box. + + Args: + widths (List[int]): Widths of columns. + + Returns: + str: A string of box characters. + """ + + parts: List[str] = [] + append = parts.append + append(self.bottom_left) + for last, width in loop_last(widths): + append(self.bottom * width) + if not last: + append(self.bottom_divider) + append(self.bottom_right) + return "".join(parts) + + +# fmt: off +ASCII: Box = Box( + "+--+\n" + "| ||\n" + "|-+|\n" + "| ||\n" + "|-+|\n" + "|-+|\n" + "| ||\n" + "+--+\n", + ascii=True, +) + +ASCII2: Box = Box( + "+-++\n" + "| ||\n" + "+-++\n" + "| ||\n" + "+-++\n" + "+-++\n" + "| ||\n" + "+-++\n", + ascii=True, +) + +ASCII_DOUBLE_HEAD: Box = Box( + "+-++\n" + "| ||\n" + "+=++\n" + "| ||\n" + "+-++\n" + "+-++\n" + "| ||\n" + "+-++\n", + ascii=True, +) + +SQUARE: Box = Box( + "┌─┬┐\n" + "│ ││\n" + "├─┼┤\n" + "│ ││\n" + "├─┼┤\n" + "├─┼┤\n" + "│ ││\n" + "└─┴┘\n" +) + +SQUARE_DOUBLE_HEAD: Box = Box( + "┌─┬┐\n" + "│ ││\n" + "╞═╪╡\n" + "│ ││\n" + "├─┼┤\n" + "├─┼┤\n" + "│ ││\n" + "└─┴┘\n" +) + +MINIMAL: Box = Box( + " ╷ \n" + " │ \n" + "╶─┼╴\n" + " │ \n" + "╶─┼╴\n" + "╶─┼╴\n" + " │ \n" + " ╵ \n" +) + + +MINIMAL_HEAVY_HEAD: Box = Box( + " ╷ \n" + " │ \n" + "╺━┿╸\n" + " │ \n" + "╶─┼╴\n" + "╶─┼╴\n" + " │ \n" + " ╵ \n" +) + +MINIMAL_DOUBLE_HEAD: Box = Box( + " ╷ \n" + " │ \n" + " ═╪ \n" + " │ \n" + " ─┼ \n" + " ─┼ \n" + " │ \n" + " ╵ \n" +) + + +SIMPLE: Box = Box( + " \n" + " \n" + " ── \n" + " \n" + " \n" + " ── \n" + " \n" + " \n" +) + +SIMPLE_HEAD: Box = Box( + " \n" + " \n" + " ── \n" + " \n" + " \n" + " \n" + " \n" + " \n" +) + + +SIMPLE_HEAVY: Box = Box( + " \n" + " \n" + " ━━ \n" + " \n" + " \n" + " ━━ \n" + " \n" + " \n" +) + + +HORIZONTALS: Box = Box( + " ── \n" + " \n" + " ── \n" + " \n" + " ── \n" + " ── \n" + " \n" + " ── \n" +) + +ROUNDED: Box = Box( + "╭─┬╮\n" + "│ ││\n" + "├─┼┤\n" + "│ ││\n" + "├─┼┤\n" + "├─┼┤\n" + "│ ││\n" + "╰─┴╯\n" +) + +HEAVY: Box = Box( + "┏━┳┓\n" + "┃ ┃┃\n" + "┣━╋┫\n" + "┃ ┃┃\n" + "┣━╋┫\n" + "┣━╋┫\n" + "┃ ┃┃\n" + "┗━┻┛\n" +) + +HEAVY_EDGE: Box = Box( + "┏━┯┓\n" + "┃ │┃\n" + "┠─┼┨\n" + "┃ │┃\n" + "┠─┼┨\n" + "┠─┼┨\n" + "┃ │┃\n" + "┗━┷┛\n" +) + +HEAVY_HEAD: Box = Box( + "┏━┳┓\n" + "┃ ┃┃\n" + "┡━╇┩\n" + "│ ││\n" + "├─┼┤\n" + "├─┼┤\n" + "│ ││\n" + "└─┴┘\n" +) + +DOUBLE: Box = Box( + "╔═╦╗\n" + "║ ║║\n" + "╠═╬╣\n" + "║ ║║\n" + "╠═╬╣\n" + "╠═╬╣\n" + "║ ║║\n" + "╚═╩╝\n" +) + +DOUBLE_EDGE: Box = Box( + "╔═╤╗\n" + "║ │║\n" + "╟─┼╢\n" + "║ │║\n" + "╟─┼╢\n" + "╟─┼╢\n" + "║ │║\n" + "╚═╧╝\n" +) + +MARKDOWN: Box = Box( + " \n" + "| ||\n" + "|-||\n" + "| ||\n" + "|-||\n" + "|-||\n" + "| ||\n" + " \n", + ascii=True, +) +# fmt: on + +# Map Boxes that don't render with raster fonts on to equivalent that do +LEGACY_WINDOWS_SUBSTITUTIONS = { + ROUNDED: SQUARE, + MINIMAL_HEAVY_HEAD: MINIMAL, + SIMPLE_HEAVY: SIMPLE, + HEAVY: SQUARE, + HEAVY_EDGE: SQUARE, + HEAVY_HEAD: SQUARE, +} + +# Map headed boxes to their headerless equivalents +PLAIN_HEADED_SUBSTITUTIONS = { + HEAVY_HEAD: SQUARE, + SQUARE_DOUBLE_HEAD: SQUARE, + MINIMAL_DOUBLE_HEAD: MINIMAL, + MINIMAL_HEAVY_HEAD: MINIMAL, + ASCII_DOUBLE_HEAD: ASCII2, +} + + +if __name__ == "__main__": # pragma: no cover + from rich.columns import Columns + from rich.panel import Panel + + from . import box as box + from .console import Console + from .table import Table + from .text import Text + + console = Console(record=True) + + BOXES = [ + "ASCII", + "ASCII2", + "ASCII_DOUBLE_HEAD", + "SQUARE", + "SQUARE_DOUBLE_HEAD", + "MINIMAL", + "MINIMAL_HEAVY_HEAD", + "MINIMAL_DOUBLE_HEAD", + "SIMPLE", + "SIMPLE_HEAD", + "SIMPLE_HEAVY", + "HORIZONTALS", + "ROUNDED", + "HEAVY", + "HEAVY_EDGE", + "HEAVY_HEAD", + "DOUBLE", + "DOUBLE_EDGE", + "MARKDOWN", + ] + + console.print(Panel("[bold green]Box Constants", style="green"), justify="center") + console.print() + + columns = Columns(expand=True, padding=2) + for box_name in sorted(BOXES): + table = Table( + show_footer=True, style="dim", border_style="not dim", expand=True + ) + table.add_column("Header 1", "Footer 1") + table.add_column("Header 2", "Footer 2") + table.add_row("Cell", "Cell") + table.add_row("Cell", "Cell") + table.box = getattr(box, box_name) + table.title = Text(f"box.{box_name}", style="magenta") + columns.add_renderable(table) + console.print(columns) + + # console.save_svg("box.svg") diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/cells.py b/data/miniconda3/lib/python3.13/site-packages/rich/cells.py new file mode 100644 index 0000000000000000000000000000000000000000..a85462271c9a14f88fda9a3954f98e857fb5aac8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/cells.py @@ -0,0 +1,174 @@ +from __future__ import annotations + +from functools import lru_cache +from typing import Callable + +from ._cell_widths import CELL_WIDTHS + +# Ranges of unicode ordinals that produce a 1-cell wide character +# This is non-exhaustive, but covers most common Western characters +_SINGLE_CELL_UNICODE_RANGES: list[tuple[int, int]] = [ + (0x20, 0x7E), # Latin (excluding non-printable) + (0xA0, 0xAC), + (0xAE, 0x002FF), + (0x00370, 0x00482), # Greek / Cyrillic + (0x02500, 0x025FC), # Box drawing, box elements, geometric shapes + (0x02800, 0x028FF), # Braille +] + +# A set of characters that are a single cell wide +_SINGLE_CELLS = frozenset( + [ + character + for _start, _end in _SINGLE_CELL_UNICODE_RANGES + for character in map(chr, range(_start, _end + 1)) + ] +) + +# When called with a string this will return True if all +# characters are single-cell, otherwise False +_is_single_cell_widths: Callable[[str], bool] = _SINGLE_CELLS.issuperset + + +@lru_cache(4096) +def cached_cell_len(text: str) -> int: + """Get the number of cells required to display text. + + This method always caches, which may use up a lot of memory. It is recommended to use + `cell_len` over this method. + + Args: + text (str): Text to display. + + Returns: + int: Get the number of cells required to display text. + """ + if _is_single_cell_widths(text): + return len(text) + return sum(map(get_character_cell_size, text)) + + +def cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> int: + """Get the number of cells required to display text. + + Args: + text (str): Text to display. + + Returns: + int: Get the number of cells required to display text. + """ + if len(text) < 512: + return _cell_len(text) + if _is_single_cell_widths(text): + return len(text) + return sum(map(get_character_cell_size, text)) + + +@lru_cache(maxsize=4096) +def get_character_cell_size(character: str) -> int: + """Get the cell size of a character. + + Args: + character (str): A single character. + + Returns: + int: Number of cells (0, 1 or 2) occupied by that character. + """ + codepoint = ord(character) + _table = CELL_WIDTHS + lower_bound = 0 + upper_bound = len(_table) - 1 + index = (lower_bound + upper_bound) // 2 + while True: + start, end, width = _table[index] + if codepoint < start: + upper_bound = index - 1 + elif codepoint > end: + lower_bound = index + 1 + else: + return 0 if width == -1 else width + if upper_bound < lower_bound: + break + index = (lower_bound + upper_bound) // 2 + return 1 + + +def set_cell_size(text: str, total: int) -> str: + """Set the length of a string to fit within given number of cells.""" + + if _is_single_cell_widths(text): + size = len(text) + if size < total: + return text + " " * (total - size) + return text[:total] + + if total <= 0: + return "" + cell_size = cell_len(text) + if cell_size == total: + return text + if cell_size < total: + return text + " " * (total - cell_size) + + start = 0 + end = len(text) + + # Binary search until we find the right size + while True: + pos = (start + end) // 2 + before = text[: pos + 1] + before_len = cell_len(before) + if before_len == total + 1 and cell_len(before[-1]) == 2: + return before[:-1] + " " + if before_len == total: + return before + if before_len > total: + end = pos + else: + start = pos + + +def chop_cells( + text: str, + width: int, +) -> list[str]: + """Split text into lines such that each line fits within the available (cell) width. + + Args: + text: The text to fold such that it fits in the given width. + width: The width available (number of cells). + + Returns: + A list of strings such that each string in the list has cell width + less than or equal to the available width. + """ + _get_character_cell_size = get_character_cell_size + lines: list[list[str]] = [[]] + + append_new_line = lines.append + append_to_last_line = lines[-1].append + + total_width = 0 + + for character in text: + cell_width = _get_character_cell_size(character) + char_doesnt_fit = total_width + cell_width > width + + if char_doesnt_fit: + append_new_line([character]) + append_to_last_line = lines[-1].append + total_width = cell_width + else: + append_to_last_line(character) + total_width += cell_width + + return ["".join(line) for line in lines] + + +if __name__ == "__main__": # pragma: no cover + print(get_character_cell_size("😽")) + for line in chop_cells("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", 8): + print(line) + for n in range(80, 1, -1): + print(set_cell_size("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", n) + "|") + print("x" * n) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/color.py b/data/miniconda3/lib/python3.13/site-packages/rich/color.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c23a6a91b833fd9bb20bd5238421a5c0f08df3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/color.py @@ -0,0 +1,621 @@ +import re +import sys +from colorsys import rgb_to_hls +from enum import IntEnum +from functools import lru_cache +from typing import TYPE_CHECKING, NamedTuple, Optional, Tuple + +from ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE +from .color_triplet import ColorTriplet +from .repr import Result, rich_repr +from .terminal_theme import DEFAULT_TERMINAL_THEME + +if TYPE_CHECKING: # pragma: no cover + from .terminal_theme import TerminalTheme + from .text import Text + + +WINDOWS = sys.platform == "win32" + + +class ColorSystem(IntEnum): + """One of the 3 color system supported by terminals.""" + + STANDARD = 1 + EIGHT_BIT = 2 + TRUECOLOR = 3 + WINDOWS = 4 + + def __repr__(self) -> str: + return f"ColorSystem.{self.name}" + + def __str__(self) -> str: + return repr(self) + + +class ColorType(IntEnum): + """Type of color stored in Color class.""" + + DEFAULT = 0 + STANDARD = 1 + EIGHT_BIT = 2 + TRUECOLOR = 3 + WINDOWS = 4 + + def __repr__(self) -> str: + return f"ColorType.{self.name}" + + +ANSI_COLOR_NAMES = { + "black": 0, + "red": 1, + "green": 2, + "yellow": 3, + "blue": 4, + "magenta": 5, + "cyan": 6, + "white": 7, + "bright_black": 8, + "bright_red": 9, + "bright_green": 10, + "bright_yellow": 11, + "bright_blue": 12, + "bright_magenta": 13, + "bright_cyan": 14, + "bright_white": 15, + "grey0": 16, + "gray0": 16, + "navy_blue": 17, + "dark_blue": 18, + "blue3": 20, + "blue1": 21, + "dark_green": 22, + "deep_sky_blue4": 25, + "dodger_blue3": 26, + "dodger_blue2": 27, + "green4": 28, + "spring_green4": 29, + "turquoise4": 30, + "deep_sky_blue3": 32, + "dodger_blue1": 33, + "green3": 40, + "spring_green3": 41, + "dark_cyan": 36, + "light_sea_green": 37, + "deep_sky_blue2": 38, + "deep_sky_blue1": 39, + "spring_green2": 47, + "cyan3": 43, + "dark_turquoise": 44, + "turquoise2": 45, + "green1": 46, + "spring_green1": 48, + "medium_spring_green": 49, + "cyan2": 50, + "cyan1": 51, + "dark_red": 88, + "deep_pink4": 125, + "purple4": 55, + "purple3": 56, + "blue_violet": 57, + "orange4": 94, + "grey37": 59, + "gray37": 59, + "medium_purple4": 60, + "slate_blue3": 62, + "royal_blue1": 63, + "chartreuse4": 64, + "dark_sea_green4": 71, + "pale_turquoise4": 66, + "steel_blue": 67, + "steel_blue3": 68, + "cornflower_blue": 69, + "chartreuse3": 76, + "cadet_blue": 73, + "sky_blue3": 74, + "steel_blue1": 81, + "pale_green3": 114, + "sea_green3": 78, + "aquamarine3": 79, + "medium_turquoise": 80, + "chartreuse2": 112, + "sea_green2": 83, + "sea_green1": 85, + "aquamarine1": 122, + "dark_slate_gray2": 87, + "dark_magenta": 91, + "dark_violet": 128, + "purple": 129, + "light_pink4": 95, + "plum4": 96, + "medium_purple3": 98, + "slate_blue1": 99, + "yellow4": 106, + "wheat4": 101, + "grey53": 102, + "gray53": 102, + "light_slate_grey": 103, + "light_slate_gray": 103, + "medium_purple": 104, + "light_slate_blue": 105, + "dark_olive_green3": 149, + "dark_sea_green": 108, + "light_sky_blue3": 110, + "sky_blue2": 111, + "dark_sea_green3": 150, + "dark_slate_gray3": 116, + "sky_blue1": 117, + "chartreuse1": 118, + "light_green": 120, + "pale_green1": 156, + "dark_slate_gray1": 123, + "red3": 160, + "medium_violet_red": 126, + "magenta3": 164, + "dark_orange3": 166, + "indian_red": 167, + "hot_pink3": 168, + "medium_orchid3": 133, + "medium_orchid": 134, + "medium_purple2": 140, + "dark_goldenrod": 136, + "light_salmon3": 173, + "rosy_brown": 138, + "grey63": 139, + "gray63": 139, + "medium_purple1": 141, + "gold3": 178, + "dark_khaki": 143, + "navajo_white3": 144, + "grey69": 145, + "gray69": 145, + "light_steel_blue3": 146, + "light_steel_blue": 147, + "yellow3": 184, + "dark_sea_green2": 157, + "light_cyan3": 152, + "light_sky_blue1": 153, + "green_yellow": 154, + "dark_olive_green2": 155, + "dark_sea_green1": 193, + "pale_turquoise1": 159, + "deep_pink3": 162, + "magenta2": 200, + "hot_pink2": 169, + "orchid": 170, + "medium_orchid1": 207, + "orange3": 172, + "light_pink3": 174, + "pink3": 175, + "plum3": 176, + "violet": 177, + "light_goldenrod3": 179, + "tan": 180, + "misty_rose3": 181, + "thistle3": 182, + "plum2": 183, + "khaki3": 185, + "light_goldenrod2": 222, + "light_yellow3": 187, + "grey84": 188, + "gray84": 188, + "light_steel_blue1": 189, + "yellow2": 190, + "dark_olive_green1": 192, + "honeydew2": 194, + "light_cyan1": 195, + "red1": 196, + "deep_pink2": 197, + "deep_pink1": 199, + "magenta1": 201, + "orange_red1": 202, + "indian_red1": 204, + "hot_pink": 206, + "dark_orange": 208, + "salmon1": 209, + "light_coral": 210, + "pale_violet_red1": 211, + "orchid2": 212, + "orchid1": 213, + "orange1": 214, + "sandy_brown": 215, + "light_salmon1": 216, + "light_pink1": 217, + "pink1": 218, + "plum1": 219, + "gold1": 220, + "navajo_white1": 223, + "misty_rose1": 224, + "thistle1": 225, + "yellow1": 226, + "light_goldenrod1": 227, + "khaki1": 228, + "wheat1": 229, + "cornsilk1": 230, + "grey100": 231, + "gray100": 231, + "grey3": 232, + "gray3": 232, + "grey7": 233, + "gray7": 233, + "grey11": 234, + "gray11": 234, + "grey15": 235, + "gray15": 235, + "grey19": 236, + "gray19": 236, + "grey23": 237, + "gray23": 237, + "grey27": 238, + "gray27": 238, + "grey30": 239, + "gray30": 239, + "grey35": 240, + "gray35": 240, + "grey39": 241, + "gray39": 241, + "grey42": 242, + "gray42": 242, + "grey46": 243, + "gray46": 243, + "grey50": 244, + "gray50": 244, + "grey54": 245, + "gray54": 245, + "grey58": 246, + "gray58": 246, + "grey62": 247, + "gray62": 247, + "grey66": 248, + "gray66": 248, + "grey70": 249, + "gray70": 249, + "grey74": 250, + "gray74": 250, + "grey78": 251, + "gray78": 251, + "grey82": 252, + "gray82": 252, + "grey85": 253, + "gray85": 253, + "grey89": 254, + "gray89": 254, + "grey93": 255, + "gray93": 255, +} + + +class ColorParseError(Exception): + """The color could not be parsed.""" + + +RE_COLOR = re.compile( + r"""^ +\#([0-9a-f]{6})$| +color\(([0-9]{1,3})\)$| +rgb\(([\d\s,]+)\)$ +""", + re.VERBOSE, +) + + +@rich_repr +class Color(NamedTuple): + """Terminal color definition.""" + + name: str + """The name of the color (typically the input to Color.parse).""" + type: ColorType + """The type of the color.""" + number: Optional[int] = None + """The color number, if a standard color, or None.""" + triplet: Optional[ColorTriplet] = None + """A triplet of color components, if an RGB color.""" + + def __rich__(self) -> "Text": + """Displays the actual color if Rich printed.""" + from .style import Style + from .text import Text + + return Text.assemble( + f"", + ) + + def __rich_repr__(self) -> Result: + yield self.name + yield self.type + yield "number", self.number, None + yield "triplet", self.triplet, None + + @property + def system(self) -> ColorSystem: + """Get the native color system for this color.""" + if self.type == ColorType.DEFAULT: + return ColorSystem.STANDARD + return ColorSystem(int(self.type)) + + @property + def is_system_defined(self) -> bool: + """Check if the color is ultimately defined by the system.""" + return self.system not in (ColorSystem.EIGHT_BIT, ColorSystem.TRUECOLOR) + + @property + def is_default(self) -> bool: + """Check if the color is a default color.""" + return self.type == ColorType.DEFAULT + + def get_truecolor( + self, theme: Optional["TerminalTheme"] = None, foreground: bool = True + ) -> ColorTriplet: + """Get an equivalent color triplet for this color. + + Args: + theme (TerminalTheme, optional): Optional terminal theme, or None to use default. Defaults to None. + foreground (bool, optional): True for a foreground color, or False for background. Defaults to True. + + Returns: + ColorTriplet: A color triplet containing RGB components. + """ + + if theme is None: + theme = DEFAULT_TERMINAL_THEME + if self.type == ColorType.TRUECOLOR: + assert self.triplet is not None + return self.triplet + elif self.type == ColorType.EIGHT_BIT: + assert self.number is not None + return EIGHT_BIT_PALETTE[self.number] + elif self.type == ColorType.STANDARD: + assert self.number is not None + return theme.ansi_colors[self.number] + elif self.type == ColorType.WINDOWS: + assert self.number is not None + return WINDOWS_PALETTE[self.number] + else: # self.type == ColorType.DEFAULT: + assert self.number is None + return theme.foreground_color if foreground else theme.background_color + + @classmethod + def from_ansi(cls, number: int) -> "Color": + """Create a Color number from it's 8-bit ansi number. + + Args: + number (int): A number between 0-255 inclusive. + + Returns: + Color: A new Color instance. + """ + return cls( + name=f"color({number})", + type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT), + number=number, + ) + + @classmethod + def from_triplet(cls, triplet: "ColorTriplet") -> "Color": + """Create a truecolor RGB color from a triplet of values. + + Args: + triplet (ColorTriplet): A color triplet containing red, green and blue components. + + Returns: + Color: A new color object. + """ + return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet) + + @classmethod + def from_rgb(cls, red: float, green: float, blue: float) -> "Color": + """Create a truecolor from three color components in the range(0->255). + + Args: + red (float): Red component in range 0-255. + green (float): Green component in range 0-255. + blue (float): Blue component in range 0-255. + + Returns: + Color: A new color object. + """ + return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue))) + + @classmethod + def default(cls) -> "Color": + """Get a Color instance representing the default color. + + Returns: + Color: Default color. + """ + return cls(name="default", type=ColorType.DEFAULT) + + @classmethod + @lru_cache(maxsize=1024) + def parse(cls, color: str) -> "Color": + """Parse a color definition.""" + original_color = color + color = color.lower().strip() + + if color == "default": + return cls(color, type=ColorType.DEFAULT) + + color_number = ANSI_COLOR_NAMES.get(color) + if color_number is not None: + return cls( + color, + type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT), + number=color_number, + ) + + color_match = RE_COLOR.match(color) + if color_match is None: + raise ColorParseError(f"{original_color!r} is not a valid color") + + color_24, color_8, color_rgb = color_match.groups() + if color_24: + triplet = ColorTriplet( + int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16) + ) + return cls(color, ColorType.TRUECOLOR, triplet=triplet) + + elif color_8: + number = int(color_8) + if number > 255: + raise ColorParseError(f"color number must be <= 255 in {color!r}") + return cls( + color, + type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT), + number=number, + ) + + else: # color_rgb: + components = color_rgb.split(",") + if len(components) != 3: + raise ColorParseError( + f"expected three components in {original_color!r}" + ) + red, green, blue = components + triplet = ColorTriplet(int(red), int(green), int(blue)) + if not all(component <= 255 for component in triplet): + raise ColorParseError( + f"color components must be <= 255 in {original_color!r}" + ) + return cls(color, ColorType.TRUECOLOR, triplet=triplet) + + @lru_cache(maxsize=1024) + def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]: + """Get the ANSI escape codes for this color.""" + _type = self.type + if _type == ColorType.DEFAULT: + return ("39" if foreground else "49",) + + elif _type == ColorType.WINDOWS: + number = self.number + assert number is not None + fore, back = (30, 40) if number < 8 else (82, 92) + return (str(fore + number if foreground else back + number),) + + elif _type == ColorType.STANDARD: + number = self.number + assert number is not None + fore, back = (30, 40) if number < 8 else (82, 92) + return (str(fore + number if foreground else back + number),) + + elif _type == ColorType.EIGHT_BIT: + assert self.number is not None + return ("38" if foreground else "48", "5", str(self.number)) + + else: # self.standard == ColorStandard.TRUECOLOR: + assert self.triplet is not None + red, green, blue = self.triplet + return ("38" if foreground else "48", "2", str(red), str(green), str(blue)) + + @lru_cache(maxsize=1024) + def downgrade(self, system: ColorSystem) -> "Color": + """Downgrade a color system to a system with fewer colors.""" + + if self.type in (ColorType.DEFAULT, system): + return self + # Convert to 8-bit color from truecolor color + if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR: + assert self.triplet is not None + _h, l, s = rgb_to_hls(*self.triplet.normalized) + # If saturation is under 15% assume it is grayscale + if s < 0.15: + gray = round(l * 25.0) + if gray == 0: + color_number = 16 + elif gray == 25: + color_number = 231 + else: + color_number = 231 + gray + return Color(self.name, ColorType.EIGHT_BIT, number=color_number) + + red, green, blue = self.triplet + six_red = red / 95 if red < 95 else 1 + (red - 95) / 40 + six_green = green / 95 if green < 95 else 1 + (green - 95) / 40 + six_blue = blue / 95 if blue < 95 else 1 + (blue - 95) / 40 + + color_number = ( + 16 + 36 * round(six_red) + 6 * round(six_green) + round(six_blue) + ) + return Color(self.name, ColorType.EIGHT_BIT, number=color_number) + + # Convert to standard from truecolor or 8-bit + elif system == ColorSystem.STANDARD: + if self.system == ColorSystem.TRUECOLOR: + assert self.triplet is not None + triplet = self.triplet + else: # self.system == ColorSystem.EIGHT_BIT + assert self.number is not None + triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number]) + + color_number = STANDARD_PALETTE.match(triplet) + return Color(self.name, ColorType.STANDARD, number=color_number) + + elif system == ColorSystem.WINDOWS: + if self.system == ColorSystem.TRUECOLOR: + assert self.triplet is not None + triplet = self.triplet + else: # self.system == ColorSystem.EIGHT_BIT + assert self.number is not None + if self.number < 16: + return Color(self.name, ColorType.WINDOWS, number=self.number) + triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number]) + + color_number = WINDOWS_PALETTE.match(triplet) + return Color(self.name, ColorType.WINDOWS, number=color_number) + + return self + + +def parse_rgb_hex(hex_color: str) -> ColorTriplet: + """Parse six hex characters in to RGB triplet.""" + assert len(hex_color) == 6, "must be 6 characters" + color = ColorTriplet( + int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16) + ) + return color + + +def blend_rgb( + color1: ColorTriplet, color2: ColorTriplet, cross_fade: float = 0.5 +) -> ColorTriplet: + """Blend one RGB color in to another.""" + r1, g1, b1 = color1 + r2, g2, b2 = color2 + new_color = ColorTriplet( + int(r1 + (r2 - r1) * cross_fade), + int(g1 + (g2 - g1) * cross_fade), + int(b1 + (b2 - b1) * cross_fade), + ) + return new_color + + +if __name__ == "__main__": # pragma: no cover + from .console import Console + from .table import Table + from .text import Text + + console = Console() + + table = Table(show_footer=False, show_edge=True) + table.add_column("Color", width=10, overflow="ellipsis") + table.add_column("Number", justify="right", style="yellow") + table.add_column("Name", style="green") + table.add_column("Hex", style="blue") + table.add_column("RGB", style="magenta") + + colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items()) + for color_number, name in colors: + if "grey" in name: + continue + color_cell = Text(" " * 10, style=f"on {name}") + if color_number < 16: + table.add_row(color_cell, f"{color_number}", Text(f'"{name}"')) + else: + color = EIGHT_BIT_PALETTE[color_number] # type: ignore[has-type] + table.add_row( + color_cell, str(color_number), Text(f'"{name}"'), color.hex, color.rgb + ) + + console.print(table) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/color_triplet.py b/data/miniconda3/lib/python3.13/site-packages/rich/color_triplet.py new file mode 100644 index 0000000000000000000000000000000000000000..02cab328251af9bfa809981aaa44933c407e2cd7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/color_triplet.py @@ -0,0 +1,38 @@ +from typing import NamedTuple, Tuple + + +class ColorTriplet(NamedTuple): + """The red, green, and blue components of a color.""" + + red: int + """Red component in 0 to 255 range.""" + green: int + """Green component in 0 to 255 range.""" + blue: int + """Blue component in 0 to 255 range.""" + + @property + def hex(self) -> str: + """get the color triplet in CSS style.""" + red, green, blue = self + return f"#{red:02x}{green:02x}{blue:02x}" + + @property + def rgb(self) -> str: + """The color in RGB format. + + Returns: + str: An rgb color, e.g. ``"rgb(100,23,255)"``. + """ + red, green, blue = self + return f"rgb({red},{green},{blue})" + + @property + def normalized(self) -> Tuple[float, float, float]: + """Convert components into floats between 0 and 1. + + Returns: + Tuple[float, float, float]: A tuple of three normalized colour components. + """ + red, green, blue = self + return red / 255.0, green / 255.0, blue / 255.0 diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/columns.py b/data/miniconda3/lib/python3.13/site-packages/rich/columns.py new file mode 100644 index 0000000000000000000000000000000000000000..669a3a7074f9a9e1af29cb4bc78b05851df67959 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/columns.py @@ -0,0 +1,187 @@ +from collections import defaultdict +from itertools import chain +from operator import itemgetter +from typing import Dict, Iterable, List, Optional, Tuple + +from .align import Align, AlignMethod +from .console import Console, ConsoleOptions, RenderableType, RenderResult +from .constrain import Constrain +from .measure import Measurement +from .padding import Padding, PaddingDimensions +from .table import Table +from .text import TextType +from .jupyter import JupyterMixin + + +class Columns(JupyterMixin): + """Display renderables in neat columns. + + Args: + renderables (Iterable[RenderableType]): Any number of Rich renderables (including str). + width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None. + padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1). + expand (bool, optional): Expand columns to full width. Defaults to False. + equal (bool, optional): Arrange in to equal sized columns. Defaults to False. + column_first (bool, optional): Align items from top to bottom (rather than left to right). Defaults to False. + right_to_left (bool, optional): Start column from right hand side. Defaults to False. + align (str, optional): Align value ("left", "right", or "center") or None for default. Defaults to None. + title (TextType, optional): Optional title for Columns. + """ + + def __init__( + self, + renderables: Optional[Iterable[RenderableType]] = None, + padding: PaddingDimensions = (0, 1), + *, + width: Optional[int] = None, + expand: bool = False, + equal: bool = False, + column_first: bool = False, + right_to_left: bool = False, + align: Optional[AlignMethod] = None, + title: Optional[TextType] = None, + ) -> None: + self.renderables = list(renderables or []) + self.width = width + self.padding = padding + self.expand = expand + self.equal = equal + self.column_first = column_first + self.right_to_left = right_to_left + self.align: Optional[AlignMethod] = align + self.title = title + + def add_renderable(self, renderable: RenderableType) -> None: + """Add a renderable to the columns. + + Args: + renderable (RenderableType): Any renderable object. + """ + self.renderables.append(renderable) + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + render_str = console.render_str + renderables = [ + render_str(renderable) if isinstance(renderable, str) else renderable + for renderable in self.renderables + ] + if not renderables: + return + _top, right, _bottom, left = Padding.unpack(self.padding) + width_padding = max(left, right) + max_width = options.max_width + widths: Dict[int, int] = defaultdict(int) + column_count = len(renderables) + + get_measurement = Measurement.get + renderable_widths = [ + get_measurement(console, options, renderable).maximum + for renderable in renderables + ] + if self.equal: + renderable_widths = [max(renderable_widths)] * len(renderable_widths) + + def iter_renderables( + column_count: int, + ) -> Iterable[Tuple[int, Optional[RenderableType]]]: + item_count = len(renderables) + if self.column_first: + width_renderables = list(zip(renderable_widths, renderables)) + + column_lengths: List[int] = [item_count // column_count] * column_count + for col_no in range(item_count % column_count): + column_lengths[col_no] += 1 + + row_count = (item_count + column_count - 1) // column_count + cells = [[-1] * column_count for _ in range(row_count)] + row = col = 0 + for index in range(item_count): + cells[row][col] = index + column_lengths[col] -= 1 + if column_lengths[col]: + row += 1 + else: + col += 1 + row = 0 + for index in chain.from_iterable(cells): + if index == -1: + break + yield width_renderables[index] + else: + yield from zip(renderable_widths, renderables) + # Pad odd elements with spaces + if item_count % column_count: + for _ in range(column_count - (item_count % column_count)): + yield 0, None + + table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False) + table.expand = self.expand + table.title = self.title + + if self.width is not None: + column_count = (max_width) // (self.width + width_padding) + for _ in range(column_count): + table.add_column(width=self.width) + else: + while column_count > 1: + widths.clear() + column_no = 0 + for renderable_width, _ in iter_renderables(column_count): + widths[column_no] = max(widths[column_no], renderable_width) + total_width = sum(widths.values()) + width_padding * ( + len(widths) - 1 + ) + if total_width > max_width: + column_count = len(widths) - 1 + break + else: + column_no = (column_no + 1) % column_count + else: + break + + get_renderable = itemgetter(1) + _renderables = [ + get_renderable(_renderable) + for _renderable in iter_renderables(column_count) + ] + if self.equal: + _renderables = [ + None + if renderable is None + else Constrain(renderable, renderable_widths[0]) + for renderable in _renderables + ] + if self.align: + align = self.align + _Align = Align + _renderables = [ + None if renderable is None else _Align(renderable, align) + for renderable in _renderables + ] + + right_to_left = self.right_to_left + add_row = table.add_row + for start in range(0, len(_renderables), column_count): + row = _renderables[start : start + column_count] + if right_to_left: + row = row[::-1] + add_row(*row) + yield table + + +if __name__ == "__main__": # pragma: no cover + import os + + console = Console() + + files = [f"{i} {s}" for i, s in enumerate(sorted(os.listdir()))] + columns = Columns(files, padding=(0, 1), expand=False, equal=False) + console.print(columns) + console.rule() + columns.column_first = True + console.print(columns) + columns.right_to_left = True + console.rule() + console.print(columns) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/console.py b/data/miniconda3/lib/python3.13/site-packages/rich/console.py new file mode 100644 index 0000000000000000000000000000000000000000..994adfc069e36a883dd93c908bf9ef685c453b05 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/console.py @@ -0,0 +1,2680 @@ +import inspect +import os +import sys +import threading +import zlib +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from datetime import datetime +from functools import wraps +from getpass import getpass +from html import escape +from inspect import isclass +from itertools import islice +from math import ceil +from time import monotonic +from types import FrameType, ModuleType, TracebackType +from typing import ( + IO, + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Literal, + Mapping, + NamedTuple, + Optional, + Protocol, + TextIO, + Tuple, + Type, + Union, + cast, + runtime_checkable, +) + +from rich._null_file import NULL_FILE + +from . import errors, themes +from ._emoji_replace import _emoji_replace +from ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT +from ._fileno import get_fileno +from ._log_render import FormatTimeCallable, LogRender +from .align import Align, AlignMethod +from .color import ColorSystem, blend_rgb +from .control import Control +from .emoji import EmojiVariant +from .highlighter import NullHighlighter, ReprHighlighter +from .markup import render as render_markup +from .measure import Measurement, measure_renderables +from .pager import Pager, SystemPager +from .pretty import Pretty, is_expandable +from .protocol import rich_cast +from .region import Region +from .scope import render_scope +from .screen import Screen +from .segment import Segment +from .style import Style, StyleType +from .styled import Styled +from .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme +from .text import Text, TextType +from .theme import Theme, ThemeStack + +if TYPE_CHECKING: + from ._windows import WindowsConsoleFeatures + from .live import Live + from .status import Status + +JUPYTER_DEFAULT_COLUMNS = 115 +JUPYTER_DEFAULT_LINES = 100 +WINDOWS = sys.platform == "win32" + +HighlighterType = Callable[[Union[str, "Text"]], "Text"] +JustifyMethod = Literal["default", "left", "center", "right", "full"] +OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"] + + +class NoChange: + pass + + +NO_CHANGE = NoChange() + +try: + _STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr] +except Exception: + _STDIN_FILENO = 0 +try: + _STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr] +except Exception: + _STDOUT_FILENO = 1 +try: + _STDERR_FILENO = sys.__stderr__.fileno() # type: ignore[union-attr] +except Exception: + _STDERR_FILENO = 2 + +_STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO) +_STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO) + + +_TERM_COLORS = { + "kitty": ColorSystem.EIGHT_BIT, + "256color": ColorSystem.EIGHT_BIT, + "16color": ColorSystem.STANDARD, +} + + +class ConsoleDimensions(NamedTuple): + """Size of the terminal.""" + + width: int + """The width of the console in 'cells'.""" + height: int + """The height of the console in lines.""" + + +@dataclass +class ConsoleOptions: + """Options for __rich_console__ method.""" + + size: ConsoleDimensions + """Size of console.""" + legacy_windows: bool + """legacy_windows: flag for legacy windows.""" + min_width: int + """Minimum width of renderable.""" + max_width: int + """Maximum width of renderable.""" + is_terminal: bool + """True if the target is a terminal, otherwise False.""" + encoding: str + """Encoding of terminal.""" + max_height: int + """Height of container (starts as terminal)""" + justify: Optional[JustifyMethod] = None + """Justify value override for renderable.""" + overflow: Optional[OverflowMethod] = None + """Overflow value override for renderable.""" + no_wrap: Optional[bool] = False + """Disable wrapping for text.""" + highlight: Optional[bool] = None + """Highlight override for render_str.""" + markup: Optional[bool] = None + """Enable markup when rendering strings.""" + height: Optional[int] = None + + @property + def ascii_only(self) -> bool: + """Check if renderables should use ascii only.""" + return not self.encoding.startswith("utf") + + def copy(self) -> "ConsoleOptions": + """Return a copy of the options. + + Returns: + ConsoleOptions: a copy of self. + """ + options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions) + options.__dict__ = self.__dict__.copy() + return options + + def update( + self, + *, + width: Union[int, NoChange] = NO_CHANGE, + min_width: Union[int, NoChange] = NO_CHANGE, + max_width: Union[int, NoChange] = NO_CHANGE, + justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE, + overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE, + no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE, + highlight: Union[Optional[bool], NoChange] = NO_CHANGE, + markup: Union[Optional[bool], NoChange] = NO_CHANGE, + height: Union[Optional[int], NoChange] = NO_CHANGE, + ) -> "ConsoleOptions": + """Update values, return a copy.""" + options = self.copy() + if not isinstance(width, NoChange): + options.min_width = options.max_width = max(0, width) + if not isinstance(min_width, NoChange): + options.min_width = min_width + if not isinstance(max_width, NoChange): + options.max_width = max_width + if not isinstance(justify, NoChange): + options.justify = justify + if not isinstance(overflow, NoChange): + options.overflow = overflow + if not isinstance(no_wrap, NoChange): + options.no_wrap = no_wrap + if not isinstance(highlight, NoChange): + options.highlight = highlight + if not isinstance(markup, NoChange): + options.markup = markup + if not isinstance(height, NoChange): + if height is not None: + options.max_height = height + options.height = None if height is None else max(0, height) + return options + + def update_width(self, width: int) -> "ConsoleOptions": + """Update just the width, return a copy. + + Args: + width (int): New width (sets both min_width and max_width) + + Returns: + ~ConsoleOptions: New console options instance. + """ + options = self.copy() + options.min_width = options.max_width = max(0, width) + return options + + def update_height(self, height: int) -> "ConsoleOptions": + """Update the height, and return a copy. + + Args: + height (int): New height + + Returns: + ~ConsoleOptions: New Console options instance. + """ + options = self.copy() + options.max_height = options.height = height + return options + + def reset_height(self) -> "ConsoleOptions": + """Return a copy of the options with height set to ``None``. + + Returns: + ~ConsoleOptions: New console options instance. + """ + options = self.copy() + options.height = None + return options + + def update_dimensions(self, width: int, height: int) -> "ConsoleOptions": + """Update the width and height, and return a copy. + + Args: + width (int): New width (sets both min_width and max_width). + height (int): New height. + + Returns: + ~ConsoleOptions: New console options instance. + """ + options = self.copy() + options.min_width = options.max_width = max(0, width) + options.height = options.max_height = height + return options + + +@runtime_checkable +class RichCast(Protocol): + """An object that may be 'cast' to a console renderable.""" + + def __rich__( + self, + ) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover + ... + + +@runtime_checkable +class ConsoleRenderable(Protocol): + """An object that supports the console protocol.""" + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": # pragma: no cover + ... + + +# A type that may be rendered by Console. +RenderableType = Union[ConsoleRenderable, RichCast, str] +"""A string or any object that may be rendered by Rich.""" + +# The result of calling a __rich_console__ method. +RenderResult = Iterable[Union[RenderableType, Segment]] + +_null_highlighter = NullHighlighter() + + +class CaptureError(Exception): + """An error in the Capture context manager.""" + + +class NewLine: + """A renderable to generate new line(s)""" + + def __init__(self, count: int = 1) -> None: + self.count = count + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> Iterable[Segment]: + yield Segment("\n" * self.count) + + +class ScreenUpdate: + """Render a list of lines at a given offset.""" + + def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None: + self._lines = lines + self.x = x + self.y = y + + def __rich_console__( + self, console: "Console", options: ConsoleOptions + ) -> RenderResult: + x = self.x + move_to = Control.move_to + for offset, line in enumerate(self._lines, self.y): + yield move_to(x, offset) + yield from line + + +class Capture: + """Context manager to capture the result of printing to the console. + See :meth:`~rich.console.Console.capture` for how to use. + + Args: + console (Console): A console instance to capture output. + """ + + def __init__(self, console: "Console") -> None: + self._console = console + self._result: Optional[str] = None + + def __enter__(self) -> "Capture": + self._console.begin_capture() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self._result = self._console.end_capture() + + def get(self) -> str: + """Get the result of the capture.""" + if self._result is None: + raise CaptureError( + "Capture result is not available until context manager exits." + ) + return self._result + + +class ThemeContext: + """A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage.""" + + def __init__(self, console: "Console", theme: Theme, inherit: bool = True) -> None: + self.console = console + self.theme = theme + self.inherit = inherit + + def __enter__(self) -> "ThemeContext": + self.console.push_theme(self.theme) + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self.console.pop_theme() + + +class PagerContext: + """A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.""" + + def __init__( + self, + console: "Console", + pager: Optional[Pager] = None, + styles: bool = False, + links: bool = False, + ) -> None: + self._console = console + self.pager = SystemPager() if pager is None else pager + self.styles = styles + self.links = links + + def __enter__(self) -> "PagerContext": + self._console._enter_buffer() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + if exc_type is None: + with self._console._lock: + buffer: List[Segment] = self._console._buffer[:] + del self._console._buffer[:] + segments: Iterable[Segment] = buffer + if not self.styles: + segments = Segment.strip_styles(segments) + elif not self.links: + segments = Segment.strip_links(segments) + content = self._console._render_buffer(segments) + self.pager.show(content) + self._console._exit_buffer() + + +class ScreenContext: + """A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage.""" + + def __init__( + self, console: "Console", hide_cursor: bool, style: StyleType = "" + ) -> None: + self.console = console + self.hide_cursor = hide_cursor + self.screen = Screen(style=style) + self._changed = False + + def update( + self, *renderables: RenderableType, style: Optional[StyleType] = None + ) -> None: + """Update the screen. + + Args: + renderable (RenderableType, optional): Optional renderable to replace current renderable, + or None for no change. Defaults to None. + style: (Style, optional): Replacement style, or None for no change. Defaults to None. + """ + if renderables: + self.screen.renderable = ( + Group(*renderables) if len(renderables) > 1 else renderables[0] + ) + if style is not None: + self.screen.style = style + self.console.print(self.screen, end="") + + def __enter__(self) -> "ScreenContext": + self._changed = self.console.set_alt_screen(True) + if self._changed and self.hide_cursor: + self.console.show_cursor(False) + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + if self._changed: + self.console.set_alt_screen(False) + if self.hide_cursor: + self.console.show_cursor(True) + + +class Group: + """Takes a group of renderables and returns a renderable object that renders the group. + + Args: + renderables (Iterable[RenderableType]): An iterable of renderable objects. + fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. + """ + + def __init__(self, *renderables: "RenderableType", fit: bool = True) -> None: + self._renderables = renderables + self.fit = fit + self._render: Optional[List[RenderableType]] = None + + @property + def renderables(self) -> List["RenderableType"]: + if self._render is None: + self._render = list(self._renderables) + return self._render + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> "Measurement": + if self.fit: + return measure_renderables(console, options, self.renderables) + else: + return Measurement(options.max_width, options.max_width) + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> RenderResult: + yield from self.renderables + + +def group(fit: bool = True) -> Callable[..., Callable[..., Group]]: + """A decorator that turns an iterable of renderables in to a group. + + Args: + fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True. + """ + + def decorator( + method: Callable[..., Iterable[RenderableType]], + ) -> Callable[..., Group]: + """Convert a method that returns an iterable of renderables in to a Group.""" + + @wraps(method) + def _replace(*args: Any, **kwargs: Any) -> Group: + renderables = method(*args, **kwargs) + return Group(*renderables, fit=fit) + + return _replace + + return decorator + + +def _is_jupyter() -> bool: # pragma: no cover + """Check if we're running in a Jupyter notebook.""" + try: + get_ipython # type: ignore[name-defined] + except NameError: + return False + ipython = get_ipython() # type: ignore[name-defined] + shell = ipython.__class__.__name__ + if ( + "google.colab" in str(ipython.__class__) + or os.getenv("DATABRICKS_RUNTIME_VERSION") + or shell == "ZMQInteractiveShell" + ): + return True # Jupyter notebook or qtconsole + elif shell == "TerminalInteractiveShell": + return False # Terminal running IPython + else: + return False # Other type (?) + + +COLOR_SYSTEMS = { + "standard": ColorSystem.STANDARD, + "256": ColorSystem.EIGHT_BIT, + "truecolor": ColorSystem.TRUECOLOR, + "windows": ColorSystem.WINDOWS, +} + +_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()} + + +@dataclass +class ConsoleThreadLocals(threading.local): + """Thread local values for Console context.""" + + theme_stack: ThemeStack + buffer: List[Segment] = field(default_factory=list) + buffer_index: int = 0 + + +class RenderHook(ABC): + """Provides hooks in to the render process.""" + + @abstractmethod + def process_renderables( + self, renderables: List[ConsoleRenderable] + ) -> List[ConsoleRenderable]: + """Called with a list of objects to render. + + This method can return a new list of renderables, or modify and return the same list. + + Args: + renderables (List[ConsoleRenderable]): A number of renderable objects. + + Returns: + List[ConsoleRenderable]: A replacement list of renderables. + """ + + +_windows_console_features: Optional["WindowsConsoleFeatures"] = None + + +def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover + global _windows_console_features + if _windows_console_features is not None: + return _windows_console_features + from ._windows import get_windows_console_features + + _windows_console_features = get_windows_console_features() + return _windows_console_features + + +def detect_legacy_windows() -> bool: + """Detect legacy Windows.""" + return WINDOWS and not get_windows_console_features().vt + + +class Console: + """A high level console interface. + + Args: + color_system (str, optional): The color system supported by your terminal, + either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect. + force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None. + force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None. + force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None. + soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False. + theme (Theme, optional): An optional style theme object, or ``None`` for default theme. + stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False. + file (IO, optional): A file object where the console should write to. Defaults to stdout. + quiet (bool, Optional): Boolean to suppress all output. Defaults to False. + width (int, optional): The width of the terminal. Leave as default to auto-detect width. + height (int, optional): The height of the terminal. Leave as default to auto-detect height. + style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None. + no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None. + tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8. + record (bool, optional): Boolean to enable recording of terminal output, + required to call :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False. + markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True. + emoji (bool, optional): Enable emoji code. Defaults to True. + emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None. + highlight (bool, optional): Enable automatic highlighting. Defaults to True. + log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True. + log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True. + log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ". + highlighter (HighlighterType, optional): Default highlighter. + legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``. + safe_box (bool, optional): Restrict box options that don't render on legacy Windows. + get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log), + or None for datetime.now. + get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic. + """ + + _environ: Mapping[str, str] = os.environ + + def __init__( + self, + *, + color_system: Optional[ + Literal["auto", "standard", "256", "truecolor", "windows"] + ] = "auto", + force_terminal: Optional[bool] = None, + force_jupyter: Optional[bool] = None, + force_interactive: Optional[bool] = None, + soft_wrap: bool = False, + theme: Optional[Theme] = None, + stderr: bool = False, + file: Optional[IO[str]] = None, + quiet: bool = False, + width: Optional[int] = None, + height: Optional[int] = None, + style: Optional[StyleType] = None, + no_color: Optional[bool] = None, + tab_size: int = 8, + record: bool = False, + markup: bool = True, + emoji: bool = True, + emoji_variant: Optional[EmojiVariant] = None, + highlight: bool = True, + log_time: bool = True, + log_path: bool = True, + log_time_format: Union[str, FormatTimeCallable] = "[%X]", + highlighter: Optional["HighlighterType"] = ReprHighlighter(), + legacy_windows: Optional[bool] = None, + safe_box: bool = True, + get_datetime: Optional[Callable[[], datetime]] = None, + get_time: Optional[Callable[[], float]] = None, + _environ: Optional[Mapping[str, str]] = None, + ): + # Copy of os.environ allows us to replace it for testing + if _environ is not None: + self._environ = _environ + + self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter + if self.is_jupyter: + if width is None: + jupyter_columns = self._environ.get("JUPYTER_COLUMNS") + if jupyter_columns is not None and jupyter_columns.isdigit(): + width = int(jupyter_columns) + else: + width = JUPYTER_DEFAULT_COLUMNS + if height is None: + jupyter_lines = self._environ.get("JUPYTER_LINES") + if jupyter_lines is not None and jupyter_lines.isdigit(): + height = int(jupyter_lines) + else: + height = JUPYTER_DEFAULT_LINES + + self.tab_size = tab_size + self.record = record + self._markup = markup + self._emoji = emoji + self._emoji_variant: Optional[EmojiVariant] = emoji_variant + self._highlight = highlight + self.legacy_windows: bool = ( + (detect_legacy_windows() and not self.is_jupyter) + if legacy_windows is None + else legacy_windows + ) + + if width is None: + columns = self._environ.get("COLUMNS") + if columns is not None and columns.isdigit(): + width = int(columns) - self.legacy_windows + if height is None: + lines = self._environ.get("LINES") + if lines is not None and lines.isdigit(): + height = int(lines) + + self.soft_wrap = soft_wrap + self._width = width + self._height = height + + self._color_system: Optional[ColorSystem] + + self._force_terminal = None + if force_terminal is not None: + self._force_terminal = force_terminal + + self._file = file + self.quiet = quiet + self.stderr = stderr + + if color_system is None: + self._color_system = None + elif color_system == "auto": + self._color_system = self._detect_color_system() + else: + self._color_system = COLOR_SYSTEMS[color_system] + + self._lock = threading.RLock() + self._log_render = LogRender( + show_time=log_time, + show_path=log_path, + time_format=log_time_format, + ) + self.highlighter: HighlighterType = highlighter or _null_highlighter + self.safe_box = safe_box + self.get_datetime = get_datetime or datetime.now + self.get_time = get_time or monotonic + self.style = style + self.no_color = ( + no_color + if no_color is not None + else self._environ.get("NO_COLOR", "") != "" + ) + if force_interactive is None: + tty_interactive = self._environ.get("TTY_INTERACTIVE", None) + if tty_interactive is not None: + if tty_interactive == "0": + force_interactive = False + elif tty_interactive == "1": + force_interactive = True + + self.is_interactive = ( + (self.is_terminal and not self.is_dumb_terminal) + if force_interactive is None + else force_interactive + ) + + self._record_buffer_lock = threading.RLock() + self._thread_locals = ConsoleThreadLocals( + theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme) + ) + self._record_buffer: List[Segment] = [] + self._render_hooks: List[RenderHook] = [] + self._live_stack: List[Live] = [] + self._is_alt_screen = False + + def __repr__(self) -> str: + return f"" + + @property + def file(self) -> IO[str]: + """Get the file object to write to.""" + file = self._file or (sys.stderr if self.stderr else sys.stdout) + file = getattr(file, "rich_proxied_file", file) + if file is None: + file = NULL_FILE + return file + + @file.setter + def file(self, new_file: IO[str]) -> None: + """Set a new file object.""" + self._file = new_file + + @property + def _buffer(self) -> List[Segment]: + """Get a thread local buffer.""" + return self._thread_locals.buffer + + @property + def _buffer_index(self) -> int: + """Get a thread local buffer.""" + return self._thread_locals.buffer_index + + @_buffer_index.setter + def _buffer_index(self, value: int) -> None: + self._thread_locals.buffer_index = value + + @property + def _theme_stack(self) -> ThemeStack: + """Get the thread local theme stack.""" + return self._thread_locals.theme_stack + + def _detect_color_system(self) -> Optional[ColorSystem]: + """Detect color system from env vars.""" + if self.is_jupyter: + return ColorSystem.TRUECOLOR + if not self.is_terminal or self.is_dumb_terminal: + return None + if WINDOWS: # pragma: no cover + if self.legacy_windows: # pragma: no cover + return ColorSystem.WINDOWS + windows_console_features = get_windows_console_features() + return ( + ColorSystem.TRUECOLOR + if windows_console_features.truecolor + else ColorSystem.EIGHT_BIT + ) + else: + color_term = self._environ.get("COLORTERM", "").strip().lower() + if color_term in ("truecolor", "24bit"): + return ColorSystem.TRUECOLOR + term = self._environ.get("TERM", "").strip().lower() + _term_name, _hyphen, colors = term.rpartition("-") + color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD) + return color_system + + def _enter_buffer(self) -> None: + """Enter in to a buffer context, and buffer all output.""" + self._buffer_index += 1 + + def _exit_buffer(self) -> None: + """Leave buffer context, and render content if required.""" + self._buffer_index -= 1 + self._check_buffer() + + def set_live(self, live: "Live") -> bool: + """Set Live instance. Used by Live context manager (no need to call directly). + + Args: + live (Live): Live instance using this Console. + + Returns: + Boolean that indicates if the live is the topmost of the stack. + + Raises: + errors.LiveError: If this Console has a Live context currently active. + """ + with self._lock: + self._live_stack.append(live) + return len(self._live_stack) == 1 + + def clear_live(self) -> None: + """Clear the Live instance. Used by the Live context manager (no need to call directly).""" + with self._lock: + self._live_stack.pop() + + def push_render_hook(self, hook: RenderHook) -> None: + """Add a new render hook to the stack. + + Args: + hook (RenderHook): Render hook instance. + """ + with self._lock: + self._render_hooks.append(hook) + + def pop_render_hook(self) -> None: + """Pop the last renderhook from the stack.""" + with self._lock: + self._render_hooks.pop() + + def __enter__(self) -> "Console": + """Own context manager to enter buffer context.""" + self._enter_buffer() + return self + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + """Exit buffer context.""" + self._exit_buffer() + + def begin_capture(self) -> None: + """Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.""" + self._enter_buffer() + + def end_capture(self) -> str: + """End capture mode and return captured string. + + Returns: + str: Console output. + """ + render_result = self._render_buffer(self._buffer) + del self._buffer[:] + self._exit_buffer() + return render_result + + def push_theme(self, theme: Theme, *, inherit: bool = True) -> None: + """Push a new theme on to the top of the stack, replacing the styles from the previous theme. + Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather + than calling this method directly. + + Args: + theme (Theme): A theme instance. + inherit (bool, optional): Inherit existing styles. Defaults to True. + """ + self._theme_stack.push_theme(theme, inherit=inherit) + + def pop_theme(self) -> None: + """Remove theme from top of stack, restoring previous theme.""" + self._theme_stack.pop_theme() + + def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext: + """Use a different theme for the duration of the context manager. + + Args: + theme (Theme): Theme instance to user. + inherit (bool, optional): Inherit existing console styles. Defaults to True. + + Returns: + ThemeContext: [description] + """ + return ThemeContext(self, theme, inherit) + + @property + def color_system(self) -> Optional[str]: + """Get color system string. + + Returns: + Optional[str]: "standard", "256" or "truecolor". + """ + + if self._color_system is not None: + return _COLOR_SYSTEMS_NAMES[self._color_system] + else: + return None + + @property + def encoding(self) -> str: + """Get the encoding of the console file, e.g. ``"utf-8"``. + + Returns: + str: A standard encoding string. + """ + return (getattr(self.file, "encoding", "utf-8") or "utf-8").lower() + + @property + def is_terminal(self) -> bool: + """Check if the console is writing to a terminal. + + Returns: + bool: True if the console writing to a device capable of + understanding escape sequences, otherwise False. + """ + # If dev has explicitly set this value, return it + if self._force_terminal is not None: + return self._force_terminal + + # Fudge for Idle + if hasattr(sys.stdin, "__module__") and sys.stdin.__module__.startswith( + "idlelib" + ): + # Return False for Idle which claims to be a tty but can't handle ansi codes + return False + + if self.is_jupyter: + # return False for Jupyter, which may have FORCE_COLOR set + return False + + environ = self._environ + + tty_compatible = environ.get("TTY_COMPATIBLE", "") + # 0 indicates device is not tty compatible + if tty_compatible == "0": + return False + # 1 indicates device is tty compatible + if tty_compatible == "1": + return True + + # https://force-color.org/ + force_color = environ.get("FORCE_COLOR") + if force_color is not None: + return force_color != "" + + # Any other value defaults to auto detect + isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None) + try: + return False if isatty is None else isatty() + except ValueError: + # in some situation (at the end of a pytest run for example) isatty() can raise + # ValueError: I/O operation on closed file + # return False because we aren't in a terminal anymore + return False + + @property + def is_dumb_terminal(self) -> bool: + """Detect dumb terminal. + + Returns: + bool: True if writing to a dumb terminal, otherwise False. + + """ + _term = self._environ.get("TERM", "") + is_dumb = _term.lower() in ("dumb", "unknown") + return self.is_terminal and is_dumb + + @property + def options(self) -> ConsoleOptions: + """Get default console options.""" + size = self.size + return ConsoleOptions( + max_height=size.height, + size=size, + legacy_windows=self.legacy_windows, + min_width=1, + max_width=size.width, + encoding=self.encoding, + is_terminal=self.is_terminal, + ) + + @property + def size(self) -> ConsoleDimensions: + """Get the size of the console. + + Returns: + ConsoleDimensions: A named tuple containing the dimensions. + """ + + if self._width is not None and self._height is not None: + return ConsoleDimensions(self._width - self.legacy_windows, self._height) + + if self.is_dumb_terminal: + return ConsoleDimensions(80, 25) + + width: Optional[int] = None + height: Optional[int] = None + + streams = _STD_STREAMS_OUTPUT if WINDOWS else _STD_STREAMS + for file_descriptor in streams: + try: + width, height = os.get_terminal_size(file_descriptor) + except (AttributeError, ValueError, OSError): # Probably not a terminal + pass + else: + break + + columns = self._environ.get("COLUMNS") + if columns is not None and columns.isdigit(): + width = int(columns) + lines = self._environ.get("LINES") + if lines is not None and lines.isdigit(): + height = int(lines) + + # get_terminal_size can report 0, 0 if run from pseudo-terminal + width = width or 80 + height = height or 25 + return ConsoleDimensions( + width - self.legacy_windows if self._width is None else self._width, + height if self._height is None else self._height, + ) + + @size.setter + def size(self, new_size: Tuple[int, int]) -> None: + """Set a new size for the terminal. + + Args: + new_size (Tuple[int, int]): New width and height. + """ + width, height = new_size + self._width = width + self._height = height + + @property + def width(self) -> int: + """Get the width of the console. + + Returns: + int: The width (in characters) of the console. + """ + return self.size.width + + @width.setter + def width(self, width: int) -> None: + """Set width. + + Args: + width (int): New width. + """ + self._width = width + + @property + def height(self) -> int: + """Get the height of the console. + + Returns: + int: The height (in lines) of the console. + """ + return self.size.height + + @height.setter + def height(self, height: int) -> None: + """Set height. + + Args: + height (int): new height. + """ + self._height = height + + def bell(self) -> None: + """Play a 'bell' sound (if supported by the terminal).""" + self.control(Control.bell()) + + def capture(self) -> Capture: + """A context manager to *capture* the result of print() or log() in a string, + rather than writing it to the console. + + Example: + >>> from rich.console import Console + >>> console = Console() + >>> with console.capture() as capture: + ... console.print("[bold magenta]Hello World[/]") + >>> print(capture.get()) + + Returns: + Capture: Context manager with disables writing to the terminal. + """ + capture = Capture(self) + return capture + + def pager( + self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False + ) -> PagerContext: + """A context manager to display anything printed within a "pager". The pager application + is defined by the system and will typically support at least pressing a key to scroll. + + Args: + pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None. + styles (bool, optional): Show styles in pager. Defaults to False. + links (bool, optional): Show links in pager. Defaults to False. + + Example: + >>> from rich.console import Console + >>> from rich.__main__ import make_test_card + >>> console = Console() + >>> with console.pager(): + console.print(make_test_card()) + + Returns: + PagerContext: A context manager. + """ + return PagerContext(self, pager=pager, styles=styles, links=links) + + def line(self, count: int = 1) -> None: + """Write new line(s). + + Args: + count (int, optional): Number of new lines. Defaults to 1. + """ + + assert count >= 0, "count must be >= 0" + self.print(NewLine(count)) + + def clear(self, home: bool = True) -> None: + """Clear the screen. + + Args: + home (bool, optional): Also move the cursor to 'home' position. Defaults to True. + """ + if home: + self.control(Control.clear(), Control.home()) + else: + self.control(Control.clear()) + + def status( + self, + status: RenderableType, + *, + spinner: str = "dots", + spinner_style: StyleType = "status.spinner", + speed: float = 1.0, + refresh_per_second: float = 12.5, + ) -> "Status": + """Display a status and spinner. + + Args: + status (RenderableType): A status renderable (str or Text typically). + spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots". + spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner". + speed (float, optional): Speed factor for spinner animation. Defaults to 1.0. + refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5. + + Returns: + Status: A Status object that may be used as a context manager. + """ + from .status import Status + + status_renderable = Status( + status, + console=self, + spinner=spinner, + spinner_style=spinner_style, + speed=speed, + refresh_per_second=refresh_per_second, + ) + return status_renderable + + def show_cursor(self, show: bool = True) -> bool: + """Show or hide the cursor. + + Args: + show (bool, optional): Set visibility of the cursor. + """ + if self.is_terminal: + self.control(Control.show_cursor(show)) + return True + return False + + def set_alt_screen(self, enable: bool = True) -> bool: + """Enables alternative screen mode. + + Note, if you enable this mode, you should ensure that is disabled before + the application exits. See :meth:`~rich.Console.screen` for a context manager + that handles this for you. + + Args: + enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True. + + Returns: + bool: True if the control codes were written. + + """ + changed = False + if self.is_terminal and not self.legacy_windows: + self.control(Control.alt_screen(enable)) + changed = True + self._is_alt_screen = enable + return changed + + @property + def is_alt_screen(self) -> bool: + """Check if the alt screen was enabled. + + Returns: + bool: True if the alt screen was enabled, otherwise False. + """ + return self._is_alt_screen + + def set_window_title(self, title: str) -> bool: + """Set the title of the console terminal window. + + Warning: There is no means within Rich of "resetting" the window title to its + previous value, meaning the title you set will persist even after your application + exits. + + ``fish`` shell resets the window title before and after each command by default, + negating this issue. Windows Terminal and command prompt will also reset the title for you. + Most other shells and terminals, however, do not do this. + + Some terminals may require configuration changes before you can set the title. + Some terminals may not support setting the title at all. + + Other software (including the terminal itself, the shell, custom prompts, plugins, etc.) + may also set the terminal window title. This could result in whatever value you write + using this method being overwritten. + + Args: + title (str): The new title of the terminal window. + + Returns: + bool: True if the control code to change the terminal title was + written, otherwise False. Note that a return value of True + does not guarantee that the window title has actually changed, + since the feature may be unsupported/disabled in some terminals. + """ + if self.is_terminal: + self.control(Control.title(title)) + return True + return False + + def screen( + self, hide_cursor: bool = True, style: Optional[StyleType] = None + ) -> "ScreenContext": + """Context manager to enable and disable 'alternative screen' mode. + + Args: + hide_cursor (bool, optional): Also hide the cursor. Defaults to False. + style (Style, optional): Optional style for screen. Defaults to None. + + Returns: + ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit. + """ + return ScreenContext(self, hide_cursor=hide_cursor, style=style or "") + + def measure( + self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None + ) -> Measurement: + """Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains + information regarding the number of characters required to print the renderable. + + Args: + renderable (RenderableType): Any renderable or string. + options (Optional[ConsoleOptions], optional): Options to use when measuring, or None + to use default options. Defaults to None. + + Returns: + Measurement: A measurement of the renderable. + """ + measurement = Measurement.get(self, options or self.options, renderable) + return measurement + + def render( + self, renderable: RenderableType, options: Optional[ConsoleOptions] = None + ) -> Iterable[Segment]: + """Render an object in to an iterable of `Segment` instances. + + This method contains the logic for rendering objects with the console protocol. + You are unlikely to need to use it directly, unless you are extending the library. + + Args: + renderable (RenderableType): An object supporting the console protocol, or + an object that may be converted to a string. + options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None. + + Returns: + Iterable[Segment]: An iterable of segments that may be rendered. + """ + + _options = options or self.options + if _options.max_width < 1: + # No space to render anything. This prevents potential recursion errors. + return + render_iterable: RenderResult + + renderable = rich_cast(renderable) + if hasattr(renderable, "__rich_console__") and not isclass(renderable): + render_iterable = renderable.__rich_console__(self, _options) + elif isinstance(renderable, str): + text_renderable = self.render_str( + renderable, highlight=_options.highlight, markup=_options.markup + ) + render_iterable = text_renderable.__rich_console__(self, _options) + else: + raise errors.NotRenderableError( + f"Unable to render {renderable!r}; " + "A str, Segment or object with __rich_console__ method is required" + ) + + try: + iter_render = iter(render_iterable) + except TypeError: + raise errors.NotRenderableError( + f"object {render_iterable!r} is not renderable" + ) + _Segment = Segment + _options = _options.reset_height() + for render_output in iter_render: + if isinstance(render_output, _Segment): + yield render_output + else: + yield from self.render(render_output, _options) + + def render_lines( + self, + renderable: RenderableType, + options: Optional[ConsoleOptions] = None, + *, + style: Optional[Style] = None, + pad: bool = True, + new_lines: bool = False, + ) -> List[List[Segment]]: + """Render objects in to a list of lines. + + The output of render_lines is useful when further formatting of rendered console text + is required, such as the Panel class which draws a border around any renderable object. + + Args: + renderable (RenderableType): Any object renderable in the console. + options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``. + style (Style, optional): Optional style to apply to renderables. Defaults to ``None``. + pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``. + new_lines (bool, optional): Include "\n" characters at end of lines. + + Returns: + List[List[Segment]]: A list of lines, where a line is a list of Segment objects. + """ + with self._lock: + render_options = options or self.options + _rendered = self.render(renderable, render_options) + if style: + _rendered = Segment.apply_style(_rendered, style) + + render_height = render_options.height + if render_height is not None: + render_height = max(0, render_height) + + lines = list( + islice( + Segment.split_and_crop_lines( + _rendered, + render_options.max_width, + include_new_lines=new_lines, + pad=pad, + style=style, + ), + None, + render_height, + ) + ) + if render_options.height is not None: + extra_lines = render_options.height - len(lines) + if extra_lines > 0: + pad_line = [ + ( + [ + Segment(" " * render_options.max_width, style), + Segment("\n"), + ] + if new_lines + else [Segment(" " * render_options.max_width, style)] + ) + ] + lines.extend(pad_line * extra_lines) + + return lines + + def render_str( + self, + text: str, + *, + style: Union[str, Style] = "", + justify: Optional[JustifyMethod] = None, + overflow: Optional[OverflowMethod] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + highlighter: Optional[HighlighterType] = None, + ) -> "Text": + """Convert a string to a Text instance. This is called automatically if + you print or log a string. + + Args: + text (str): Text to render. + style (Union[str, Style], optional): Style to apply to rendered text. + justify (str, optional): Justify method: "default", "left", "center", "full", or "right". Defaults to ``None``. + overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to ``None``. + emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default. + markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default. + highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default. + highlighter (HighlighterType, optional): Optional highlighter to apply. + Returns: + ConsoleRenderable: Renderable object. + + """ + emoji_enabled = emoji or (emoji is None and self._emoji) + markup_enabled = markup or (markup is None and self._markup) + highlight_enabled = highlight or (highlight is None and self._highlight) + + if markup_enabled: + rich_text = render_markup( + text, + style=style, + emoji=emoji_enabled, + emoji_variant=self._emoji_variant, + ) + rich_text.justify = justify + rich_text.overflow = overflow + else: + rich_text = Text( + ( + _emoji_replace(text, default_variant=self._emoji_variant) + if emoji_enabled + else text + ), + justify=justify, + overflow=overflow, + style=style, + ) + + _highlighter = (highlighter or self.highlighter) if highlight_enabled else None + if _highlighter is not None: + highlight_text = _highlighter(str(rich_text)) + highlight_text.copy_styles(rich_text) + return highlight_text + + return rich_text + + def get_style( + self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None + ) -> Style: + """Get a Style instance by its theme name or parse a definition. + + Args: + name (str): The name of a style or a style definition. + + Returns: + Style: A Style object. + + Raises: + MissingStyle: If no style could be parsed from name. + + """ + if isinstance(name, Style): + return name + + try: + style = self._theme_stack.get(name) + if style is None: + style = Style.parse(name) + return style.copy() if style.link else style + except errors.StyleSyntaxError as error: + if default is not None: + return self.get_style(default) + raise errors.MissingStyle( + f"Failed to get style {name!r}; {error}" + ) from None + + def _collect_renderables( + self, + objects: Iterable[Any], + sep: str, + end: str, + *, + justify: Optional[JustifyMethod] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + ) -> List[ConsoleRenderable]: + """Combine a number of renderables and text into one renderable. + + Args: + objects (Iterable[Any]): Anything that Rich can render. + sep (str): String to write between print data. + end (str): String to write at end of print data. + justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``. + emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. + markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. + highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. + + Returns: + List[ConsoleRenderable]: A list of things to render. + """ + renderables: List[ConsoleRenderable] = [] + _append = renderables.append + text: List[Text] = [] + append_text = text.append + + append = _append + if justify in ("left", "center", "right"): + + def align_append(renderable: RenderableType) -> None: + _append(Align(renderable, cast(AlignMethod, justify))) + + append = align_append + + _highlighter: HighlighterType = _null_highlighter + if highlight or (highlight is None and self._highlight): + _highlighter = self.highlighter + + def check_text() -> None: + if text: + sep_text = Text(sep, justify=justify, end=end) + append(sep_text.join(text)) + text.clear() + + for renderable in objects: + renderable = rich_cast(renderable) + if isinstance(renderable, str): + append_text( + self.render_str( + renderable, + emoji=emoji, + markup=markup, + highlight=highlight, + highlighter=_highlighter, + ) + ) + elif isinstance(renderable, Text): + append_text(renderable) + elif isinstance(renderable, ConsoleRenderable): + check_text() + append(renderable) + elif is_expandable(renderable): + check_text() + append(Pretty(renderable, highlighter=_highlighter)) + else: + append_text(_highlighter(str(renderable))) + + check_text() + + if self.style is not None: + style = self.get_style(self.style) + renderables = [Styled(renderable, style) for renderable in renderables] + + return renderables + + def rule( + self, + title: TextType = "", + *, + characters: str = "─", + style: Union[str, Style] = "rule.line", + align: AlignMethod = "center", + ) -> None: + """Draw a line with optional centered title. + + Args: + title (str, optional): Text to render over the rule. Defaults to "". + characters (str, optional): Character(s) to form the line. Defaults to "─". + style (str, optional): Style of line. Defaults to "rule.line". + align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center". + """ + from .rule import Rule + + rule = Rule(title=title, characters=characters, style=style, align=align) + self.print(rule) + + def control(self, *control: Control) -> None: + """Insert non-printing control codes. + + Args: + control_codes (str): Control codes, such as those that may move the cursor. + """ + if not self.is_dumb_terminal: + with self: + self._buffer.extend(_control.segment for _control in control) + + def out( + self, + *objects: Any, + sep: str = " ", + end: str = "\n", + style: Optional[Union[str, Style]] = None, + highlight: Optional[bool] = None, + ) -> None: + """Output to the terminal. This is a low-level way of writing to the terminal which unlike + :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will + optionally apply highlighting and a basic style. + + Args: + sep (str, optional): String to write between print data. Defaults to " ". + end (str, optional): String to write at end of print data. Defaults to "\\\\n". + style (Union[str, Style], optional): A style to apply to output. Defaults to None. + highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use + console default. Defaults to ``None``. + """ + raw_output: str = sep.join(str(_object) for _object in objects) + self.print( + raw_output, + style=style, + highlight=highlight, + emoji=False, + markup=False, + no_wrap=True, + overflow="ignore", + crop=False, + end=end, + ) + + def print( + self, + *objects: Any, + sep: str = " ", + end: str = "\n", + style: Optional[Union[str, Style]] = None, + justify: Optional[JustifyMethod] = None, + overflow: Optional[OverflowMethod] = None, + no_wrap: Optional[bool] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + width: Optional[int] = None, + height: Optional[int] = None, + crop: bool = True, + soft_wrap: Optional[bool] = None, + new_line_start: bool = False, + ) -> None: + """Print to the console. + + Args: + objects (positional args): Objects to log to the terminal. + sep (str, optional): String to write between print data. Defaults to " ". + end (str, optional): String to write at end of print data. Defaults to "\\\\n". + style (Union[str, Style], optional): A style to apply to output. Defaults to None. + justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``. + overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None. + no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None. + emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``. + markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``. + highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``. + width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``. + crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True. + soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for + Console default. Defaults to ``None``. + new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``. + """ + if not objects: + objects = (NewLine(),) + + if soft_wrap is None: + soft_wrap = self.soft_wrap + if soft_wrap: + if no_wrap is None: + no_wrap = True + if overflow is None: + overflow = "ignore" + crop = False + render_hooks = self._render_hooks[:] + with self: + renderables = self._collect_renderables( + objects, + sep, + end, + justify=justify, + emoji=emoji, + markup=markup, + highlight=highlight, + ) + for hook in render_hooks: + renderables = hook.process_renderables(renderables) + render_options = self.options.update( + justify=justify, + overflow=overflow, + width=min(width, self.width) if width is not None else NO_CHANGE, + height=height, + no_wrap=no_wrap, + markup=markup, + highlight=highlight, + ) + + new_segments: List[Segment] = [] + extend = new_segments.extend + render = self.render + if style is None: + for renderable in renderables: + extend(render(renderable, render_options)) + else: + for renderable in renderables: + extend( + Segment.apply_style( + render(renderable, render_options), self.get_style(style) + ) + ) + if new_line_start: + if ( + len("".join(segment.text for segment in new_segments).splitlines()) + > 1 + ): + new_segments.insert(0, Segment.line()) + if crop: + buffer_extend = self._buffer.extend + for line in Segment.split_and_crop_lines( + new_segments, self.width, pad=False + ): + buffer_extend(line) + else: + self._buffer.extend(new_segments) + + def print_json( + self, + json: Optional[str] = None, + *, + data: Any = None, + indent: Union[None, int, str] = 2, + highlight: bool = True, + skip_keys: bool = False, + ensure_ascii: bool = False, + check_circular: bool = True, + allow_nan: bool = True, + default: Optional[Callable[[Any], Any]] = None, + sort_keys: bool = False, + ) -> None: + """Pretty prints JSON. Output will be valid JSON. + + Args: + json (Optional[str]): A string containing JSON. + data (Any): If json is not supplied, then encode this data. + indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2. + highlight (bool, optional): Enable highlighting of output: Defaults to True. + skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False. + ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False. + check_circular (bool, optional): Check for circular references. Defaults to True. + allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True. + default (Callable, optional): A callable that converts values that can not be encoded + in to something that can be JSON encoded. Defaults to None. + sort_keys (bool, optional): Sort dictionary keys. Defaults to False. + """ + from rich.json import JSON + + if json is None: + json_renderable = JSON.from_data( + data, + indent=indent, + highlight=highlight, + skip_keys=skip_keys, + ensure_ascii=ensure_ascii, + check_circular=check_circular, + allow_nan=allow_nan, + default=default, + sort_keys=sort_keys, + ) + else: + if not isinstance(json, str): + raise TypeError( + f"json must be str. Did you mean print_json(data={json!r}) ?" + ) + json_renderable = JSON( + json, + indent=indent, + highlight=highlight, + skip_keys=skip_keys, + ensure_ascii=ensure_ascii, + check_circular=check_circular, + allow_nan=allow_nan, + default=default, + sort_keys=sort_keys, + ) + self.print(json_renderable, soft_wrap=True) + + def update_screen( + self, + renderable: RenderableType, + *, + region: Optional[Region] = None, + options: Optional[ConsoleOptions] = None, + ) -> None: + """Update the screen at a given offset. + + Args: + renderable (RenderableType): A Rich renderable. + region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None. + x (int, optional): x offset. Defaults to 0. + y (int, optional): y offset. Defaults to 0. + + Raises: + errors.NoAltScreen: If the Console isn't in alt screen mode. + + """ + if not self.is_alt_screen: + raise errors.NoAltScreen("Alt screen must be enabled to call update_screen") + render_options = options or self.options + if region is None: + x = y = 0 + render_options = render_options.update_dimensions( + render_options.max_width, render_options.height or self.height + ) + else: + x, y, width, height = region + render_options = render_options.update_dimensions(width, height) + + lines = self.render_lines(renderable, options=render_options) + self.update_screen_lines(lines, x, y) + + def update_screen_lines( + self, lines: List[List[Segment]], x: int = 0, y: int = 0 + ) -> None: + """Update lines of the screen at a given offset. + + Args: + lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`). + x (int, optional): x offset (column no). Defaults to 0. + y (int, optional): y offset (column no). Defaults to 0. + + Raises: + errors.NoAltScreen: If the Console isn't in alt screen mode. + """ + if not self.is_alt_screen: + raise errors.NoAltScreen("Alt screen must be enabled to call update_screen") + screen_update = ScreenUpdate(lines, x, y) + segments = self.render(screen_update) + self._buffer.extend(segments) + self._check_buffer() + + def print_exception( + self, + *, + width: Optional[int] = 100, + extra_lines: int = 3, + theme: Optional[str] = None, + word_wrap: bool = False, + show_locals: bool = False, + suppress: Iterable[Union[str, ModuleType]] = (), + max_frames: int = 100, + ) -> None: + """Prints a rich render of the last exception and traceback. + + Args: + width (Optional[int], optional): Number of characters used to render code. Defaults to 100. + extra_lines (int, optional): Additional lines of code to render. Defaults to 3. + theme (str, optional): Override pygments theme used in traceback + word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False. + show_locals (bool, optional): Enable display of local variables. Defaults to False. + suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback. + max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100. + """ + from .traceback import Traceback + + traceback = Traceback( + width=width, + extra_lines=extra_lines, + theme=theme, + word_wrap=word_wrap, + show_locals=show_locals, + suppress=suppress, + max_frames=max_frames, + ) + self.print(traceback) + + @staticmethod + def _caller_frame_info( + offset: int, + currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe, + ) -> Tuple[str, int, Dict[str, Any]]: + """Get caller frame information. + + Args: + offset (int): the caller offset within the current frame stack. + currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to + retrieve the current frame. Defaults to ``inspect.currentframe``. + + Returns: + Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and + the dictionary of local variables associated with the caller frame. + + Raises: + RuntimeError: If the stack offset is invalid. + """ + # Ignore the frame of this local helper + offset += 1 + + frame = currentframe() + if frame is not None: + # Use the faster currentframe where implemented + while offset and frame is not None: + frame = frame.f_back + offset -= 1 + assert frame is not None + return frame.f_code.co_filename, frame.f_lineno, frame.f_locals + else: + # Fallback to the slower stack + frame_info = inspect.stack()[offset] + return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals + + def log( + self, + *objects: Any, + sep: str = " ", + end: str = "\n", + style: Optional[Union[str, Style]] = None, + justify: Optional[JustifyMethod] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + log_locals: bool = False, + _stack_offset: int = 1, + ) -> None: + """Log rich content to the terminal. + + Args: + objects (positional args): Objects to log to the terminal. + sep (str, optional): String to write between print data. Defaults to " ". + end (str, optional): String to write at end of print data. Defaults to "\\\\n". + style (Union[str, Style], optional): A style to apply to output. Defaults to None. + justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``. + emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None. + markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None. + highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None. + log_locals (bool, optional): Boolean to enable logging of locals where ``log()`` + was called. Defaults to False. + _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1. + """ + if not objects: + objects = (NewLine(),) + + render_hooks = self._render_hooks[:] + + with self: + renderables = self._collect_renderables( + objects, + sep, + end, + justify=justify, + emoji=emoji, + markup=markup, + highlight=highlight, + ) + if style is not None: + renderables = [Styled(renderable, style) for renderable in renderables] + + filename, line_no, locals = self._caller_frame_info(_stack_offset) + link_path = None if filename.startswith("<") else os.path.abspath(filename) + path = filename.rpartition(os.sep)[-1] + if log_locals: + locals_map = { + key: value + for key, value in locals.items() + if not key.startswith("__") + } + renderables.append(render_scope(locals_map, title="[i]locals")) + + renderables = [ + self._log_render( + self, + renderables, + log_time=self.get_datetime(), + path=path, + line_no=line_no, + link_path=link_path, + ) + ] + for hook in render_hooks: + renderables = hook.process_renderables(renderables) + new_segments: List[Segment] = [] + extend = new_segments.extend + render = self.render + render_options = self.options + for renderable in renderables: + extend(render(renderable, render_options)) + buffer_extend = self._buffer.extend + for line in Segment.split_and_crop_lines( + new_segments, self.width, pad=False + ): + buffer_extend(line) + + def on_broken_pipe(self) -> None: + """This function is called when a `BrokenPipeError` is raised. + + This can occur when piping Textual output in Linux and macOS. + The default implementation is to exit the app, but you could implement + this method in a subclass to change the behavior. + + See https://docs.python.org/3/library/signal.html#note-on-sigpipe for details. + """ + self.quiet = True + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, sys.stdout.fileno()) + raise SystemExit(1) + + def _check_buffer(self) -> None: + """Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False) + Rendering is supported on Windows, Unix and Jupyter environments. For + legacy Windows consoles, the win32 API is called directly. + This method will also record what it renders if recording is enabled via Console.record. + """ + if self.quiet: + del self._buffer[:] + return + + try: + self._write_buffer() + except BrokenPipeError: + self.on_broken_pipe() + + def _write_buffer(self) -> None: + """Write the buffer to the output file.""" + + with self._lock: + if self.record and not self._buffer_index: + with self._record_buffer_lock: + self._record_buffer.extend(self._buffer[:]) + + if self._buffer_index == 0: + if self.is_jupyter: # pragma: no cover + from .jupyter import display + + display(self._buffer, self._render_buffer(self._buffer[:])) + del self._buffer[:] + else: + if WINDOWS: + use_legacy_windows_render = False + if self.legacy_windows: + fileno = get_fileno(self.file) + if fileno is not None: + use_legacy_windows_render = ( + fileno in _STD_STREAMS_OUTPUT + ) + + if use_legacy_windows_render: + from rich._win32_console import LegacyWindowsTerm + from rich._windows_renderer import legacy_windows_render + + buffer = self._buffer[:] + if self.no_color and self._color_system: + buffer = list(Segment.remove_color(buffer)) + + legacy_windows_render(buffer, LegacyWindowsTerm(self.file)) + else: + # Either a non-std stream on legacy Windows, or modern Windows. + text = self._render_buffer(self._buffer[:]) + # https://bugs.python.org/issue37871 + # https://github.com/python/cpython/issues/82052 + # We need to avoid writing more than 32Kb in a single write, due to the above bug + write = self.file.write + # Worse case scenario, every character is 4 bytes of utf-8 + MAX_WRITE = 32 * 1024 // 4 + try: + if len(text) <= MAX_WRITE: + write(text) + else: + batch: List[str] = [] + batch_append = batch.append + size = 0 + for line in text.splitlines(True): + if size + len(line) > MAX_WRITE and batch: + write("".join(batch)) + batch.clear() + size = 0 + batch_append(line) + size += len(line) + if batch: + write("".join(batch)) + batch.clear() + except UnicodeEncodeError as error: + error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***" + raise + else: + text = self._render_buffer(self._buffer[:]) + try: + self.file.write(text) + except UnicodeEncodeError as error: + error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***" + raise + + self.file.flush() + del self._buffer[:] + + def _render_buffer(self, buffer: Iterable[Segment]) -> str: + """Render buffered output, and clear buffer.""" + output: List[str] = [] + append = output.append + color_system = self._color_system + legacy_windows = self.legacy_windows + not_terminal = not self.is_terminal + if self.no_color and color_system: + buffer = Segment.remove_color(buffer) + for text, style, control in buffer: + if style: + append( + style.render( + text, + color_system=color_system, + legacy_windows=legacy_windows, + ) + ) + elif not (not_terminal and control): + append(text) + + rendered = "".join(output) + return rendered + + def input( + self, + prompt: TextType = "", + *, + markup: bool = True, + emoji: bool = True, + password: bool = False, + stream: Optional[TextIO] = None, + ) -> str: + """Displays a prompt and waits for input from the user. The prompt may contain color / style. + + It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded. + + Args: + prompt (Union[str, Text]): Text to render in the prompt. + markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True. + emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True. + password: (bool, optional): Hide typed text. Defaults to False. + stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None. + + Returns: + str: Text read from stdin. + """ + if prompt: + self.print(prompt, markup=markup, emoji=emoji, end="") + if password: + result = getpass("", stream=stream) + else: + if stream: + result = stream.readline() + else: + result = input() + return result + + def export_text(self, *, clear: bool = True, styles: bool = False) -> str: + """Generate text from console contents (requires record=True argument in constructor). + + Args: + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. + styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text. + Defaults to ``False``. + + Returns: + str: String containing console contents. + + """ + assert ( + self.record + ), "To export console contents set record=True in the constructor or instance" + + with self._record_buffer_lock: + if styles: + text = "".join( + (style.render(text) if style else text) + for text, style, _ in self._record_buffer + ) + else: + text = "".join( + segment.text + for segment in self._record_buffer + if not segment.control + ) + if clear: + del self._record_buffer[:] + return text + + def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None: + """Generate text from console and save to a given location (requires record=True argument in constructor). + + Args: + path (str): Path to write text files. + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. + styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text. + Defaults to ``False``. + + """ + text = self.export_text(clear=clear, styles=styles) + with open(path, "w", encoding="utf-8") as write_file: + write_file.write(text) + + def export_html( + self, + *, + theme: Optional[TerminalTheme] = None, + clear: bool = True, + code_format: Optional[str] = None, + inline_styles: bool = False, + ) -> str: + """Generate HTML from console contents (requires record=True argument in constructor). + + Args: + theme (TerminalTheme, optional): TerminalTheme object containing console colors. + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. + code_format (str, optional): Format string to render HTML. In addition to '{foreground}', + '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``. + inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files + larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag. + Defaults to False. + + Returns: + str: String containing console contents as HTML. + """ + assert ( + self.record + ), "To export console contents set record=True in the constructor or instance" + fragments: List[str] = [] + append = fragments.append + _theme = theme or DEFAULT_TERMINAL_THEME + stylesheet = "" + + render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format + + with self._record_buffer_lock: + if inline_styles: + for text, style, _ in Segment.filter_control( + Segment.simplify(self._record_buffer) + ): + text = escape(text) + if style: + rule = style.get_html_style(_theme) + if style.link: + text = f'{text}' + text = f'{text}' if rule else text + append(text) + else: + styles: Dict[str, int] = {} + for text, style, _ in Segment.filter_control( + Segment.simplify(self._record_buffer) + ): + text = escape(text) + if style: + rule = style.get_html_style(_theme) + style_number = styles.setdefault(rule, len(styles) + 1) + if style.link: + text = f'{text}' + else: + text = f'{text}' + append(text) + stylesheet_rules: List[str] = [] + stylesheet_append = stylesheet_rules.append + for style_rule, style_number in styles.items(): + if style_rule: + stylesheet_append(f".r{style_number} {{{style_rule}}}") + stylesheet = "\n".join(stylesheet_rules) + + rendered_code = render_code_format.format( + code="".join(fragments), + stylesheet=stylesheet, + foreground=_theme.foreground_color.hex, + background=_theme.background_color.hex, + ) + if clear: + del self._record_buffer[:] + return rendered_code + + def save_html( + self, + path: str, + *, + theme: Optional[TerminalTheme] = None, + clear: bool = True, + code_format: str = CONSOLE_HTML_FORMAT, + inline_styles: bool = False, + ) -> None: + """Generate HTML from console contents and write to a file (requires record=True argument in constructor). + + Args: + path (str): Path to write html file. + theme (TerminalTheme, optional): TerminalTheme object containing console colors. + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``. + code_format (str, optional): Format string to render HTML. In addition to '{foreground}', + '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``. + inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files + larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag. + Defaults to False. + + """ + html = self.export_html( + theme=theme, + clear=clear, + code_format=code_format, + inline_styles=inline_styles, + ) + with open(path, "w", encoding="utf-8") as write_file: + write_file.write(html) + + def export_svg( + self, + *, + title: str = "Rich", + theme: Optional[TerminalTheme] = None, + clear: bool = True, + code_format: str = CONSOLE_SVG_FORMAT, + font_aspect_ratio: float = 0.61, + unique_id: Optional[str] = None, + ) -> str: + """ + Generate an SVG from the console contents (requires record=True in Console constructor). + + Args: + title (str, optional): The title of the tab in the output image + theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True`` + code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables + into the string in order to form the final SVG output. The default template used and the variables + injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable. + font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format`` + string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font). + If you aren't specifying a different font inside ``code_format``, you probably don't need this. + unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node + ids). If not set, this defaults to a computed value based on the recorded content. + """ + + from rich.cells import cell_len + + style_cache: Dict[Style, str] = {} + + def get_svg_style(style: Style) -> str: + """Convert a Style to CSS rules for SVG.""" + if style in style_cache: + return style_cache[style] + css_rules = [] + color = ( + _theme.foreground_color + if (style.color is None or style.color.is_default) + else style.color.get_truecolor(_theme) + ) + bgcolor = ( + _theme.background_color + if (style.bgcolor is None or style.bgcolor.is_default) + else style.bgcolor.get_truecolor(_theme) + ) + if style.reverse: + color, bgcolor = bgcolor, color + if style.dim: + color = blend_rgb(color, bgcolor, 0.4) + css_rules.append(f"fill: {color.hex}") + if style.bold: + css_rules.append("font-weight: bold") + if style.italic: + css_rules.append("font-style: italic;") + if style.underline: + css_rules.append("text-decoration: underline;") + if style.strike: + css_rules.append("text-decoration: line-through;") + + css = ";".join(css_rules) + style_cache[style] = css + return css + + _theme = theme or SVG_EXPORT_THEME + + width = self.width + char_height = 20 + char_width = char_height * font_aspect_ratio + line_height = char_height * 1.22 + + margin_top = 1 + margin_right = 1 + margin_bottom = 1 + margin_left = 1 + + padding_top = 40 + padding_right = 8 + padding_bottom = 8 + padding_left = 8 + + padding_width = padding_left + padding_right + padding_height = padding_top + padding_bottom + margin_width = margin_left + margin_right + margin_height = margin_top + margin_bottom + + text_backgrounds: List[str] = [] + text_group: List[str] = [] + classes: Dict[str, int] = {} + style_no = 1 + + def escape_text(text: str) -> str: + """HTML escape text and replace spaces with nbsp.""" + return escape(text).replace(" ", " ") + + def make_tag( + name: str, content: Optional[str] = None, **attribs: object + ) -> str: + """Make a tag from name, content, and attributes.""" + + def stringify(value: object) -> str: + if isinstance(value, (float)): + return format(value, "g") + return str(value) + + tag_attribs = " ".join( + f'{k.lstrip("_").replace("_", "-")}="{stringify(v)}"' + for k, v in attribs.items() + ) + return ( + f"<{name} {tag_attribs}>{content}" + if content + else f"<{name} {tag_attribs}/>" + ) + + with self._record_buffer_lock: + segments = list(Segment.filter_control(self._record_buffer)) + if clear: + self._record_buffer.clear() + + if unique_id is None: + unique_id = "terminal-" + str( + zlib.adler32( + ("".join(repr(segment) for segment in segments)).encode( + "utf-8", + "ignore", + ) + + title.encode("utf-8", "ignore") + ) + ) + y = 0 + for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)): + x = 0 + for text, style, _control in line: + style = style or Style() + rules = get_svg_style(style) + if rules not in classes: + classes[rules] = style_no + style_no += 1 + class_name = f"r{classes[rules]}" + + if style.reverse: + has_background = True + background = ( + _theme.foreground_color.hex + if style.color is None + else style.color.get_truecolor(_theme).hex + ) + else: + bgcolor = style.bgcolor + has_background = bgcolor is not None and not bgcolor.is_default + background = ( + _theme.background_color.hex + if style.bgcolor is None + else style.bgcolor.get_truecolor(_theme).hex + ) + + text_length = cell_len(text) + if has_background: + text_backgrounds.append( + make_tag( + "rect", + fill=background, + x=x * char_width, + y=y * line_height + 1.5, + width=char_width * text_length, + height=line_height + 0.25, + shape_rendering="crispEdges", + ) + ) + + if text != " " * len(text): + text_group.append( + make_tag( + "text", + escape_text(text), + _class=f"{unique_id}-{class_name}", + x=x * char_width, + y=y * line_height + char_height, + textLength=char_width * len(text), + clip_path=f"url(#{unique_id}-line-{y})", + ) + ) + x += cell_len(text) + + line_offsets = [line_no * line_height + 1.5 for line_no in range(y)] + lines = "\n".join( + f""" + {make_tag("rect", x=0, y=offset, width=char_width * width, height=line_height + 0.25)} + """ + for line_no, offset in enumerate(line_offsets) + ) + + styles = "\n".join( + f".{unique_id}-r{rule_no} {{ {css} }}" for css, rule_no in classes.items() + ) + backgrounds = "".join(text_backgrounds) + matrix = "".join(text_group) + + terminal_width = ceil(width * char_width + padding_width) + terminal_height = (y + 1) * line_height + padding_height + chrome = make_tag( + "rect", + fill=_theme.background_color.hex, + stroke="rgba(255,255,255,0.35)", + stroke_width="1", + x=margin_left, + y=margin_top, + width=terminal_width, + height=terminal_height, + rx=8, + ) + + title_color = _theme.foreground_color.hex + if title: + chrome += make_tag( + "text", + escape_text(title), + _class=f"{unique_id}-title", + fill=title_color, + text_anchor="middle", + x=terminal_width // 2, + y=margin_top + char_height + 6, + ) + chrome += f""" + + + + + + """ + + svg = code_format.format( + unique_id=unique_id, + char_width=char_width, + char_height=char_height, + line_height=line_height, + terminal_width=char_width * width - 1, + terminal_height=(y + 1) * line_height - 1, + width=terminal_width + margin_width, + height=terminal_height + margin_height, + terminal_x=margin_left + padding_left, + terminal_y=margin_top + padding_top, + styles=styles, + chrome=chrome, + backgrounds=backgrounds, + matrix=matrix, + lines=lines, + ) + return svg + + def save_svg( + self, + path: str, + *, + title: str = "Rich", + theme: Optional[TerminalTheme] = None, + clear: bool = True, + code_format: str = CONSOLE_SVG_FORMAT, + font_aspect_ratio: float = 0.61, + unique_id: Optional[str] = None, + ) -> None: + """Generate an SVG file from the console contents (requires record=True in Console constructor). + + Args: + path (str): The path to write the SVG to. + title (str, optional): The title of the tab in the output image + theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal + clear (bool, optional): Clear record buffer after exporting. Defaults to ``True`` + code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables + into the string in order to form the final SVG output. The default template used and the variables + injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable. + font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format`` + string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font). + If you aren't specifying a different font inside ``code_format``, you probably don't need this. + unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node + ids). If not set, this defaults to a computed value based on the recorded content. + """ + svg = self.export_svg( + title=title, + theme=theme, + clear=clear, + code_format=code_format, + font_aspect_ratio=font_aspect_ratio, + unique_id=unique_id, + ) + with open(path, "w", encoding="utf-8") as write_file: + write_file.write(svg) + + +def _svg_hash(svg_main_code: str) -> str: + """Returns a unique hash for the given SVG main code. + + Args: + svg_main_code (str): The content we're going to inject in the SVG envelope. + + Returns: + str: a hash of the given content + """ + return str(zlib.adler32(svg_main_code.encode())) + + +if __name__ == "__main__": # pragma: no cover + console = Console(record=True) + + console.log( + "JSONRPC [i]request[/i]", + 5, + 1.3, + True, + False, + None, + { + "jsonrpc": "2.0", + "method": "subtract", + "params": {"minuend": 42, "subtrahend": 23}, + "id": 3, + }, + ) + + console.log("Hello, World!", "{'a': 1}", repr(console)) + + console.print( + { + "name": None, + "empty": [], + "quiz": { + "sport": { + "answered": True, + "q1": { + "question": "Which one is correct team name in NBA?", + "options": [ + "New York Bulls", + "Los Angeles Kings", + "Golden State Warriors", + "Huston Rocket", + ], + "answer": "Huston Rocket", + }, + }, + "maths": { + "answered": False, + "q1": { + "question": "5 + 7 = ?", + "options": [10, 11, 12, 13], + "answer": 12, + }, + "q2": { + "question": "12 - 8 = ?", + "options": [1, 2, 3, 4], + "answer": 4, + }, + }, + }, + } + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/constrain.py b/data/miniconda3/lib/python3.13/site-packages/rich/constrain.py new file mode 100644 index 0000000000000000000000000000000000000000..65fdf56342e8b5b8e181914881025231684e1871 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/constrain.py @@ -0,0 +1,37 @@ +from typing import Optional, TYPE_CHECKING + +from .jupyter import JupyterMixin +from .measure import Measurement + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderableType, RenderResult + + +class Constrain(JupyterMixin): + """Constrain the width of a renderable to a given number of characters. + + Args: + renderable (RenderableType): A renderable object. + width (int, optional): The maximum width (in characters) to render. Defaults to 80. + """ + + def __init__(self, renderable: "RenderableType", width: Optional[int] = 80) -> None: + self.renderable = renderable + self.width = width + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + if self.width is None: + yield self.renderable + else: + child_options = options.update_width(min(self.width, options.max_width)) + yield from console.render(self.renderable, child_options) + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> "Measurement": + if self.width is not None: + options = options.update_width(self.width) + measurement = Measurement.get(console, options, self.renderable) + return measurement diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/containers.py b/data/miniconda3/lib/python3.13/site-packages/rich/containers.py new file mode 100644 index 0000000000000000000000000000000000000000..901ff8ba6ea0836481a015ed5c627889cc416c03 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/containers.py @@ -0,0 +1,167 @@ +from itertools import zip_longest +from typing import ( + TYPE_CHECKING, + Iterable, + Iterator, + List, + Optional, + TypeVar, + Union, + overload, +) + +if TYPE_CHECKING: + from .console import ( + Console, + ConsoleOptions, + JustifyMethod, + OverflowMethod, + RenderResult, + RenderableType, + ) + from .text import Text + +from .cells import cell_len +from .measure import Measurement + +T = TypeVar("T") + + +class Renderables: + """A list subclass which renders its contents to the console.""" + + def __init__( + self, renderables: Optional[Iterable["RenderableType"]] = None + ) -> None: + self._renderables: List["RenderableType"] = ( + list(renderables) if renderables is not None else [] + ) + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + """Console render method to insert line-breaks.""" + yield from self._renderables + + def __rich_measure__( + self, console: "Console", options: "ConsoleOptions" + ) -> "Measurement": + dimensions = [ + Measurement.get(console, options, renderable) + for renderable in self._renderables + ] + if not dimensions: + return Measurement(1, 1) + _min = max(dimension.minimum for dimension in dimensions) + _max = max(dimension.maximum for dimension in dimensions) + return Measurement(_min, _max) + + def append(self, renderable: "RenderableType") -> None: + self._renderables.append(renderable) + + def __iter__(self) -> Iterable["RenderableType"]: + return iter(self._renderables) + + +class Lines: + """A list subclass which can render to the console.""" + + def __init__(self, lines: Iterable["Text"] = ()) -> None: + self._lines: List["Text"] = list(lines) + + def __repr__(self) -> str: + return f"Lines({self._lines!r})" + + def __iter__(self) -> Iterator["Text"]: + return iter(self._lines) + + @overload + def __getitem__(self, index: int) -> "Text": + ... + + @overload + def __getitem__(self, index: slice) -> List["Text"]: + ... + + def __getitem__(self, index: Union[slice, int]) -> Union["Text", List["Text"]]: + return self._lines[index] + + def __setitem__(self, index: int, value: "Text") -> "Lines": + self._lines[index] = value + return self + + def __len__(self) -> int: + return self._lines.__len__() + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + """Console render method to insert line-breaks.""" + yield from self._lines + + def append(self, line: "Text") -> None: + self._lines.append(line) + + def extend(self, lines: Iterable["Text"]) -> None: + self._lines.extend(lines) + + def pop(self, index: int = -1) -> "Text": + return self._lines.pop(index) + + def justify( + self, + console: "Console", + width: int, + justify: "JustifyMethod" = "left", + overflow: "OverflowMethod" = "fold", + ) -> None: + """Justify and overflow text to a given width. + + Args: + console (Console): Console instance. + width (int): Number of cells available per line. + justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left". + overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipsis". Defaults to "fold". + + """ + from .text import Text + + if justify == "left": + for line in self._lines: + line.truncate(width, overflow=overflow, pad=True) + elif justify == "center": + for line in self._lines: + line.rstrip() + line.truncate(width, overflow=overflow) + line.pad_left((width - cell_len(line.plain)) // 2) + line.pad_right(width - cell_len(line.plain)) + elif justify == "right": + for line in self._lines: + line.rstrip() + line.truncate(width, overflow=overflow) + line.pad_left(width - cell_len(line.plain)) + elif justify == "full": + for line_index, line in enumerate(self._lines): + if line_index == len(self._lines) - 1: + break + words = line.split(" ") + words_size = sum(cell_len(word.plain) for word in words) + num_spaces = len(words) - 1 + spaces = [1 for _ in range(num_spaces)] + index = 0 + if spaces: + while words_size + num_spaces < width: + spaces[len(spaces) - index - 1] += 1 + num_spaces += 1 + index = (index + 1) % len(spaces) + tokens: List[Text] = [] + for index, (word, next_word) in enumerate( + zip_longest(words, words[1:]) + ): + tokens.append(word) + if index < len(spaces): + style = word.get_style_at_offset(console, -1) + next_style = next_word.get_style_at_offset(console, 0) + space_style = style if style == next_style else line.style + tokens.append(Text(" " * spaces[index], style=space_style)) + self[line_index] = Text("").join(tokens) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/control.py b/data/miniconda3/lib/python3.13/site-packages/rich/control.py new file mode 100644 index 0000000000000000000000000000000000000000..248b0f595a5f101eb43c62ccc090729271be3c43 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/control.py @@ -0,0 +1,219 @@ +import time +from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union, Final + +from .segment import ControlCode, ControlType, Segment + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderResult + +STRIP_CONTROL_CODES: Final = [ + 7, # Bell + 8, # Backspace + 11, # Vertical tab + 12, # Form feed + 13, # Carriage return +] +_CONTROL_STRIP_TRANSLATE: Final = { + _codepoint: None for _codepoint in STRIP_CONTROL_CODES +} + +CONTROL_ESCAPE: Final = { + 7: "\\a", + 8: "\\b", + 11: "\\v", + 12: "\\f", + 13: "\\r", +} + +CONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = { + ControlType.BELL: lambda: "\x07", + ControlType.CARRIAGE_RETURN: lambda: "\r", + ControlType.HOME: lambda: "\x1b[H", + ControlType.CLEAR: lambda: "\x1b[2J", + ControlType.ENABLE_ALT_SCREEN: lambda: "\x1b[?1049h", + ControlType.DISABLE_ALT_SCREEN: lambda: "\x1b[?1049l", + ControlType.SHOW_CURSOR: lambda: "\x1b[?25h", + ControlType.HIDE_CURSOR: lambda: "\x1b[?25l", + ControlType.CURSOR_UP: lambda param: f"\x1b[{param}A", + ControlType.CURSOR_DOWN: lambda param: f"\x1b[{param}B", + ControlType.CURSOR_FORWARD: lambda param: f"\x1b[{param}C", + ControlType.CURSOR_BACKWARD: lambda param: f"\x1b[{param}D", + ControlType.CURSOR_MOVE_TO_COLUMN: lambda param: f"\x1b[{param+1}G", + ControlType.ERASE_IN_LINE: lambda param: f"\x1b[{param}K", + ControlType.CURSOR_MOVE_TO: lambda x, y: f"\x1b[{y+1};{x+1}H", + ControlType.SET_WINDOW_TITLE: lambda title: f"\x1b]0;{title}\x07", +} + + +class Control: + """A renderable that inserts a control code (non printable but may move cursor). + + Args: + *codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a + tuple of ControlType and an integer parameter + """ + + __slots__ = ["segment"] + + def __init__(self, *codes: Union[ControlType, ControlCode]) -> None: + control_codes: List[ControlCode] = [ + (code,) if isinstance(code, ControlType) else code for code in codes + ] + _format_map = CONTROL_CODES_FORMAT + rendered_codes = "".join( + _format_map[code](*parameters) for code, *parameters in control_codes + ) + self.segment = Segment(rendered_codes, None, control_codes) + + @classmethod + def bell(cls) -> "Control": + """Ring the 'bell'.""" + return cls(ControlType.BELL) + + @classmethod + def home(cls) -> "Control": + """Move cursor to 'home' position.""" + return cls(ControlType.HOME) + + @classmethod + def move(cls, x: int = 0, y: int = 0) -> "Control": + """Move cursor relative to current position. + + Args: + x (int): X offset. + y (int): Y offset. + + Returns: + ~Control: Control object. + + """ + + def get_codes() -> Iterable[ControlCode]: + control = ControlType + if x: + yield ( + control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD, + abs(x), + ) + if y: + yield ( + control.CURSOR_DOWN if y > 0 else control.CURSOR_UP, + abs(y), + ) + + control = cls(*get_codes()) + return control + + @classmethod + def move_to_column(cls, x: int, y: int = 0) -> "Control": + """Move to the given column, optionally add offset to row. + + Returns: + x (int): absolute x (column) + y (int): optional y offset (row) + + Returns: + ~Control: Control object. + """ + + return ( + cls( + (ControlType.CURSOR_MOVE_TO_COLUMN, x), + ( + ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP, + abs(y), + ), + ) + if y + else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x)) + ) + + @classmethod + def move_to(cls, x: int, y: int) -> "Control": + """Move cursor to absolute position. + + Args: + x (int): x offset (column) + y (int): y offset (row) + + Returns: + ~Control: Control object. + """ + return cls((ControlType.CURSOR_MOVE_TO, x, y)) + + @classmethod + def clear(cls) -> "Control": + """Clear the screen.""" + return cls(ControlType.CLEAR) + + @classmethod + def show_cursor(cls, show: bool) -> "Control": + """Show or hide the cursor.""" + return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR) + + @classmethod + def alt_screen(cls, enable: bool) -> "Control": + """Enable or disable alt screen.""" + if enable: + return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME) + else: + return cls(ControlType.DISABLE_ALT_SCREEN) + + @classmethod + def title(cls, title: str) -> "Control": + """Set the terminal window title + + Args: + title (str): The new terminal window title + """ + return cls((ControlType.SET_WINDOW_TITLE, title)) + + def __str__(self) -> str: + return self.segment.text + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + if self.segment.text: + yield self.segment + + +def strip_control_codes( + text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE +) -> str: + """Remove control codes from text. + + Args: + text (str): A string possibly contain control codes. + + Returns: + str: String with control codes removed. + """ + return text.translate(_translate_table) + + +def escape_control_codes( + text: str, + _translate_table: Dict[int, str] = CONTROL_ESCAPE, +) -> str: + """Replace control codes with their "escaped" equivalent in the given text. + (e.g. "\b" becomes "\\b") + + Args: + text (str): A string possibly containing control codes. + + Returns: + str: String with control codes replaced with their escaped version. + """ + return text.translate(_translate_table) + + +if __name__ == "__main__": # pragma: no cover + from rich.console import Console + + console = Console() + console.print("Look at the title of your terminal window ^") + # console.print(Control((ControlType.SET_WINDOW_TITLE, "Hello, world!"))) + for i in range(10): + console.set_window_title("🚀 Loading" + "." * i) + time.sleep(0.5) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/default_styles.py b/data/miniconda3/lib/python3.13/site-packages/rich/default_styles.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0ad83a29f0c65b58e501ad4f5ed10f0830d0a1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/default_styles.py @@ -0,0 +1,193 @@ +from typing import Dict + +from .style import Style + +DEFAULT_STYLES: Dict[str, Style] = { + "none": Style.null(), + "reset": Style( + color="default", + bgcolor="default", + dim=False, + bold=False, + italic=False, + underline=False, + blink=False, + blink2=False, + reverse=False, + conceal=False, + strike=False, + ), + "dim": Style(dim=True), + "bright": Style(dim=False), + "bold": Style(bold=True), + "strong": Style(bold=True), + "code": Style(reverse=True, bold=True), + "italic": Style(italic=True), + "emphasize": Style(italic=True), + "underline": Style(underline=True), + "blink": Style(blink=True), + "blink2": Style(blink2=True), + "reverse": Style(reverse=True), + "strike": Style(strike=True), + "black": Style(color="black"), + "red": Style(color="red"), + "green": Style(color="green"), + "yellow": Style(color="yellow"), + "magenta": Style(color="magenta"), + "cyan": Style(color="cyan"), + "white": Style(color="white"), + "inspect.attr": Style(color="yellow", italic=True), + "inspect.attr.dunder": Style(color="yellow", italic=True, dim=True), + "inspect.callable": Style(bold=True, color="red"), + "inspect.async_def": Style(italic=True, color="bright_cyan"), + "inspect.def": Style(italic=True, color="bright_cyan"), + "inspect.class": Style(italic=True, color="bright_cyan"), + "inspect.error": Style(bold=True, color="red"), + "inspect.equals": Style(), + "inspect.help": Style(color="cyan"), + "inspect.doc": Style(dim=True), + "inspect.value.border": Style(color="green"), + "live.ellipsis": Style(bold=True, color="red"), + "layout.tree.row": Style(dim=False, color="red"), + "layout.tree.column": Style(dim=False, color="blue"), + "logging.keyword": Style(bold=True, color="yellow"), + "logging.level.notset": Style(dim=True), + "logging.level.debug": Style(color="green"), + "logging.level.info": Style(color="blue"), + "logging.level.warning": Style(color="yellow"), + "logging.level.error": Style(color="red", bold=True), + "logging.level.critical": Style(color="red", bold=True, reverse=True), + "log.level": Style.null(), + "log.time": Style(color="cyan", dim=True), + "log.message": Style.null(), + "log.path": Style(dim=True), + "repr.ellipsis": Style(color="yellow"), + "repr.indent": Style(color="green", dim=True), + "repr.error": Style(color="red", bold=True), + "repr.str": Style(color="green", italic=False, bold=False), + "repr.brace": Style(bold=True), + "repr.comma": Style(bold=True), + "repr.ipv4": Style(bold=True, color="bright_green"), + "repr.ipv6": Style(bold=True, color="bright_green"), + "repr.eui48": Style(bold=True, color="bright_green"), + "repr.eui64": Style(bold=True, color="bright_green"), + "repr.tag_start": Style(bold=True), + "repr.tag_name": Style(color="bright_magenta", bold=True), + "repr.tag_contents": Style(color="default"), + "repr.tag_end": Style(bold=True), + "repr.attrib_name": Style(color="yellow", italic=False), + "repr.attrib_equal": Style(bold=True), + "repr.attrib_value": Style(color="magenta", italic=False), + "repr.number": Style(color="cyan", bold=True, italic=False), + "repr.number_complex": Style(color="cyan", bold=True, italic=False), # same + "repr.bool_true": Style(color="bright_green", italic=True), + "repr.bool_false": Style(color="bright_red", italic=True), + "repr.none": Style(color="magenta", italic=True), + "repr.url": Style(underline=True, color="bright_blue", italic=False, bold=False), + "repr.uuid": Style(color="bright_yellow", bold=False), + "repr.call": Style(color="magenta", bold=True), + "repr.path": Style(color="magenta"), + "repr.filename": Style(color="bright_magenta"), + "rule.line": Style(color="bright_green"), + "rule.text": Style.null(), + "json.brace": Style(bold=True), + "json.bool_true": Style(color="bright_green", italic=True), + "json.bool_false": Style(color="bright_red", italic=True), + "json.null": Style(color="magenta", italic=True), + "json.number": Style(color="cyan", bold=True, italic=False), + "json.str": Style(color="green", italic=False, bold=False), + "json.key": Style(color="blue", bold=True), + "prompt": Style.null(), + "prompt.choices": Style(color="magenta", bold=True), + "prompt.default": Style(color="cyan", bold=True), + "prompt.invalid": Style(color="red"), + "prompt.invalid.choice": Style(color="red"), + "pretty": Style.null(), + "scope.border": Style(color="blue"), + "scope.key": Style(color="yellow", italic=True), + "scope.key.special": Style(color="yellow", italic=True, dim=True), + "scope.equals": Style(color="red"), + "table.header": Style(bold=True), + "table.footer": Style(bold=True), + "table.cell": Style.null(), + "table.title": Style(italic=True), + "table.caption": Style(italic=True, dim=True), + "traceback.error": Style(color="red", italic=True), + "traceback.border.syntax_error": Style(color="bright_red"), + "traceback.border": Style(color="red"), + "traceback.text": Style.null(), + "traceback.title": Style(color="red", bold=True), + "traceback.exc_type": Style(color="bright_red", bold=True), + "traceback.exc_value": Style.null(), + "traceback.offset": Style(color="bright_red", bold=True), + "traceback.error_range": Style(underline=True, bold=True), + "traceback.note": Style(color="green", bold=True), + "traceback.group.border": Style(color="magenta"), + "bar.back": Style(color="grey23"), + "bar.complete": Style(color="rgb(249,38,114)"), + "bar.finished": Style(color="rgb(114,156,31)"), + "bar.pulse": Style(color="rgb(249,38,114)"), + "progress.description": Style.null(), + "progress.filesize": Style(color="green"), + "progress.filesize.total": Style(color="green"), + "progress.download": Style(color="green"), + "progress.elapsed": Style(color="yellow"), + "progress.percentage": Style(color="magenta"), + "progress.remaining": Style(color="cyan"), + "progress.data.speed": Style(color="red"), + "progress.spinner": Style(color="green"), + "status.spinner": Style(color="green"), + "tree": Style(), + "tree.line": Style(), + "markdown.paragraph": Style(), + "markdown.text": Style(), + "markdown.em": Style(italic=True), + "markdown.emph": Style(italic=True), # For commonmark backwards compatibility + "markdown.strong": Style(bold=True), + "markdown.code": Style(bold=True, color="cyan", bgcolor="black"), + "markdown.code_block": Style(color="cyan", bgcolor="black"), + "markdown.block_quote": Style(color="magenta"), + "markdown.list": Style(color="cyan"), + "markdown.item": Style(), + "markdown.item.bullet": Style(color="yellow", bold=True), + "markdown.item.number": Style(color="yellow", bold=True), + "markdown.hr": Style(color="yellow"), + "markdown.h1.border": Style(), + "markdown.h1": Style(bold=True), + "markdown.h2": Style(bold=True, underline=True), + "markdown.h3": Style(bold=True), + "markdown.h4": Style(bold=True, dim=True), + "markdown.h5": Style(underline=True), + "markdown.h6": Style(italic=True), + "markdown.h7": Style(italic=True, dim=True), + "markdown.link": Style(color="bright_blue"), + "markdown.link_url": Style(color="blue", underline=True), + "markdown.s": Style(strike=True), + "iso8601.date": Style(color="blue"), + "iso8601.time": Style(color="magenta"), + "iso8601.timezone": Style(color="yellow"), +} + + +if __name__ == "__main__": # pragma: no cover + import argparse + import io + + from rich.console import Console + from rich.table import Table + from rich.text import Text + + parser = argparse.ArgumentParser() + parser.add_argument("--html", action="store_true", help="Export as HTML table") + args = parser.parse_args() + html: bool = args.html + console = Console(record=True, width=70, file=io.StringIO()) if html else Console() + + table = Table("Name", "Styling") + + for style_name, style in DEFAULT_STYLES.items(): + table.add_row(Text(style_name, style=style), str(style)) + + console.print(table) + if html: + print(console.export_html(inline_styles=True)) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/diagnose.py b/data/miniconda3/lib/python3.13/site-packages/rich/diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5ff3ec3299994c61171859854c16242468ed8b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/diagnose.py @@ -0,0 +1,39 @@ +import os +import platform + +from rich import inspect +from rich.console import Console, get_windows_console_features +from rich.panel import Panel +from rich.pretty import Pretty + + +def report() -> None: # pragma: no cover + """Print a report to the terminal with debugging information""" + console = Console() + inspect(console) + features = get_windows_console_features() + inspect(features) + + env_names = ( + "CLICOLOR", + "COLORTERM", + "COLUMNS", + "JPY_PARENT_PID", + "JUPYTER_COLUMNS", + "JUPYTER_LINES", + "LINES", + "NO_COLOR", + "TERM_PROGRAM", + "TERM", + "TTY_COMPATIBLE", + "TTY_INTERACTIVE", + "VSCODE_VERBOSE_LOGGING", + ) + env = {name: os.getenv(name) for name in env_names} + console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables")) + + console.print(f'platform="{platform.system()}"') + + +if __name__ == "__main__": # pragma: no cover + report() diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/emoji.py b/data/miniconda3/lib/python3.13/site-packages/rich/emoji.py new file mode 100644 index 0000000000000000000000000000000000000000..9433e6fb3ffb1f2e3f1f868131f82525d0e455db --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/emoji.py @@ -0,0 +1,91 @@ +import sys +from typing import TYPE_CHECKING, Optional, Union, Literal + +from .jupyter import JupyterMixin +from .segment import Segment +from .style import Style +from ._emoji_codes import EMOJI +from ._emoji_replace import _emoji_replace + + +if TYPE_CHECKING: + from .console import Console, ConsoleOptions, RenderResult + + +EmojiVariant = Literal["emoji", "text"] + + +class NoEmoji(Exception): + """No emoji by that name.""" + + +class Emoji(JupyterMixin): + __slots__ = ["name", "style", "_char", "variant"] + + VARIANTS = {"text": "\uFE0E", "emoji": "\uFE0F"} + + def __init__( + self, + name: str, + style: Union[str, Style] = "none", + variant: Optional[EmojiVariant] = None, + ) -> None: + """A single emoji character. + + Args: + name (str): Name of emoji. + style (Union[str, Style], optional): Optional style. Defaults to None. + + Raises: + NoEmoji: If the emoji doesn't exist. + """ + self.name = name + self.style = style + self.variant = variant + try: + self._char = EMOJI[name] + except KeyError: + raise NoEmoji(f"No emoji called {name!r}") + if variant is not None: + self._char += self.VARIANTS.get(variant, "") + + @classmethod + def replace(cls, text: str) -> str: + """Replace emoji markup with corresponding unicode characters. + + Args: + text (str): A string with emojis codes, e.g. "Hello :smiley:!" + + Returns: + str: A string with emoji codes replaces with actual emoji. + """ + return _emoji_replace(text) + + def __repr__(self) -> str: + return f"" + + def __str__(self) -> str: + return self._char + + def __rich_console__( + self, console: "Console", options: "ConsoleOptions" + ) -> "RenderResult": + yield Segment(self._char, console.get_style(self.style)) + + +if __name__ == "__main__": # pragma: no cover + import sys + + from rich.columns import Columns + from rich.console import Console + + console = Console(record=True) + + columns = Columns( + (f":{name}: {name}" for name in sorted(EMOJI.keys()) if "\u200D" not in name), + column_first=True, + ) + + console.print(columns) + if len(sys.argv) > 1: + console.save_html(sys.argv[1]) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/errors.py b/data/miniconda3/lib/python3.13/site-packages/rich/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcbe53ef59373c608e62ea285536f8b22b47ecb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/errors.py @@ -0,0 +1,34 @@ +class ConsoleError(Exception): + """An error in console operation.""" + + +class StyleError(Exception): + """An error in styles.""" + + +class StyleSyntaxError(ConsoleError): + """Style was badly formatted.""" + + +class MissingStyle(StyleError): + """No such style.""" + + +class StyleStackError(ConsoleError): + """Style stack is invalid.""" + + +class NotRenderableError(ConsoleError): + """Object is not renderable.""" + + +class MarkupError(ConsoleError): + """Markup was badly formatted.""" + + +class LiveError(ConsoleError): + """Error related to Live display.""" + + +class NoAltScreen(ConsoleError): + """Alt screen mode was required.""" diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/file_proxy.py b/data/miniconda3/lib/python3.13/site-packages/rich/file_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0b0da6c2a62b2b1468c35ddd69f1bbb9b91aa8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/file_proxy.py @@ -0,0 +1,57 @@ +import io +from typing import IO, TYPE_CHECKING, Any, List + +from .ansi import AnsiDecoder +from .text import Text + +if TYPE_CHECKING: + from .console import Console + + +class FileProxy(io.TextIOBase): + """Wraps a file (e.g. sys.stdout) and redirects writes to a console.""" + + def __init__(self, console: "Console", file: IO[str]) -> None: + self.__console = console + self.__file = file + self.__buffer: List[str] = [] + self.__ansi_decoder = AnsiDecoder() + + @property + def rich_proxied_file(self) -> IO[str]: + """Get proxied file.""" + return self.__file + + def __getattr__(self, name: str) -> Any: + return getattr(self.__file, name) + + def write(self, text: str) -> int: + if not isinstance(text, str): + raise TypeError(f"write() argument must be str, not {type(text).__name__}") + buffer = self.__buffer + lines: List[str] = [] + while text: + line, new_line, text = text.partition("\n") + if new_line: + lines.append("".join(buffer) + line) + buffer.clear() + else: + buffer.append(line) + break + if lines: + console = self.__console + with console: + output = Text("\n").join( + self.__ansi_decoder.decode_line(line) for line in lines + ) + console.print(output) + return len(text) + + def flush(self) -> None: + output = "".join(self.__buffer) + if output: + self.__console.print(output) + del self.__buffer[:] + + def fileno(self) -> int: + return self.__file.fileno() diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/filesize.py b/data/miniconda3/lib/python3.13/site-packages/rich/filesize.py new file mode 100644 index 0000000000000000000000000000000000000000..83bc9118d2bdb8983f863063687c2ea394a9abb1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/filesize.py @@ -0,0 +1,88 @@ +"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2 + +The functions declared in this module should cover the different +use cases needed to generate a string representation of a file size +using several different units. Since there are many standards regarding +file size units, three different functions have been implemented. + +See Also: + * `Wikipedia: Binary prefix `_ + +""" + +__all__ = ["decimal"] + +from typing import Iterable, List, Optional, Tuple + + +def _to_str( + size: int, + suffixes: Iterable[str], + base: int, + *, + precision: Optional[int] = 1, + separator: Optional[str] = " ", +) -> str: + if size == 1: + return "1 byte" + elif size < base: + return f"{size:,} bytes" + + for i, suffix in enumerate(suffixes, 2): # noqa: B007 + unit = base**i + if size < unit: + break + return "{:,.{precision}f}{separator}{}".format( + (base * size / unit), + suffix, + precision=precision, + separator=separator, + ) + + +def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]: + """Pick a suffix and base for the given size.""" + for i, suffix in enumerate(suffixes): + unit = base**i + if size < unit * base: + break + return unit, suffix + + +def decimal( + size: int, + *, + precision: Optional[int] = 1, + separator: Optional[str] = " ", +) -> str: + """Convert a filesize in to a string (powers of 1000, SI prefixes). + + In this convention, ``1000 B = 1 kB``. + + This is typically the format used to advertise the storage + capacity of USB flash drives and the like (*256 MB* meaning + actually a storage capacity of more than *256 000 000 B*), + or used by **Mac OS X** since v10.6 to report file sizes. + + Arguments: + int (size): A file size. + int (precision): The number of decimal places to include (default = 1). + str (separator): The string to separate the value from the units (default = " "). + + Returns: + `str`: A string containing a abbreviated file size and units. + + Example: + >>> filesize.decimal(30000) + '30.0 kB' + >>> filesize.decimal(30000, precision=2, separator="") + '30.00kB' + + """ + return _to_str( + size, + ("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"), + 1000, + precision=precision, + separator=separator, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/rich/highlighter.py b/data/miniconda3/lib/python3.13/site-packages/rich/highlighter.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c462e2b632a268ecfb4772320206b94a3d859c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rich/highlighter.py @@ -0,0 +1,232 @@ +import re +from abc import ABC, abstractmethod +from typing import List, Union + +from .text import Span, Text + + +def _combine_regex(*regexes: str) -> str: + """Combine a number of regexes in to a single regex. + + Returns: + str: New regex with all regexes ORed together. + """ + return "|".join(regexes) + + +class Highlighter(ABC): + """Abstract base class for highlighters.""" + + def __call__(self, text: Union[str, Text]) -> Text: + """Highlight a str or Text instance. + + Args: + text (Union[str, ~Text]): Text to highlight. + + Raises: + TypeError: If not called with text or str. + + Returns: + Text: A test instance with highlighting applied. + """ + if isinstance(text, str): + highlight_text = Text(text) + elif isinstance(text, Text): + highlight_text = text.copy() + else: + raise TypeError(f"str or Text instance required, not {text!r}") + self.highlight(highlight_text) + return highlight_text + + @abstractmethod + def highlight(self, text: Text) -> None: + """Apply highlighting in place to text. + + Args: + text (~Text): A text object highlight. + """ + + +class NullHighlighter(Highlighter): + """A highlighter object that doesn't highlight. + + May be used to disable highlighting entirely. + + """ + + def highlight(self, text: Text) -> None: + """Nothing to do""" + + +class RegexHighlighter(Highlighter): + """Applies highlighting from a list of regular expressions.""" + + highlights: List[str] = [] + base_style: str = "" + + def highlight(self, text: Text) -> None: + """Highlight :class:`rich.text.Text` using regular expressions. + + Args: + text (~Text): Text to highlighted. + + """ + + highlight_regex = text.highlight_regex + for re_highlight in self.highlights: + highlight_regex(re_highlight, style_prefix=self.base_style) + + +class ReprHighlighter(RegexHighlighter): + """Highlights the text typically produced from ``__repr__`` methods.""" + + base_style = "repr." + highlights = [ + r"(?P<)(?P[-\w.:|]*)(?P[\w\W]*)(?P>)", + r'(?P[\w_]{1,50})=(?P"?[\w_]+"?)?', + r"(?P[][{}()])", + _combine_regex( + r"(?P[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})", + r"(?P([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})", + r"(?P(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})", + r"(?P(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})", + r"(?P[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})", + r"(?P[\w.]*?)\(", + r"\b(?PTrue)\b|\b(?PFalse)\b|\b(?PNone)\b", + r"(?P\.\.\.)", + r"(?P(?(?\B(/[-\w._+]+)*\/)(?P[-\w._+]*)?", + r"(?b?'''.*?(?(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~@]*)", + ), + ] + + +class JSONHighlighter(RegexHighlighter): + """Highlights JSON""" + + # Captures the start and end of JSON strings, handling escaped quotes + JSON_STR = r"(?b?\".*?(?[\{\[\(\)\]\}])", + r"\b(?Ptrue)\b|\b(?Pfalse)\b|\b(?Pnull)\b", + r"(?P(? None: + super().highlight(text) + + # Additional work to handle highlighting JSON keys + plain = text.plain + append = text.spans.append + whitespace = self.JSON_WHITESPACE + for match in re.finditer(self.JSON_STR, plain): + start, end = match.span() + cursor = end + while cursor < len(plain): + char = plain[cursor] + cursor += 1 + if char == ":": + append(Span(start, end, "json.key")) + elif char in whitespace: + continue + break + + +class ISO8601Highlighter(RegexHighlighter): + """Highlights the ISO8601 date time strings. + Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html + """ + + base_style = "iso8601." + highlights = [ + # + # Dates + # + # Calendar month (e.g. 2008-08). The hyphen is required + r"^(?P[0-9]{4})-(?P1[0-2]|0[1-9])$", + # Calendar date w/o hyphens (e.g. 20080830) + r"^(?P(?P[0-9]{4})(?P1[0-2]|0[1-9])(?P3[01]|0[1-9]|[12][0-9]))$", + # Ordinal date (e.g. 2008-243). The hyphen is optional + r"^(?P(?P[0-9]{4})-?(?P36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$", + # + # Weeks + # + # Week of the year (e.g., 2008-W35). The hyphen is optional + r"^(?P(?P[0-9]{4})-?W(?P5[0-3]|[1-4][0-9]|0[1-9]))$", + # Week date (e.g., 2008-W35-6). The hyphens are optional + r"^(?P(?P[0-9]{4})-?W(?P5[0-3]|[1-4][0-9]|0[1-9])-?(?P[1-7]))$", + # + # Times + # + # Hours and minutes (e.g., 17:21). The colon is optional + r"^(?P